2017-06-15 225 views
0

我使用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)

回答

2

而不是硬編碼在測試ID可以使用分配了ID例如持續時

... 
url      | statusCode 
"/myurl/id/${entity1.id}" | HttpStatus.OK 
...