整合原因
1、应用程序的入口main方法
2、junit单元测试中,没有main方法也能执行
junit集成了一个mian方法。该方法会判断测试类中的 @Test注解,junit会让有test注解的方法执行。
3、junit不知道我们是否使用了spring框架,所以不会为我们读取配置文件或配置类创建spring的IOC容器。
整合配置
1、导入spring整合junit的jar包。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
2、使用 spring的 @Runwith 注解替换junit的main方法。
3. @ContextConfiguration注解告知spring容器的创建时时基于XML还是注解配置类
属性:
class:指定注解类的字节码文件
location:指定XML的位置,加上cllasspath关键字,表示在类路径下
使用spring5.x版本时,junit必须是4.1.2及以上版本,否则会有无法初始化的异常
package org.example.service;
import config.SpringConfiguration;
import junit.framework.TestCase;
import org.example.pojo.Account;
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;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)//替换junit的main方法
@ContextConfiguration(classes = SpringConfiguration.class)//指定spring的配置
public class AccountServiceTest extends TestCase {
@Autowired
private AccountService accountService; //加上注解后就可以使用自动注入了
@Test
public void testFindAll() {
List<Account> all = accountService.findAll();
for (Account account: all) {
System.out.println(account);
}
}
@Test
public void testFindOne() {
Account accountById = accountService.findAccountById(1);
System.out.println(accountById);
}
@Test
public void testFindSave() {
Account account = new Account();
account.setName("ddd");
account.setMoney(100F);
accountService.saveAccount(account);
}
@Test
public void testFindUpdate() {
Account account = new Account();
account.setName("ddd");
account.setMoney(10000F);
account.setId(4);
accountService.updateAccount(account);
}
@Test
public void testFindDelete() {
Account account = new Account();
accountService.deleteAccount(4);
}
}