0

我使用 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);
}
}
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 回答