准备工作:
4.0.0 com.powernode spring6-015-junit 1.0-SNAPSHOT jar repository.spring.milestone Spring Milestone Repository https://repo.spring.io/milestone org.springframework spring-context 6.0.0-M2 org.springframework spring-test 6.0.0-M2 junit junit 4.13.2 test 17 17
package com.powernode.spring6.bean;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;/*** @author 动力节点* @version 1.0* @className User* @since 1.0**/
@Component
public class User {@Value("张三")private String name;@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +'}';}public String getName() {return name;}public void setName(String name) {this.name = name;}public User() {}public User(String name) {this.name = name;}
}
单元测试:
package com.powernode.spring6.test;import com.powernode.spring6.bean.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*** @author 动力节点* @version 1.0* @className SpringJUnit4Test* @since 1.0**/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class SpringJUnit4Test {@Autowiredprivate User user;@Testpublic void testUser(){System.out.println(user.getName());}
}
执行结果如下:

Spring提供的方便主要是这几个注解:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(“classpath:spring.xml”)
在单元测试类上使用这两个注解之后,在单元测试类中的属性上可以使用@Autowired。比较方便。
引入JUnit5的依赖,Spring对JUnit支持的依赖还是:spring-test,如下:
4.0.0 com.powernode spring6-015-junit 1.0-SNAPSHOT jar repository.spring.milestone Spring Milestone Repository https://repo.spring.io/milestone org.springframework spring-context 6.0.0-M2 org.springframework spring-test 6.0.0-M2 org.junit.jupiter junit-jupiter 5.9.0 test 17 17
package com.powernode.spring6.test;import com.powernode.spring6.bean.User;import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:spring.xml")
public class SpringJUnit5Test {@Autowiredprivate User user;@Test
//这个需要注意,是import org.junit.jupiter.api.Test;里面的Test,不是org中的,引错的话会出现空指针异常public void testUser(){System.out.println(user.getName());}
}
在JUnit5当中,可以使用Spring提供的以下两个注解,标注到单元测试类上,这样在类当中就可以使用@Autowired注解了。
@ExtendWith(SpringExtension.class)
@ContextConfiguration(“classpath:spring.xml”)
以上内容来自于动力节点老杜的spring6课程
b站动力节点spring6的spring6整合junit
上一篇:吃豆人游戏-第12届蓝桥杯Scratch选拔赛真题精选
下一篇:祝福新生儿的诗