java - Spring Cloud Contract 未执行 @Before
问题描述
我正在使用 Spring Cloud Contract 编写测试。
在我的配置中,我用于测试在每次测试运行时创建和销毁的内存数据库。
为了成功测试,我需要将一些数据放入数据库中,但似乎 jUnit 中使用的经典 @Before 注释不起作用(其中的代码永远不会执行)。
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.context.WebApplicationContext;
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class BaseTestClass {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseTestClass.class);
@Autowired
EntityRepository entityRepository;
@Autowired
private WebApplicationContext context;
@Before
public void init() {
// This code never runs
LOGGER.info("Init started");
MyEntity entity1 = new MyEntity();
entityRepository.save(entity1);
}
@BeforeEach
public void setup() {
RestAssuredMockMvc.webAppContextSetup(context);
}
}
我错过了什么?
解决方案
@Before
属于 JUnit4 及更早版本,@BeforeEach
属于 JUnit5 作为@Before
. 如果您使用 JUnit5 运行,则可能将所有初始化逻辑放入@BeforeEach
(或者如果它是一次性初始化,则放入@BeforeAll
)