我有一个简单的 Spring Boot 应用程序,其中包含 Employee Controller ,如果过去的年份大于 2014 年,则返回员工姓名,如果它不小于 2014 年,那么我将抛出一个自定义异常并在异常处理程序中处理它。我想使用 powermock 对异常流进行单元测试,但我不知道该怎么做。我浏览了一些链接,但无法理解。
目前我得到 java.lang.IllegalArgumentException: WebApplicationContext is required。
雇员 Controller .java
@RestController
public class EmployeeController{
@GetMapping(value = "/employee/{joiningYear}",produces = MediaType.APPLICATION_JSON_VALUE)
public List<String> getEmployeeById(@PathVariable int joiningYear) throws YearViolationException {
if(joiningYear < 2014){
throw new YearViolationException("year should not be less than 2014");
}else{
// send all employee's names joined in that year
}
return null;
}
}
异常处理程序
@RestControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(value = { YearViolationException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiErrorResponse yearConstraintViolationExceptio(YearViolationException ex) {
return new ApiErrorResponse(400, 5001, ex.getMessage());
}
}
自定义异常
public class YearViolationException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public YearViolationException(String message) {
super(message);
}
}
Junit 到单元测试异常处理程序
@RunWith(PowerMockRunner.class)
@WebAppConfiguration
@SpringBootTest
public class ExceptionControllerTest {
@Autowired
private WebApplicationContext applicationContext;
private MockMvc mockMVC;
@Before
public void setUp() {
mockMVC = MockMvcBuilders.webAppContextSetup(applicationContext).build();
}
@Test
public void testhandleBanNotNumericException() throws Exception {
mockMVC.perform(get("/employee/2010").accept(MediaType.APPLICATION_JSON)).andDo(print())
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}
}
最佳答案
正如其他人所说,您根本不需要 mockMVC。如果您想测试 REST 端点,您需要的是 TestRestTemplate。
Runwith SpringRunner.class 和 WebEnvironment 设置一样重要。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class RestServiceApplicationTests {
private String baseUrl = "http://localhost:8090";
private String endpointToThrowException = "/employee/2010";
@Autowired
private TestRestTemplate testRestTemplate;
@Test(expected = YearViolationException.class)
public void testhandleBanNotNumericException() {
testRestTemplate.getForObject(baseUrl + endpointToThrowException, String.class);
}
关于spring - 如何使用 Power Mock 对 Spring Boot Rest Controller 和异常处理程序进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43911326/