0
我試圖測試我的Spring REST控制器,但我的@Service
始終嘗試連接到數據庫。Mocked @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("[email protected]");
first.setBirthday(LocalDate.parse("1996-04-30"));
User second = new User();
second.setUserId(2);
second.setUsername("test2");
second.setPassword("test2");
second.setEmail("[email protected]");
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("[email protected]"))).
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("[email protected]"))).
andExpect(jsonPath("$[1].email", is(LocalDate.parse("1996-04-30"))));
verify(userServiceMock, times(1)).findAll();
verifyNoMoreInteractions(userServiceMock);
}
}
我的測試總是失敗的,因爲不是得到first
和second
作爲回報,它從數據庫中讀取數據。如果我關閉DB,則會拋出NestedServletException, nested: DataAccessResourceFailureException
。
如何正確測試它?我究竟做錯了什麼?
你並沒有嘲笑任何東西......你的應用程序仍然使用真實的服務。爲了模擬,在你的測試中創建一個'UserService'類型的字段,並用'@ MockBean'註釋(並刪除你的手動模擬創建),而不是手動創建'MockMvc'放''Autowired'並讓Spring Boot測試支持爲你處理它。 –