【问题标题】:Mocked @Service connects to database while testing模拟@Service 在测试时连接到数据库
【发布时间】:2017-05-19 10:39:01
【问题描述】:

我正在尝试测试我的 Spring REST 控制器,但我的 @Service 总是尝试连接到数据库。

控制器:

@RestController
@RequestMapping(value = "/api/v1/users")
public class UserController {

private UserService userService;

@Autowired
public UserController(UserService userService) {
    this.userService = userService;
}

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<User>> getAllUsers() {
    List<User> users = userService.findAll();
    if (users.isEmpty()) {
        return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
    }

    return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}

测试:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class UserControllerTest {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext wac;

@Before
public void setup() {
    this.mockMvc = webAppContextSetup(wac).build();
}

@Test
public void getAll_IfFound_ShouldReturnFoundUsers() throws Exception {
    User first = new User();
    first.setUserId(1);
    first.setUsername("test");
    first.setPassword("test");
    first.setEmail("test@email.com");
    first.setBirthday(LocalDate.parse("1996-04-30"));

    User second = new User();
    second.setUserId(2);
    second.setUsername("test2");
    second.setPassword("test2");
    second.setEmail("test2@email.com");
    second.setBirthday(LocalDate.parse("1996-04-30"));

    UserService userServiceMock = Mockito.mock(UserService.class);  

    Mockito.when(userServiceMock.findAll()).thenReturn(Arrays.asList(first, second));

    mockMvc.perform(get("/api/v1/users")).
            andExpect(status().isOk()).
            andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).
            andExpect(jsonPath("$", hasSize(2))).
            andExpect(jsonPath("$[0].userId", is(1))).
            andExpect(jsonPath("$[0].username", is("test"))).
            andExpect(jsonPath("$[0].password", is("test"))).
            andExpect(jsonPath("$[0].email", is("test@email.com"))).
            andExpect(jsonPath("$[0].email", is(LocalDate.parse("1996-04-30")))).
            andExpect(jsonPath("$[1].userId", is(2))).
            andExpect(jsonPath("$[1].username", is("test2"))).
            andExpect(jsonPath("$[1].password", is("test2"))).
            andExpect(jsonPath("$[1].email", is("test2@email.com"))).
            andExpect(jsonPath("$[1].email", is(LocalDate.parse("1996-04-30"))));

    verify(userServiceMock, times(1)).findAll();
    verifyNoMoreInteractions(userServiceMock);
}
}

我的测试总是失败,因为它从数据库中读取数据,而不是返回 firstsecond。如果我关闭 DB,它会抛出 NestedServletException, nested: DataAccessResourceFailureException

如何正确测试它?我做错了什么?

【问题讨论】:

  • 你没有嘲笑任何东西......你的应用程序仍然使用真正的服务。要模拟,请在您的测试中创建一个 UserService 类型的字段并使用 @MockBean 进行注释(并删除您的手动模拟创建),而不是手动创建 MockMvc 并在其上放置 @Autowired 并让 Spring Boot 测试支持处理给你。

标签: java spring unit-testing mockito spring-test


【解决方案1】:

以这种方式模拟 userService UserService userServiceMock = Mockito.mock(UserService.class); 不会将其注入控制器。删除此行并注入 userService 如下

@MockBean UserService userServiceMock;

正如@M.Deinum 建议的那样,您可以删除手动创建MockMvc 并自动连接它

@Autowired
private MockMvc mockMvc;

最后你的代码应该是这样的

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class UserControllerTest {

    @MockBean 
    UserService userServiceMock;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void getAll_IfFound_ShouldReturnFoundUsers() throws Exception {
       User first = new User();
       first.setUserId(1);
       first.setUsername("test");
       first.setPassword("test");
       first.setEmail("test@email.com");
       first.setBirthday(LocalDate.parse("1996-04-30"));

       User second = new User();
       second.setUserId(2);
       second.setUsername("test2");
       second.setPassword("test2");
       second.setEmail("test2@email.com");
       second.setBirthday(LocalDate.parse("1996-04-30"));

       Mockito.when(userServiceMock.findAll())
           .thenReturn(Arrays.asList(first, second));

       mockMvc.perform(get("/api/v1/users")).
        andExpect(status().isOk()).
        andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).
        andExpect(jsonPath("$", hasSize(2))).
        andExpect(jsonPath("$[0].userId", is(1))).
        andExpect(jsonPath("$[0].username", is("test"))).
        andExpect(jsonPath("$[0].password", is("test"))).
        andExpect(jsonPath("$[0].email", is("test@email.com"))).
        andExpect(jsonPath("$[0].email", is(LocalDate.parse("1996-04-30")))).
        andExpect(jsonPath("$[1].userId", is(2))).
        andExpect(jsonPath("$[1].username", is("test2"))).
        andExpect(jsonPath("$[1].password", is("test2"))).
        andExpect(jsonPath("$[1].email", is("test2@email.com"))).
        andExpect(jsonPath("$[1].email", is(LocalDate.parse("1996-04-30"))));

        verify(userServiceMock, times(1)).findAll();
        verifyNoMoreInteractions(userServiceMock);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2013-06-20
    • 2011-03-14
    • 2016-06-12
    • 2010-09-23
    相关资源
    最近更新 更多