在我的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());
}
}
感谢任何帮助,提示或建议!
答案 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());
}
}