两种方法都要用到Junit JAR包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
方法一:直接在测试类的头部加注解的方式(配合Spring-test)
所加注解为
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext.xml")
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import top.flytop.studentsign.pojo.Student;
import top.flytop.studentsign.service.impl.UserServiceImpl;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext.xml")
public class UserTest {
@Resource
public UserServiceImpl userServiceImpl;
@Test
public void testGetStuInfo() {
System.out.println(userServiceImpl);
Student s = userServiceImpl.getStuAllInfo(1);
System.out.println(s);
}
}
注意:需要引入Spring-test JAR包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.18.RELEASE</version>
<scope>test</scope>
</dependency>
此处,如果 @ContextConfiguration()引入的配置文件有多个,可按照如下方式书写(location为该注解默认属性,属性名可省略):
@ContextConfiguration(locations = { "classpath*:/spring1.xml", "classpath*:/spring2.xml" })
方法二:手动加载Spring容器,以getBean()的方式获取对象。(不需要Spring-test JAR包)
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.flytop.studentsign.pojo.Student;
import top.flytop.studentsign.service.impl.UserServiceImpl;
import javax.annotation.Resource;
public class UserTest {
//创建Spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
//从Spring容器中获取UserDao对象
UserServiceImpl userServiceImpl = ac.getBean("userServiceImpl",UserServiceImpl.class);
@Test
public void testGetStuInfo() {
System.out.println(userServiceImpl);
Student s = userServiceImpl.getStuAllInfo(1);
System.out.println(s);
}
}