我使用 Spring MVC 和 Spring boot 来编写一个 Restful 服务。此代码通过邮递员工作正常。当我对控制器进行单元测试以接受发布请求时,模拟的 myService 将始终初始化自身,而不是返回由 when...thenReturn... 定义的模拟值...我使用 verify( MyService,times(1)).executeRule(any(MyRule.class)); 它表明未使用模拟。我还尝试将standaloneSetup 用于mockMoc,但它抱怨找不到路径“/api/rule”的映射。任何人都可以帮助解决这个问题吗?
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class MyControllerTest {
@Mock
private MyService myService;
@InjectMocks
private MyController myRulesController;
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void controllerTest() throws Exception{
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
Long userId=(long)12345;
MyRule happyRule = MyRule.createHappyRule(......);
List<myEvent> mockEvents=new ArrayList<myEvent>();
myEvents.add(new MyEvent(......));
when(myService.executeRule(any(MyRule.class))).thenReturn(mockEvents);
String requestBody = ow.writeValueAsString(happyRule);
MvcResult result = mockMvc.perform(post("/api/rule").contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isOk())
.andExpect(
content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
verify(MyService,times(1)).executeRule(any(MyRule.class));
String jsonString = result.getResponse().getContentAsString();
}
}
下面是我的控制器类,其中 MyService 是一个接口。我已经实现了这个接口。
@RestController
@RequestMapping("/api/rule")
public class MyController {
@Autowired
private MyService myService;
@RequestMapping(method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
public List<MyEvent> eventsForRule(@RequestBody MyRule myRule) {
return myService.executeRule(myRule);
}
}