【问题标题】:Spring Boot Controller Test with Mock Service doesn't use the mock serviceSpring Boot Controller Test with Mock Service 不使用模拟服务
【发布时间】:2021-05-26 15:20:57
【问题描述】:

我有一个带有 Service 的简单 RestController,并且想通过为 Service 提供模拟实现来仅测试控制器。 但是,当我运行测试时,我在 resultActions = mockMvc.perform(get("/user")); 对象中得到一个空响应。 这是我的代码: 控制器

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/user")
    public ResponseEntity<List<String>> getUsers(){
        return ResponseEntity.ok().body(userService.getUsers());
    }

}

控制器测试

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {

    @MockBean
    UserService userService;

    private final Logger log = LoggerFactory.getLogger(UserControllerTest.class);
    @Autowired
    MockMvc mockMvc;

    @Before
    public void init(){
        List<String> usrs = new ArrayList<>();
        usrs.add("JUNIT-USER");
        userService = Mockito.mock(UserService.class);
        when(userService.getUsers()).thenReturn(usrs);
    }

    @Test
    public void test1() throws Exception {
        ResultActions resultActions = mockMvc.perform(get("/user"));
        resultActions.andDo(mvcResult -> {
            log.info(mvcResult.getResponse().getContentType());
            log.info(mvcResult.getResponse().getContentAsString());
            log.info(String.valueOf(mvcResult.getResponse().getContentLength()));

        });
        resultActions
        .andExpect(status().isOk())
        .andExpect(MockMvcResultMatchers.content().json("[\"JUNIT-USER\"]"));
    }

}

测试中日志语句的输出如下:

2021-02-24 15:23:16.161  INFO 22197 --- [           main] com.vi.learn.UserControllerTest      : application/json
2021-02-24 15:23:16.161  INFO 22197 --- [           main] com.vi.learn.UserControllerTest      : []
2021-02-24 15:23:16.161  INFO 22197 --- [           main] com.vi.learn.UserControllerTest      : 0

因此测试失败并出现以下断言错误: java.lang.AssertionError: []: Expected 2 values but got 0

我在这里做错了什么?

【问题讨论】:

    标签: junit4 spring-boot-test spring-mvc-test


    【解决方案1】:

    现有的两种方法

    • 使用 mock () 方法
    • 使用@MockBean 注释

    @MockBean
    用户服务用户服务;
    要么
    userService = Mockito.mock(UserService.class);

    你必须选择其中之一,所以只需使用 @MockBean

     @Before
    public void init(){
        List<String> usrs = new ArrayList<>();
        usrs.add("JUNIT-USER");
        when(userService.getUsers()).thenReturn(usrs);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-20
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2020-08-13
      • 2013-12-21
      • 2021-11-13
      相关资源
      最近更新 更多