JUnit整合Spring
2021-04-20 03:27
标签:package context one end pack spring update app junit单元测试 1. 加入Spring-test依赖 2. 指定Spring的Runner方法 3. 指定主配置文件或主配置类 样例: JUnit整合Spring 标签:package context one end pack spring update app junit单元测试 原文地址:https://www.cnblogs.com/abuduri/p/13286072.htmldependency>
groupId>org.springframeworkgroupId>
artifactId>spring-testartifactId>
version>5.2.7.RELEASEversion>
dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@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 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);
}
}