Spring整合Junit

Spring整合Junit

Spring整合Junit_第1张图片

在之前文章中Spring的测试方法几乎都能够看到如下的代码:

ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml");
XXX xxx = context.getBean(XXX.class);

它的作用是创建Spring容器,最终获取到对象,但是在每次测试时都需要重复编写。造成代码冗余。可以通过Spring整合JUnit可以使程序创建spring容器。

步骤

1、引入依赖

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>6.0.9version>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-aopartifactId>
    <version>6.0.9version>
dependency>

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-aspectsartifactId>
    <version>6.0.9version>
dependency>
<dependency>
    <groupId>org.junit.jupitergroupId>
    <artifactId>junit-jupiter-apiartifactId>
    <version>5.10.0-M1version>
    <scope>testscope>
dependency>

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.2.5.RELEASEversion>
dependency>

2、bean.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <context:component-scan base-package="com.louis.junitTest">context:component-scan>
beans>

3、创建目标类

@Component
public class User {
    public void user(){
        System.out.println("User.....");
    }
}

4、创建测试类

①JUnit5

方式一

@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean.xml")

方式二

@SpringJUnitConfig(locations = "classpath:bean.xml")
public class TestUser {
    //注入
    @Autowired
    private User users;

    @Test
    public void test(){
        users.user();
    }
}

/*
* User.....
 */

②JUnit4

依赖
<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.13.2version>
    <scope>testscope>
dependency>
整合JUnit4
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class TestJUnit {
    //注入User
    @Autowired
    private User user;

    @Test
    public void testUser(){
        user.user();
    }
}

/*
* User.....
* */

你可能感兴趣的:(Spring,spring,junit,sqlserver)