Mocked @Service在测试时连接到数据库

时间:2017-05-19 10:39:02

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

我试图测试我的Spring REST控制器,但我的@Service总是试图连接到DB。

控制器:

@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作为返回,它从数据库中读取数据。如果我关闭数据库,它会抛出NestedServletException, nested: DataAccessResourceFailureException

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

1 个答案:

答案 0 :(得分: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);
    }
}