为什么@RunWith(SpringJUnit4ClassRunner.class)不起作用?

Aid*_*uly 5 junit spring

我正在尝试使用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"));
    }}
Run Code Online (Sandbox Code Playgroud)

但是,使用@RunWith(SpringJUnit4ClassRunner.class)的代码会给我一个错误

**2014年6月11日下午1:00:15 org.springframework.test.context.TestContextManager retrieveTestExecutionListeners信息:无法实例化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"));
   }
Run Code Online (Sandbox Code Playgroud)

Ral*_*lph 9

您的测试中至少存在两个问题

  • 1)您不能在测试中使用标准ServletContext.要么使用Spring配置的一部分只使用不使用ServletContext的Beans,要么使用Spring-MVC-Test支持(从Spring 3.2开始提供)

  • 2)@BeforeClass在加载spring spring context之前运行.因此请@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"));
   }
Run Code Online (Sandbox Code Playgroud)