spring和SpringBoot配置junit

Spring整合junit:

1.导入(spring-test和junit)jar的maven坐标(junit使用版本1.12及以上)

2.使用spring的Runwith注解替换SpringJUnit4ClassRunner类(junit整合了main方法)

3.导入spring的配置文件

spring配置test

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")

@RunWith :用来代替SpringJUnit4ClassRunner类,让spring管理test方法

@ContextConfiguration: 用来引入配置文件

springboot和spring类似

pom.xml和java注解

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
</dependency>
@RunWith(SpringRunner.class)
@SpringBootTest(classes = XXXApplication.class)
@WebAppConfiguration

XXXApplication.class:是指springboot的启动类(不写这个会导致无法注入)

@RunWith :用来代替SpringJUnit4ClassRunner类,让spring管理test方法

@SpringBootTest : 让springboot找到启动项

@WebAppConfiguration : 表示扫描配置问题,默认就是springboot的配置

类命名方式 测试类+Test; 方法命名方式 test+方法名;

报错1

没有设置JUnit4

改成JUnit4

报错2 maven install时,找不到测试类

将maven插件中改成<skip>true</skip>

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
</build>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值