【问题标题】:spring boot controller test, mockMov doesn't mockspring boot 控制器测试,mockMov 不模拟
【发布时间】:2016-06-02 17:22:30
【问题描述】:

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

【问题讨论】:

    标签: java unit-testing spring-boot spring-mvc-test


    【解决方案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;
            }
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-22
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 2018-08-15
      • 2017-01-04
      • 1970-01-01
      相关资源
      最近更新 更多