我正在尝试使用Spring框架使用JUnit测试CRUD方法。下面的代码可以完美地工作
@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]
**
@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"));
}
最佳答案
您的测试中至少有两个问题
@BeforeClass
在spring上下文ins加载之前运行。因此,请改为使用@Before
。 试图解决这两个问题的示例:
@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"));
}
关于spring - 为什么@RunWith(SpringJUnit4ClassRunner.class)不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24156450/