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

被折叠的 条评论
为什么被折叠?



