0

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);
}
}
4

1 に答える 1

1

api はアプリケーションのコンテキスト ルートですか? その場合は、リクエスト URI からコンテキスト ルートを削除してテストします。コンテキスト ルートを渡すと 404 がスローされます。コンテキスト ルートを渡す場合は、以下のテスト ケースを参照してください。お役に立てれば。

@RunWith(MockitoJUnitRunner.class)
public class MyControllerTest {

    @InjectMocks
    private MyController myRulesController;


    private MockMvc mockMvc;



    @Before
    public void setup() {

        this.mockMvc = standaloneSetup(myRulesController).build();
    }
    @Test
    public void controllerTest() throws Exception{
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        MyController.User user = new MyController.User("test-user");
        ow.writeValueAsString(user);
        MvcResult result = mockMvc.perform(post("/api/rule").contentType(MediaType.APPLICATION_JSON).contextPath("/api")
                .content(ow.writeValueAsString(user)))
                .andExpect(status().isOk())
                .andExpect(
                        content().contentType(MediaType.APPLICATION_JSON))
                .andReturn();
    }


}

下はコントローラー

/**
 * Created by schinta6 on 4/26/16.
 */
@RestController
@RequestMapping("/api/rule")
public class MyController {

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    public User eventsForRule(@RequestBody User payload) {

        return new User("Test-user");

    }


    public static class User {

        private String name;

        public User(String name){
            this.name = name;
        }

    }

}
于 2016-04-26T19:40:55.950 に答える