Me gustaría probar el código de retorno de una excepción. Aquí está mi código de producción:
class A { try { something... } catch (Exception e) { throw new MyExceptionClass(INTERNAL_ERROR_CODE, e); } }Y la excepción correspondiente:
class MyExceptionClass extends ... { private errorCode; public MyExceptionClass(int errorCode){ this.errorCode = errorCode; } public getErrorCode(){ return this.errorCode; } }Mi prueba unitaria:
public class AUnitTests{ @Rule public ExpectedException thrown= ExpectedException.none(); @Test (expected = MyExceptionClass.class, public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception { thrown.expect(MyExceptionClass.class); ??? expected return code INTERNAL_ERROR_CODE ??? something(); } }Simple:
@Test public void whenSerialNumberIsEmpty_shouldThrowSerialNumberInvalid() throws Exception { try{ whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode(); fail("should have thrown"); } catch (MyExceptionClass e){ assertThat(e.getCode(), is(MyExceptionClass.INTERNAL_ERROR_CODE)); }Eso es todo lo que necesitas aquí:
Puede verificarlo usando hamcres matchers siempre que thrown.expect esté sobrecargado para recibir Matcher
thrown.expect(CombinableMatcher.both( CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class))) .and(Matchers.hasProperty("errorCode", CoreMatchers.is(123))));Tenga en cuenta que deberá agregar Hamcrest Matcher a sus dependencias. Los núcleos emparejados que están incluidos en JUnit no son suficientes.
O si no quieres usar CombinableMatcher:
thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class)); thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123)); Además, no necesita una declaración (expected = MyExceptionClass.class) para la anotación @Test
Ampliando la respuesta de Sergii, puede limpiar esto aún más escribiendo un comparador personalizado.
import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public class CustomMatcher extends TypeSafeMatcher<CustomException> { public static CustomMatcher hasCode(String item) { return new CustomMatcher(item); } private String foundErrorCode; private final String expectedErrorCode; private CustomMatcher(String expectedErrorCode) { this.expectedErrorCode = expectedErrorCode; } @Override protected boolean matchesSafely(final CustomException exception) { foundErrorCode = exception.getErrorCode(); return foundErrorCode.equalsIgnoreCase(expectedErrorCode); } @Override public void describeTo(Description description) { description.appendValue(foundErrorCode) .appendText(" was not found instead of ") .appendValue(expectedErrorCode); } }El código de error se puede comprobar como:
import org.junit.rules.ExpectedException; public class MyObjTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void someMethodThatThrowsCustomException() { thrown.expect(CustomException.class); thrown.expect(CustomMatcher.hasCode("110501")); MyObj obj = new MyObj(); obj.methodThatThrowsCustomException(); } }Referencia: https://dzone.com/articles/testing-custom-exceptions