JUnit整合Spring
Posted 阿布都日
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JUnit整合Spring相关的知识,希望对你有一定的参考价值。
1. 加入Spring-test依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.7.RELEASE</version> </dependency>
2. 指定Spring的Runner方法
@RunWith(SpringJUnit4ClassRunner.class)
3. 指定主配置文件或主配置类
@ContextConfiguration(classes = Config.class) 或 @ContextConfiguration(locations = "classpath:bean.xml")
样例:
package com.example; import com.example.config.Config; import com.example.domain.Account; import com.example.service.IAccountService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * Spring整合JUnit单元测试,测试我们的配置 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) public class AccountServiceTest { @Autowired IAccountService as; @Test public void testFindAll() { List<Account> accounts = as.findAllAccount(); for(Account account : accounts){ System.out.println(account); } } @Test public void testFindOne() { Account account=as.findAccountById(1); System.out.println(account); } @Test public void testSave() { Account account=new Account("ddd",100); as.saveAccount(account); } @Test public void testUpdate() { Account account=new Account(2,"ddd",100); as.updateAccount(account); } @Test public void testDelete() { as.deleteAccount(1); } }
以上是关于JUnit整合Spring的主要内容,如果未能解决你的问题,请参考以下文章