@Test创建新记录

时间:2018-08-10 11:59:48

标签: java spring spring-boot junit

我最近开始使用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方法隐含的是

public void create(Owner owner) {
    owner.setId(new Date().getTime());
    ownersMap.put(owner.getId(), owner);

}

谢谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您正在测试持久性,它可以正常工作。但是,我建议您删除您在测试中创建的条目,无论是在测试方法中,还是在创建单独的方法(在其中删除)中,并使用@After对其进行注释。

例如使用此代码:

 @Before
 @After
 public void deleteTestUsers(){
    // call delete endpoint
 }

使用这样的代码段,请确保

  • 运行测试之前,您已处于“已知”状态-表示该条目不存在。
  • 运行测试后,您将清除创建的条目-因此将其保持在“已知”状态。

有点像公共厕所。 -清洁前和清洁后。 ;-)

相关问题