Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
Pruebe el código de error de una excepción personalizada con JUnit 4

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(); } }
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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í:

  • no desea esperar esa excepción específica, ya que desea verificar algunas propiedades de la misma
  • sabe que desea ingresar a ese bloque catch específico; por lo tanto, simplemente falla cuando la llamada no se lanza
  • no necesita ninguna otra verificación: cuando el método arroja cualquier otra excepción, JUnit lo informará como error de todos modos
about 4 years ago · Santiago Trujillo Report

0

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

about 4 years ago · Santiago Trujillo Report

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!