Cześć,
muszę przetestować klasę, która łapie wyjątki w aplikacji przy pomocy Springowej adnotacji @ControllerAdvice i @ExceptionHandler
metody wyglądają tak jak poniżej :
```
public class Response {
private String returnCode;
private String returnLabel;
public Response(String returnCode, String returnLabel) {
this.returnCode = returnCode;
this.returnLabel = returnLabel;
}
public String getReturnCode() {
return returnCode;
}
public void setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
public String getReturnLabel() {
return returnLabel;
}
public void setReturnLabel(String returnLabel) {
this.returnLabel = returnLabel;
}
@Override
public String toString() {
return "Response{" +
"returnCode='" + returnCode + '\'' +
", returnLabel='" + returnLabel + '\'' +
'}';
}
}
```
```
@ControllerAdvice
public class ExceptionHandler {
@org.springframework.web.bind.annotation.ExceptionHandler(value = SomeException.class)
public ResponseEntity<Response> handleSomeException(SomeException exception) {
Response resp = new Response();
resp.setReturnCode("SomeCode");
resp.setReturnLabel(exception.getMessage());
return new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
```
Jesli chodzi o testy jednostkowe to zrobiłem je w taki sposób jak poniżej ale jest problem z asercją. Nie do końca wiem jak to poprawnie przetestować z Mockito, żeby zwiększyć Coverage w projekcie
```
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner)
public class TestSuite {
private ExceptionHandler handler;
@Mock
private Response response;
@Test
public void testHandleSomeException() {
handler = new ExceptionHandler();
SomeException ex = new SomeException();
when(response.getReturnCode()).thenReturn("SomeCode");
when(response.getReturnLabel()).thenReturn(ex.getMessage());
assertEquals(handler.handleSomeException(ex), new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR));
}
}
```
Generalnie adviser działa ale nie wiem jak go dobrze przetestowac, obecnie mam
java.lang.AssertionError:
Expected :500 Internal Server Error, Response{returnCode='SomeCode', returnLabel='null'. - i tutaj też nie wiem dlaczego z ex.getMessage() idzie null w odpowiedzi ?
Actual : 500 Internal server error, response,{}
Będę bardzo wdzięczny za jakąś podpowiedź