问题描述
我正在尝试使用Spring框架使用JUnit测试CRUD方法.下面的代码运行完美
I am trying to test CRUD methods with JUnit using Spring framework. The code below works perfectly
@Transactional
public class TestJdbcDaoImpl {
@SuppressWarnings("deprecation")
@BeforeClass
@Test
public static void setUpBeforeClass() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
JdbcDaoImpl dao = ctx.getBean("jdbcDaoImpl",JdbcDaoImpl.class);
Circle cicle = new Circle();
dao.insertCircle(new Circle(6,"e"));
}}
但是,以下带有@RunWith(SpringJUnit4ClassRunner.class)的代码给我一个错误
** 2014年6月11日下午1:00:15 org.springframework.test.context.TestContextManager restoreTestExecutionListeners信息:无法实例化TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener].指定自定义侦听器类或使默认侦听器类(及其必需的依赖项)可用.令人反感的类:[javax/servlet/ServletContext]**
**Jun 11, 2014 1:00:15 PM org.springframework.test.context.TestContextManager retrieveTestExecutionListeners INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]**
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring.xml")
@Transactional
public class TestJdbcDaoImpl {
@Autowired
private static JdbcDaoImpl dao;
@SuppressWarnings("deprecation")
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Circle cicle = new Circle();
dao.insertCircle(new Circle(10,"e"));
}
推荐答案
您的测试中至少存在两个问题
There are at least two problems in your test
-
1)您不能在测试中使用标准的ServletContext.您要么使用仅使用不使用ServletContext的Bean的Spring配置的一部分,要么使用Spring-MVC-Test支持(从Spring 3.2开始可用)
1) You can not use the standard ServletContext in a test. Either you use a part of the Spring configuration that only uses Beans that not use the ServletContext, or you use the Spring-MVC-Test support (available since Spring 3.2)
2)@BeforeClass
在加载spring上下文之前运行.因此,请改用@Before
.
2) @BeforeClass
run before the spring context ins loaded. Therefore use @Before
instead.
试图解决这两个问题的示例:
Example that try to fix both problems:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration // <-- enable WebApp Test Support
@ContextConfiguration("/spring.xml")
@Transactional
public class TestJdbcDaoImpl {
@Autowired
private static JdbcDaoImpl dao;
@SuppressWarnings("deprecation")
@Before // <-- Before instead of BeforeClass
public static void setUpBeforeClass() throws Exception {
Circle cicle = new Circle();
dao.insertCircle(new Circle(10,"e"));
}
这篇关于为什么@RunWith(SpringJUnit4ClassRunner.class)不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!