Spring MVC と Spring ブートを使用して、Restful サービスを記述します。このコードは、postman を介して正常に動作します。コントローラーが投稿要求を受け入れるための単体テストを実行すると、モックされた myService は、 when... thenReturn によって定義されたモック値を返すのではなく、常に自身を初期化します...私は verify( を使用しますMyService,times(1)).executeRule(any(MyRule.class)); モックが使用されていないことを示しています。また、mockMoc に standaloneSetup を使用しようとしましたが、パス "/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);
}
}