testcontainers配置
官网地址:testcontainers
添加依赖
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>junit</artifactId>
<groupId>junit</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<scope>test</scope>
</dependency>
增加数据库连接
datasource:
driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
url: jdbc:tc:mysql:5.7.31:///test?characterEncoding=utf-8&autoReconnect=true&allowMultiQueries=true&rewriteBatchedStatements=true&TC_INITSCRIPT=init_mysql.sql
username: test
password: test
TC_INITSCRIPT:指定的是初始化脚本
基类base类
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
public abstract class BaseTest {
@Autowired protected ObjectMapper objectMapper;
@Autowired WebApplicationContext webApplicationContext;
@LocalServerPort private int port;
@Rule public MySQLContainer mysql = new MySQLContainer();
@BeforeEach
public void commonSetUp() {
RestAssured.port = port;
RestAssured.requestSpecification =
new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.build();
}
}
测试类
需要继承base基类
@Slf4j
class CrowdControllerTest extends BaseTest {
@Autowired CrowdSelectionMapper crowdSelectionMapper;
@Before
public void testMysqlStart() {
mysql.start();
}
@Test
public void testUnit() {
CrowdSelectionPO crowdSelectionPO = crowdSelectionMapper.selectById(264);
log.info(String.valueOf(crowdSelectionPO));
}
}
需要在所有test方法执行之前,启动MySQLContainer实例