import org.springframework.test.web.servlet.setup.mockmvcbuilders; < /p>
Code: Select all
@InjectMocks
private MyController controllerUnderTest;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
this.mockMvc = MockMvcBuilders
.standaloneSetup(controllerUnderTest)
.setHandlerExceptionResolvers(
ControllerTestHelper.createExceptionResolver()).build();
}
@Test
public void testData() throws Exception {
MyRequest mockRequest = mock(MyRequest.class);
when(myService.getRequest()).thenReturn(mockRequest);
when(myService.getFill(mockRequest)).thenThrow(new AnotherException("Test exception"));
mockMvc.perform(post("/api{market}/{language}", "invalidMarket", "invalidLanguage")
.andExpect(result -> {
Throwable ex = result.getResolvedException();
Throwable cause = ex.getCause();
assertNotNull(cause);
assertInstanceOf(CustomException.class, cause);
});
}
jakarta.servlet.servletException: Anforderungsverarbeitung fehlgeschlagen:
com.company.exceptions.customException: mycontroller.getData Ausnahme
gefangen: InvalidMarket /InvalidSluban < /p>
at
org.springframework.web.servlet.FrameWorkServlet.ProcessRequest(frameWorkServlet.java:1022)
at
org.springFrameWork.Web.Servlet.FrameWorklet.Dopost.dopost.dopost.dopost.dopost.dopost. Java: 914)
at jakarta.servlet.http.httpServlet.service (httpservlet.java:590) at
org.springframework.web.Servlet.FrameWERVLET.SERVICE(FRAMEWERVLET.JAVA:8885) & service(FrameWork.java.java:8885) & service(Frameworks.java.java:8885) & service(frameworks.java.java. p>
haben den Test durchgesehen und es wird in den Catch -Block eingegeben und diese CustOMexception ausgeworfen, was ich für diesen Test möchte. < /p>
Dies ist die Methode, die getestet wird. < /p>
Code: Select all
@PostMapping(value = "/api{market}/{language}")
public @ResponseBody MyResponse getData() throws AnotherException {
// removed lots of logic to keep it minimal
try {
MyResponse customResponse = myService.getFill(myService.getRequest(); // this fails as intended
return customResponse;
} catch (AnotherException ex) {
// I enter here as intended
throw new CustomException(errorMsg, ex);
}
}
Ich möchte, dass der Test bestätigt, dass ich CustOMException .
Code: Select all
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
public class ControllerTestHelper {
public static ExceptionHandlerExceptionResolver createExceptionResolver() {
ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {};
exceptionResolver.afterPropertiesSet();
return exceptionResolver;
}
}