我正在为SpringBoot 2 RestController编写一个集成测试。我想测试404行为和实体的创建。然而,当我尝试在测试之前或期间创建实体并持久化它们时,它们不会持久化到SpringBoot上下文中。我的意思是,它们在测试上下文中是可见的(在测试调试期间),但对控制器来说是不可见的(即它找不到它们,我的测试失败)。我做错了什么?
如何在测试期间持久化实体并刷新上下文,以便在集成测试期间调用的代码能够看到它们?我不想使用@before注释来填充数据库,因为我想在@test方法中这样做。
这是我的密码。谢谢
@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));
Invoicee savedInvoicee = invoiceeRepository.save(new Invoicee());
assertThat(invoiceeRepository.count(), equalTo(1L));
Invoicer savedInvoicer = invoicerRepository.save(new Invoicer());
assertThat(invoicerRepository.count(), equalTo(1L));
entityManager.flush();
InvoiceInputDto inputDto = InvoiceInputDto
.builder()
.invoicee(savedInvoicee.getId())
.invoicer(savedInvoicer.getId())
.name("test-name")
.build();
ResponseEntity<InvoiceDto> response = template.postForEntity(url("/invoices", TOKEN), inputDto, InvoiceDto.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.CREATED));
assertThat(response.getBody().getName(), equalTo(inputDto.getName()));
assertThat(invoiceeRepository.findById(savedInvoicee.getId()).get().getInvoices(), hasSize(1));
}
}