当我依赖Spring Validator时,如何使用MockMvc测试我的SpringBoot RestController?

时间:2018-04-04 15:27:03

标签: spring-boot spring-test spring-test-mvc

在我的rest-controller中,我使用自定义Spring验证器类验证输入JSON。

当我现在想为控制器编写单元测试时,我收到的错误是找不到我的Validator ......

我正在使用构造函数注入我的rest-controller中的两个组件。

@Autowired
public JobController(JobValidator jobValidator, JobService jobService) {
    this.jobValidator = jobValidator;
    this.jobService = jobService;
}

这里是我对应的Test类。

@RunWith(SpringRunner.class)
@WebMvcTest(JobsController.class)
@AutoConfigureMockMvc
public class MailMonitorJobControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private JobService jobService;

@Test
public void givenJobs_whenGetJobs_thenReturnJsonArray() throws Exception {
    Job job = new Job("TEST");
    List<Job> allJobs = Arrays.asList(job);
    Mockito.when(jobService.getAllJobs()).thenReturn(allJobs);
    mockMvc.perform(get("/api/v1/test")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}

}

感谢任何帮助,提示或建议!

1 个答案:

答案 0 :(得分:0)

非常感谢@pvpkiran!我不得不将JobValidator添加为模拟!

@RunWith(SpringRunner.class)
@WebMvcTest(JobsController.class)
@AutoConfigureMockMvc
public class MailMonitorJobControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private JobService jobService;

@MockBean
private JobValidator jobValidator;

@Test
public void givenJobs_whenGetJobs_thenReturnJsonArray() throws Exception {
Job job = new Job("TEST");
List<Job> allJobs = Arrays.asList(job);
Mockito.when(jobService.getAllJobs()).thenReturn(allJobs);
mockMvc.perform(get("/api/v1/test")
        .contentType(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());
}

}