为控制器类编写负单元测试用例:spring boot

Posted

技术标签:

【中文标题】为控制器类编写负单元测试用例:spring boot【英文标题】:writing negative unit test cases for controller classes :springboot 【发布时间】:2019-11-05 09:03:54 【问题描述】:

有没有办法为控制器类编写一些负面测试用例

@RestController
@RequestMapping(value = "/health")
@Api(value = "EVerify Health check API", description = "Health check API")
public class HealthStatusController 

    @Autowired
    @Qualifier("implementation")
    private HealthStatus healthStatus;

    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "Get the health status of the API", response = ResponseEntity.class)
    public @ResponseBody
    ResponseEntity getHealth() 
        Integer status = healthStatus.healthCheck();
        if (status == 200)
            return ResponseEntity.status(HttpStatus.OK).build();
        else
            return ResponseEntity.status(HttpStatus.ACCEPTED).build();
    

我写了一个如下的正面测试用例

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HealthStatusControllerTest 

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    @Qualifier("implementation")
    private HealthStatus healthStatus;

    @InjectMocks
    private HealthStatusController healthStatusController;

    @Rule public ExpectedException exception = ExpectedException.none();

    @Before
    public void setUp() throws Exception 
        mockMvc = MockMvcBuilders.standaloneSetup(healthStatusController).build();
    

    @Test
    public void getHealthCheckReturns200Test() throws Exception 
        exception.expect(Exception.class);

        Mockito.when(healthStatus.healthCheck()).thenReturn(200);
        mockMvc.perform(get("/health")).andExpect(status().isOk()).andReturn();
    

感谢您的帮助。

【问题讨论】:

你可以模拟HealthStatus 你能帮我举个例子吗? 【参考方案1】:

你可以模拟不同状态的 HealthStatus

Mockito.when(healthStatus.healthCheck()).thenReturn(500);
mockMvc.perform(get("/health")).andExpect(status().is(500)).andReturn();

您可能需要添加@Spy

@Spy
@Autowired
@Qualifier("implementation")
private HealthStatus healthStatus;

【讨论】:

以上是关于为控制器类编写负单元测试用例:spring boot的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Spring Boot 应用程序中为带有 @Configuration 注释的类编写单元测试用例

Spring Boot API 的单元测试

在 Spring boot 中为 Filter (OncePerRequestFilter) 编写单元测试

具有多个模块和多个主类的spring boot项目-单元测试失败

如何在 Spring-boot 中不模拟服务类的情况下为 REST 控制器端点编写单元测试

如何在Spring Boot中的所有测试用例之前只设置一次独立控制器?