Spring 基于junit进行测试

本文介绍了如何在JUnit测试中利用Spring的资源,包括设置SpringJUnit4ClassRunner来让Spring接管测试,通过@ContextConfiguration指定Spring上下文配置文件,确保Junit版本与Spring版本兼容,并提供了一个测试类的示例,展示了如何注入并测试服务。

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

如何再Junit中使用spring中的资源

Spring接管Junit的运行权     使用Spring专用的Junit类加载器

为Junit测试用例设定对应的spring容器

从Spring5.0之后  要求Junit的版本必须是4.2及以上

Junit仅用于单元测试 不能将Junit的测试类配置成spring的bean 否则该配置将会被打包进入工程中

对应pom.xml中加入

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

对应的测试类

/  设定spring专用的类加载器
@RunWith(SpringJUnit4ClassRunner.class)
//  设定加载的spring上下文对应的配置
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void testFindById(){
        Account byId = accountService.findById(2);
//        System.out.println(byId);
        //                  预期值           实际值   进行对比
        Assert.assertEquals("Tom",byId.getName());
    }

    @Test
    public void testFindall(){
        List<Account> list = accountService.findAll();
        Assert.assertEquals(2,list.size());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值