简体   繁体   English

@Test创建新记录

[英]@Test creates new record

I recently started to using Junit. 我最近开始使用Junit。 So im newbie. 所以我是新手。

When i use @Test anotation above method and run that with method with Junit. 当我在上述方法中使用@Test注释并与Junit方法一起运行时。 It creates a new record. 它创建一个新记录。 Is this normal or am i making a mistake? 这是正常现象还是我犯错了?

    @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()));
}

My create owner method is 我的创建所有者方法是

@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();
    }
}

and my createOwner method impl is 而我的createOwner方法impl是

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

}

Thank you for your help. 谢谢您的帮助。

You are testing the persistence and it is working normal. 您正在测试持久性,并且它可以正常工作。 However I would suggest deleting the entries that you created in your test, either in the test method or creating a separate method (in which you delete) and annotate it with @After . 但是,我建议删除您在测试中创建的条目,无论是在测试方法中,还是在创建单独的方法(在其中删除)时都使用@After注释。

For example using this: 例如使用这个:

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

Using such a snippet you make sure that 使用这样的代码段,您可以确保

  • Before running the test you got a "known" state - meaning that the entry does not exist. 在运行测试之前,您已处于“已知”状态-表示该条目不存在。
  • After running the test you clear up the created entry - hence leaving it in a "known" state. 运行测试后,您清除创建的条目-因此将其保持在“已知”状态。

Kind of like the public toilet. 有点像公共厕所。 - Clean before & clean after. -清洁前和清洁后。 ;-) ;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM