Spring Boot--junit的使用

本文介绍了SpringBoot中使用JUnit进行单元测试的实践,包括添加测试依赖、创建测试基类、编写测试类、打包测试、忽略测试方法以及断言的使用。同时,针对私有方法测试、Controller层测试、数据回滚和WebSocket测试问题给出了解决方案。此外,还提到了在maven打包时排除测试代码的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

juint

参考文章1
待补充

1. 依赖

修改pom.xml 增加依赖,一般Spring Boot项目有引入

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

2.增加测试类基类(避免每个类都需要注解)

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

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

    @Before
    public void init() {
        System.out.println("开始测试-----------------");
    }

    @After
    public void after() {
        System.out.println("测试结束-----------------");
    }

}

3.测试类

public class TestServices extends SpringbootdemoApplicationTests {

    @Autowired
    Service service;

    @Test
    //回滚数据操作
    @Transactional
    public void testDelete() {
        service.deleteById("111111");
    }

    

4.打包测试

@Suite.SuiteClasses({TestServices.class,TestServices2.class})
//@Ignore("not ready yet")
@RunWith(Suite.class)
@Suite.SuiteClasses({TestServices.class,TestServices2.class})
public class TestSuits {
}

5.忽略方法

@Ignore("not ready yet")

断言

待补充

常见问题解决

私有方法测试

参考2利用反射获取方法,调用方法

private Double format(Double fileSize){
	Double size = fileSize;
	size = size / 1024 / 1024;
	size = (int)(size.doubleValue() * 10 + 0.5) / 10.0;
	return size;
}
@Test
public void testFormat(){
	ClientDownloadAction action = new ClientDownloadAction();
	double size = 3732930;
	Class class1 = action.getClass();
	try {
		Method format = class1.getDeclaredMethod("format", Double.class);
		format.setAccessible(true);//设为可见
		Double result = (Double)format.invoke(action, size);
		Double expect = 3.6;
		Assert.assertEquals(expect, result);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

controller 层测试

待补充

数据回滚

根据参考3在方法上增加注解 @Transactional

websocket导致测试类启动失败

加载需要加载servlet容器,根据
参考4中的解决方法
修改类上面的注解

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)

maven打包时去除 test

在这里插入图片描述

参考


  1. SpringBoot使用Junit单元测试 ↩︎

  2. 如何给一个私有方法做单元测试 ↩︎

  3. Spring Boot(五):如何在单元测试中自动回滚数据 ↩︎

  4. springboot整合websocket后运行测试类报javax.websocket.server.ServerContainer not available ↩︎

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值