编写简单的SpringBoot单元测试类

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/swadian2008/article/details/95227478

目录

一、引入测试依赖

二、 Spring Boot 测试

1、注解解释:

(1)@RunWith

(2)@SpringBootTest

二、Spring MVC 测试


简单总结下SpringBoot开发中常用到的两个单元测试方法:

(1) Spring Boot 测试

(2) Spring MVC 测试

一、引入测试依赖

首先引入SpringBoot测试的依赖

扫描二维码关注公众号,回复: 7198769 查看本文章
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

依赖 spring-boot-starter-test 测试模块,其中包括JUnitHamcrestMockito

在spring-boot中,模块的依赖都是以starter的方式进行,以 spring-boot-starter-方式命名,指明了具体的模块。spring-boot生态中提供了丰富的starter供开发者使用。

Spring Boot的启动器Starter

二、 Spring Boot 测试

SpringBoot的单元测试非常简单,只要在测试类上,添加@RunWith@SpringBootTest注解就可以了。

示例代码如下(注:此代码不能直接执行,只做结构展示):

1、注解解释:

(1)@RunWith

 是一个测试运行器,JUnit所有的测试方法都有测试运行器负责执行。

JUnit为单元测试提供了一个默认的测试运行器BlockJUnit4Runner,但是没有限制必须使用默认的运行器。

SpringRunnerSpringJUnit4ClassRunner(BlockJUnit4Runner的拓展的别名。像这样,@RunWith(JUnit4.Class)就是指定用JUnit4来运行。

(2)@SpringBootTest

它可以用作标准spring-test

@ContextConfiguration注释的替代方法。注解的工作原理是通过SpringApplication在测试中创建ApplicationContext。

所以Spring1.4以上的版本一般情况下是这样的:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootStarterTests {
}

普通Spring项目中的测试一般情况下是这样的:

@RunWith(SpringRunner.class)
@ContextConfiguration(locations={"classpath:spring-servlet.xml", "classpath:spring-dao-test.xml", "classpath:spring-service-test.xml"})
public class MemberTest {
}

@BeforeClass:针对所有测试,只执行一次,且必须为static void

​​​​​​@Before  :执行测试方法前执行

@After  :执行测试方法后执行

@Test :测试方法

@AfterClass:针对所有测试,只执行一次,且必须为static void

一个单元测试类的执行顺序为:

@BeforeClass -> @Before -> @Test -> @After -> @AfterClass

每一个测试方法的调用顺序为:

@Before -> @Test -> @After

二、Spring MVC 测试

测试Controller接口,需添加注解@WebAppConfiguration

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class UserServiceImplTest {

    @Autowired
    private UserService userService;

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void before(){
        // 指定WebApplicationContext,将会从该上下文获取相应的控制器并得到相应的MockMvc
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        LogUtils.info("单元测试开始执行...");
    }

    @Test
    public void selectUser() throws Exception {
        mockMvc.perform(
                post("http://localhost:8080/demo/User/getUser")
                .contentType(MediaType.APPLICATION_JSON_UTF8) // 传参格式
                .content("{\"name\":\"xiaohong\"}") // JSON 格式传参
        )
                .andExpect(status().isOk()) // 添加断言
                .andDo(MockMvcResultHandlers.print()) // 打印操作
                .andReturn();
    }

    @After
    public void after(){
        LogUtils.info("单元测试执行结束...");
    }
}

猜你喜欢

转载自blog.csdn.net/swadian2008/article/details/95227478