我使用Spock和Spring Framework为我的应用程序编写集成测试。Groovy - 集成测试
我想在每次测试前保存一些对象,并在每次测试后删除所有对象。
但问题在于,每次测试后都不会删除由Hibernate生成的ID。当我在第一次测试之前创建2个对象时,Hibernate生成id 1和2,并且当我为test 1和2运行测试findById时,测试成功。但是,对于ID为1,2下一个测试是不是成功,因为在数据库中的对象具有ID 3和4
这里是我的代码:
@ContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ControllerSpec extends Specification {
@Autowired
private TestRestTemplate restTemplate
@Autowired
private MyRepository repository
private EntityDTO dto
private MyEntity entity1
private MyEntity entity2
@Before
void set() {
this.entity1 = new MyEntity(1L)
this.entity2 = new MyEntity(2L)
this.dto = new EntityDTO()
repository.save(this.entity1)
repository.save(this.entity2)
}
@After
void clean() {
List<MyEntity> all = repository.findAll()
if (all != null || !all.isEmpty()) {
for (MyEntity entity : all) {
repository.delete(entity)
}
}
}
@Unroll
'findById test'() {
when:
def response = restTemplate.getForEntity(url, EntityDTO)
then:
response.getStatusCode() == statusCode
where:
url | statusCode
'/myurl/id/1' | HttpStatus.OK
'/myurl/id/2' | HttpStatus.OK
'/myurl/id/3' | HttpStatus.NOT_FOUND
}
而且我的控制器:
@GetMapping(value = "/id/{id}")
public ResponseEntity<EntityDTO> findById(@PathVariable Long id) {
final EntityDTO dto = service.findById(id);
if (dto != null) {
return new ResponseEntity<EntityDTO>(dto, HttpStatus.OK);
}
return new ResponseEntity<EntityDTO>(dto, HttpStatus.NOT_FOUND);
}
当我运行此代码我得到一个错误:
Condition not satisfied:
response.getStatusCode() == statusCode | | | | | 404 | 200 | false <404 Not Found,{Content-Length=[0], Date=[Thu, 15 Jun 2017 16:07:21 GMT]}>
,当我点击“看性差异”我看到的细节:预期:
groovy.lang.MissingFieldException: No such field: name for class: org.springframework.http.HttpStatus at groovy.lang.MetaClassImpl.getAttribute(MetaClassImpl.java:2820) ... at org.spockframework.runtime.JUnitSupervisor.convertToComparisonFailure(JUnitSupervisor.java:135)
实际是像预期与一个区别是相同的: 在
org.spockframework.runtime.JUnitSupervisor.convertToComparisonFailure(JUnitSupervisor.java:134)