【问题标题】:@Test creates new record@Test 创建新记录
【发布时间】: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


【解决方案1】:

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

例如使用这个:

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

使用这样的 sn-p 你可以确保

  • 在运行测试之前,您处于“已知”状态 - 表示该条目不存在。
  • 运行测试后,您会清除创建的条目 - 从而使其处于“已知”状态。

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

【讨论】:

  • 所以正常我需要用@After 删除谢谢。
  • 是的。通常你会有 2 个数据库,一个用于刺痛,另一个用于生产。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 2014-12-13
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 2016-05-17
相关资源
最近更新 更多