yankj12 / blog

技术研究、管理实践、其他的一些文章
MIT License
1 stars 2 forks source link

使用Junit测试SpringBoot #58

Open yankj12 opened 5 years ago

yankj12 commented 5 years ago

我自己的一个示例

Junit4

Java代码

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.yan.imgspider.ImageApplication;
import com.yan.imgspider.service.facade.ImageService;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { ImageApplication.class })
public class ImgTest {

    @Autowired
    xxxx...

    @Test
    public void test(){

    }
}

spring boot 跑junit 报错

nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

可以看到,对spring-boot项目进行单元测试是件容易的事儿,需要添加spring-boot-starter-test依赖,然后 使用@RunWith和@SpringBootTest或@SpringApplicationConfiguration(1.4.0过期)注解,然后引入自己要测试的bean,调用指定方法进行测试即可。

@RunWith(SpringJUnit4ClassRunner.class)  
@SpringBootTest(classes=Application.class)// 指定spring-boot的启动类   
//@SpringApplicationConfiguration(classes = Application.class)// 1.4.0 前版本  
public class SpringBootJdbcTest {  

参考资料

Junit5

Maven依赖

springboot2.2.0之前,spring-boot-starter-test默认支持的是junit4。之后支持的是junit5

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> 
    </parent>
...

  <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  </dependencies>

Java代码


// Junit5
@ExtendWith(SpringExtension.class)
@SpringBootTest
@DisplayName("TaskMapperTest")
public class TaskMapperTest {
    @Autowired
    xxxx...

    @Test
    public void test(){

    }
}

Junit5测试RestController


// Junit5
@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@DisplayName("TaskRedissonController")
class RedissonControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testRedissonTest() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/redisson/save/redis_lock_student").accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();
    }

}

参考资料