为什么用 BeforeAll 注释的设置方法不会将 ShippingAddress 对象保存到数据库?



我正在尝试向我的项目添加一些测试,并且在运行测试之前需要填充数据库。

我尝试过使用一个void setup((方法来实现这一点,该方法用BeforeEach进行了注释,并试图确保数据不会回滚。这是我的代码示例。我必须补充一点,shippingAddressRepository和billingAddressRepository都扩展了JPARepository。当我运行测试时,它抛出一个自定义异常,告诉我在DB中找不到发货地址的id。

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {OrdersApiApplication.class, H2JpaConfig.class})
@AutoConfigureMockMvc
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestClassOrder(ClassOrderer.OrderAnnotation.class)
@TestPropertySource("classpath:application.yml")
class OrdersControllerTest extends GenericIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ShippingAddressRepository shippingAddressRepository;
@Autowired
private BillingAddressRepository billingAddressRepository;
private static ShippingAddress testShippingAddress;
private static BillingAddress testBillingAddress;
@BeforeAll
@Rollback(value=false)
public void setup() {
testShippingAddress = shippingAddressRepository.save(new ShippingAddress("1","0722123443","Popescu","Ana","aleea lalelelor", "Romania","Sv","2112",null));
System.out.println(testShippingAddress);
testBillingAddress = billingAddressRepository.save(new BillingAddress("1", "0722123443","Popescu","Ana","aleea lalelelor", "Romania","Sv","2112",null));
}
@Nested
class CreateOrderTests {
@Nested
class CreateProductTests {
private ObjectMapper mapper = new ObjectMapper();
@Test
void shouldCreateOrderSuccessfully() throws Exception {
ShippingAddress shippingAddress = new ShippingAddress();
shippingAddress.setId("1");
// act
MvcResult mvcResult = mockMvc
.perform(createPostRequest(OrdersController.PATH, new CreateOrderReqDTO(OrderStatus.PAID, 3, 100.0, 100.0, 5.0, "1", "1", "1", "1")))
.andReturn();
OrderDTO response = mapper.readValue(mvcResult.getResponse().getContentAsString(), new TypeReference<>() {
});
// assert
assertEquals(100.0, response.getTotal());
assertEquals(100.0, response.getGrandTotal());
}
}
}

}

有很多方法:

  • 将liquibase脚本与测试环境的测试数据一起使用
  • 使用@Sql注释https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/jdbc/Sql.html
  • 如果您使用PostgreSQLContainer这样的测试容器,则有一种方法withInitScript("someScript.sql"(
  • 如果你使用H2,那么把init部分放在你的url中,比如:";jdbc:h2:mem:test;INIT=RUNSCRIPT FROM"classpath:scripts/create.sql">

最新更新