Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Mocked@Service在测试时连接到数据库_Java_Spring_Unit Testing_Mockito_Spring Test - Fatal编程技术网

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

Java Mocked@Service在测试时连接到数据库,java,spring,unit-testing,mockito,spring-test,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

我试图测试我的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);
}
}
我的测试总是失败,因为它从数据库读取数据,而不是以
第一个
第二个
作为返回。如果我关闭DB,它将抛出嵌套的:DataAccessResourceFailureException


我怎样才能正确地测试它?我做错了什么?

以这种方式模拟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);
    }
}

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