未使用Spring Boot为单元测试创​​建H2 DB

时间:2020-06-12 10:11:34

标签: spring-boot junit h2

我想测试我的应用程序,我正在使用Spring Boot,这是一个仅用于单元测试的H2数据库。

因此,在我的application-test.properties中,我定义了一个内存数据库。

application-test.properties:

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;IFEXISTS=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.datasource.continue-on-error=true
# Enabling H2 Console
spring.h2.console.enabled=true
# Custom H2 Console URL
spring.h2.console.path=/h2-console

这是我要运行的测试的文件之一

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@Transactional
@ActiveProfiles("test")
public class FileControllerTest {

@Autowired
private WebApplicationContext context;

@Autowired
private MockMvc mvc;

@Before()
public void setup() {
    mvc = MockMvcBuilders.webAppContextSetup(context).build();
}

@Test
public void importExcelFile() throws Exception {
    final byte[] bytes = Files.readAllBytes(Paths.get("src/test/resources/import_demo.xlsx"));
    mockMvc.perform(multipart("/upload/{managerId}/project/{projectId}", 1, 1)
            .file("file", bytes).with(user("manager")))
            .andExpect(status().isOk()); 
}

public static String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
}

这是我从localhost:9191 / h2-console获得的信息(我的数据库在端口9191上定义)

enter image description here

我想我为此很好地定义了pom.xml

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
         <version>1.4.193</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

0 个答案:

没有答案