【发布时间】:2018-08-10 11:59:48
【问题描述】:
我最近开始使用 Junit。所以我是新手。
当我使用上述方法的 @Test 注释并使用 Junit 的方法运行它时。 它创造了一个新的记录。这是正常的还是我弄错了?
@Before
public void setUp() {
restTemp = new RestTemplate();
}
@Test
public void testCreateOwner() {
Owner owner = new Owner();
owner.setFirstName("new");
owner.setLastName("record");
URI location = restTemp.postForLocation("http://localhost:8080/rest/owner", owner);
Owner owner2 = restTemp.getForObject(location, Owner.class);
MatcherAssert.assertThat(owner2.getFirstName(), Matchers.equalTo(owner.getFirstName()));
MatcherAssert.assertThat(owner2.getLastName(), Matchers.equalTo(owner.getLastName()));
}
我的创建所有者方法是
@RequestMapping(value = "/owner", method = RequestMethod.POST)
public ResponseEntity<URI> createOwner(@RequestBody Owner owner) {
try {
petClinicService.createOwner(owner);
Long id = owner.getId();
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri();
return ResponseEntity.created(location).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
而我的 createOwner 方法 impl 是
public void create(Owner owner) {
owner.setId(new Date().getTime());
ownersMap.put(owner.getId(), owner);
}
感谢您的帮助。
【问题讨论】:
-
你确实从你的测试中调用
petClinicService.createOwner(owner);... -
是的。我知道,但是我该如何测试呢?
-
肮脏的方法是在
@After中删除它们,因为您正在使用弹簧搜索 - 还有其他方法 -
喜欢第二个数据库?
-
顺便说一句,这些测试不再是单元测试...... IMO。你让服务器在测试运行的同时运行,否则你的测试将失败。嗯,是的,第二个内存数据库是一种选择,但即便如此,也有 junit
@Rule、spring 的@Rollback(value = true)等,可以为您清理
标签: java spring spring-boot junit