其他分享
首页 > 其他分享> > Spring 基于junit进行测试

Spring 基于junit进行测试

作者:互联网

如何再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());
    }
}

标签:accountService,spring,Junit,public,测试,Spring,test,junit
来源: https://blog.csdn.net/acwing/article/details/120603534