我的控制器类别:
package some.pkg.controller;
@RestController
@RequestMapping(value="/api", produces="application/json")
public class MyController {
@Autowired
private IntSequenceFilter sequenceFilter;
@PostMapping("/odd")
public FilteredSequence filterOdd(@RequestBody SequenceRequest sequenceRequest) {
List<Integer> filteredSequence = sequenceFilter.process(sequenceRequest.getData());
return new FilteredSequence(filteredSequence);
}
}
我的服务等级:
package some.pkg.service;
@Service
public class IntSequenceFilter {
// ... Some code ...
}
这是我的测试:
package some.pkg.controller
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private IntSequenceFilter sequenceFilter;
@Test
public void testFilter() throws Exception {
MvcResult response = mockMvc.perform(
MockMvcRequestBuilders.post("/api/odd")
.content("{\"data\":\"1;2;3;-1;-2;-3\"}")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andReturn();
// ... Some assertions ...
}
}
我运行测试时,未在控制器的 filterOdd 方法内部调用 sequenceFilter.process()。有人可以帮我弄清楚这里出了什么问题吗?
答案 0 :(得分:2)
我相信您是说通过检查process()方法中的日志语句未调用sequenceFilter.process()
。
这是一个模拟,您需要模拟以下行为
Mockito.when (sequenceFilter.process (Mockito.any ())).thenReturn (sequences);
如果您想调用实际的服务实现,请使用Spy
替换
@MockBean
private IntSequenceFilter sequenceFilter;
与
@SpyBean
private IntSequenceFilter sequenceFilter;
答案 1 :(得分:0)
请尝试添加以下设置方法,以通过模拟设置控制器。
@InjectMocks
private MyController myController;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.setMockMvc(MockMvcBuilders.standaloneSetup(myController).build());
// set return values from the mocked service
when(sequenceFilter.process(...).thenReturn(...);
}