mardi 17 avril 2018

How can I persist entities during a SpringBootTest integration test

I am writing an integration test for a SpringBoot 2 RestController. I want to test 404 behaviour and creation of entities. However, when I try to create entities and persist them before or during a test, they are not persisted in the SpringBoot context. By that I mean they are visible in the test context (during debugging of the test) but not for the Controller (ie it does not find them and my tests fail). What am I doing wrong?

How can I persist entities and flush the context during a test so that code that is called during an integration test sees them? I don't want to use a @before annotation to populate a database because I want to do it in my @test methods.

Here is my code. Thanks

@RunWith(SpringRunner.class)
@Transactional
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class InvoiceControlllerIT extends GenericControllerIT {

  @Autowired
  EntityManager entityManager;

  @Test
  @Transactional
  public void cascadesChildEntityAssociationOnCreate() throws IOException {
    assertThat(invoicerRepository.count(), equalTo(0L));
    assertThat(invoiceRepository.count(), equalTo(0L));
    assertThat(invoiceeRepository.count(), equalTo(0L));
    // create an invoicee
    Invoicee savedInvoicee = invoiceeRepository.save(new Invoicee());
    assertThat(invoiceeRepository.count(), equalTo(1L));
    // create an invoicer
    Invoicer savedInvoicer = invoicerRepository.save(new Invoicer());
    assertThat(invoicerRepository.count(), equalTo(1L));
    // THIS IS THE PROBLEM, FLUSHING DURING THE TEST DOES NOT EFFECT THE CONTROLLERS ABILITY TO SEE THE NEWLY CREATED ENTITIES
    entityManager.flush();
    // create input
    InvoiceInputDto inputDto = InvoiceInputDto
            .builder()
            .invoicee(savedInvoicee.getId())
            .invoicer(savedInvoicer.getId())
            .name("test-name")
            .build();
    // make call
    ResponseEntity<InvoiceDto> response = template.postForEntity(url("/invoices", TOKEN), inputDto, InvoiceDto.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.CREATED));
    assertThat(response.getBody().getName(), equalTo(inputDto.getName()));
    // check associations
    assertThat(invoiceeRepository.findById(savedInvoicee.getId()).get().getInvoices(), hasSize(1));
  }
}

Aucun commentaire:

Enregistrer un commentaire