我從不爲我的休息控制器和服務編寫測試。 我已閱讀官方文檔,如何在春季啓動時編寫集成測試。 因此,例如我有一個休息Controller類春季啓動,測試垃圾信息庫
@RestController
@RequestMapping(value = "users")
public class SvcUser {
@RequestMapping(value = "user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<String> registrateUser(@RequestBody Registration registrate) throws TimeoutException, SocketTimeoutException {
final String result = userService.registrateUser(registrate.getPhoneCode(), registrate.getPhoneNumber(), registrate.getOsType());
return ResponseEntity.ok(result);
}
而且裏面userServiceClass我做了水木清華這樣
registrateUser(String args ...){
Users user = new User();
user.setSmth(smth);
userRepository.save(user)
}
我的集成測試
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,classes = GmoikaApiApplication.class)
public class GmoikaApiApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp(){
this.mockMvc = webAppContextSetup(wac).build();
}
@Test
public void firstTest() throws Exception {
mockMvc.perform(post("https://stackoverflow.com/users/user")
.content("my new user"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.error",is(0)))
.andDo(print())
.andReturn();
}
這是正常工作,但我在我的數據庫中有新用戶。我不想在生產中僅由於測試而創建假用戶。我的問題是如何避免在集成測試中的數據庫中創建新用戶?
使用測試db表示'hsqldb'是彈簧測試的默認值。你可以使用它。 – sunkuet02
您可以使用'@ Transactional'和'@ Rollback'來創建用戶,然後將其滾回到數據庫中。 – Brad