написание отрицательных тестовых случаев для классов контроллера: springboot - PullRequest
1 голос
/ 23 июня 2019

Могу ли я написать несколько отрицательных тестовых примеров для класса контроллера

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

Благодарим Вас за помощь.

1 Ответ

0 голосов
/ 23 июня 2019

Вы можете смоделировать HealthStatus с другим статусом

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

Возможно, вам потребуется добавить @Spy

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