导入spring测试的jar包
Spring测试必须保证Eclipse的单元测试的最低版本是 4.12版本,如果使用的Eclipse版本很低,那么单元测试版本可能低于4.12,那么需要开发者手动导入单元测试的jar包。
Spring测试必须使用单元测试测试,不可以使用main方法
如果使用Spring方式测试,必须使用两个注解
@RunWith注解
表示先启动Spring容器,把junit运行在Spring容器中
@ContextConfiguration注解
从哪里加载资源文件,默认从src(源目录)下面加载
xml方式配置
package com.spring.test;
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 com.spring.config.SpringConfig;
import com.spring.controller.CustomController;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class SpringTest {
@Autowired
private CustomController controller;
@Test
public void testInsert() throws Exception {
controller.insert();
}
@Test
public void testDelete() throws Exception {
controller.delete();
}
}
纯注解方式的配置
package com.spring.test;
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 com.spring.config.SpringConfig;
import com.spring.controller.CustomController;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class SpringTest {
@Autowired
private CustomController controller;
@Test
public void testInsert() throws Exception {
controller.insert();
}
@Test
public void testDelete() throws Exception {
controller.delete();
}
}