java - spring boot Controller 测试,mockMov 不模拟

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

我使用Spring MVC和Spring boot来编写Restful服务。这段代码通过 postman 工作得很好。虽然当我对 Controller 进行单元测试以接受发布请求时,模拟的 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();

}
}

下面是我的 Controller 类,其中 MyService 是一个接口(interface)。我已经实现了这个接口(interface)。

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

最佳答案

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


}

下面是 Controller

/**
 * 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;
        }

    }

}

关于java - spring boot Controller 测试,mockMov 不模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35534067/

相关文章:

java - Oracle JDK 和 OpenJDK 之间的区别

c# - .net 中的测试驱动开发和单元测试

java - Spring Boot 不使用 CustomAuthenticationProvider 返回用户名

c++ - 如何创建需要汇总答案的单元测试?

spring - Eureka 和 Jersey 2.x

java - 带有 Zuul 的 Spring Boot 2.4.2 网关 API

java - 列表和数组列表有什么区别

java - 使用动态键获取 LinkedHashMapValue

java - Java 中的自定义 ZoneIds/时区

javascript - 如何将 tinytest 与发布/订阅一起使用?