编程语言
首页 > 编程语言> > 如何使用Power Mock对Spring Boot Rest Controller和异常处理程序进行单元测试

如何使用Power Mock对Spring Boot Rest Controller和异常处理程序进行单元测试

作者:互联网

我有一个简单的Spring boot应用程序,其中包含Employee控制器,如果所经过的年份大于2014,则返回Employee名称;如果不小于2014,则抛出自定义异常,并在Exception Handler中对其进行处理.我想使用powermock对异常流进行单元测试,但是我不确定该怎么做.我已经通过一些链接,但无法理解.

目前,我正在获取java.lang.IllegalArgumentException:需要WebApplicationContext.

EmployeeController.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());
    }
}

CustomException

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));

    }
}

解决方法:

正如其他人所述,您根本不需要嘲笑MVC.如果要测试REST端点,则需要TestRestTemplate.
与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);
}

标签:powermockito,spring-boot,junit,powermock,spring
来源: https://codeday.me/bug/20191026/1933121.html