Pokazywanie postów oznaczonych etykietą exception. Pokaż wszystkie posty
Pokazywanie postów oznaczonych etykietą exception. Pokaż wszystkie posty

2016-12-28

Optional.ofNullable().orElseThrow()

Przykład wykorzystania klasy Optional dostępnej od Java 8.

Bez Optionala
public void test(Task task) throws VerificationException {
    if (task.getCustomer() == null) {
        logger.error(CUSTOMER_NOT_FOUND);
        throw BmVerificationException.badRequest(CUSTOMER_NOT_FOUND);
    }
}
Z Optionalem
public void test(Task task) throws VerificationException {
    Optional.ofNullable(task.getCustomer()).orElseThrow(this::getException);
}

private VerificationException getException() {
    logger.error(CUSTOMER_NOT_FOUND);
    return VerificationException.badRequest(CUSTOMER_NOT_FOUND);
}

2016-12-27

AssertJ - assertThatExceptionOfType

Przykład alternatywnego testowania wyjątku - assertThatExceptionOfType
public class FooTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock
    private Validator validator;

    @InjectMocks
    private Foo sut;

    private HistoryRequest historyRequest;

    @Before
    public void setUp() throws Exception {
        historyRequest = new HistoryRequest();
    }

    @Test
    public void getHistoryThrowsExceptionDueToAccessDenied() throws Exception {
        when(validator.validate(historyRequest)).thenReturn(new Client());

        assertThatExceptionOfType(BloggerException.class)
                .isThrownBy(() -> sut.getHistory(historyRequest))
                .withMessage("Access denied");
    }
}