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

标签 spring spring-boot junit powermock powermockito

我有一个简单的 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/

相关文章:

java - 查找哪个依赖项包含 Spring WebApplicationInitializer

java - 事务的传播行为

spring - 在测试类弄脏 Spring JUnit 应用程序上下文后如何重置它?

spring - Spring Security 中的安全注解

java - 由于线程处于 WAITING 和 TIMED_WAITING 状态,请求处于挂起状态

kotlin - 在 Kotlin DSL Gradle 上包含/排除标签 Junit5 的正确方法是什么

java - 如何使用spring boot在java中运行neo4j查询?

java - 类文件版本 57.0,该版本的 Java 运行时仅识别 52.0 以下的类文件版本

java - 如何在 Ant 中仅运行特定的 JUnit 测试?

java - JUnit 测试套件 : Way to create a dataset first before tests start running