@RunWith(SpringJUnit4ClassRunner.class)无法使用NULL' contextLoader'加载ApplicationContext。

时间:2017-02-16 08:07:10

标签: spring junit springjunit4classrunner

我有这个代码,

@RunWith(SpringJUnit4ClassRunner.class)
public class JunitDemo {

    @Test
    public void testAssertArrayEquals() {

        byte[] expected = "trial".getBytes();
        byte[] actual = "trial".getBytes();

        Assert.assertArrayEquals("fail", expected, actual);
    }
}

并运行测试,有错误

  

引起:java.lang.IllegalArgumentException:无法加载   ApplicationContext带有NULL' contextLoader'。考虑注释   你的测试类使用@ContextConfiguration。         在org.springframework.util.Assert.notNull(Assert.java:112)         at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:276)         at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)         ......还有28个

然后,我找到了与SO相同的Q,解决方案是

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class JunitDemo {

    @Resource
    private ApplicationContext ApplicationContext;

    @Test
    public void testAssertArrayEquals() {

        byte[] expected = "trial".getBytes();
        byte[] actual = "trial".getBytes();

        Assert.assertArrayEquals("fail", expected, actual);
    }
}

事实上,对于这个pojo,我确实需要xml配置。 我会得到其他错误

  

引起:java.io.FileNotFoundException:类路径资源   无法打开[/JunitDemo-context.xml],因为它不存在             在org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)             在org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)             ......还有37个

如何正确运行我的程序?

2 个答案:

答案 0 :(得分:1)

来自@ContextConfiguration文档:

  

@ContextConfiguration定义用于的类级元数据   确定如何加载和配置ApplicationContext   集成测试。

注释本身具有属性loader,doc说:

  

如果未指定,则加载器将从第一个继承   使用@ContextConfiguration注释并指定的超类   显式加载器。如果层次结构中没有类指定显式   loader,将使用默认加载器。

     

在运行时选择的默认具体实现。

因此,您可以直接使用loader属性指定上下文loader。要导航到直接配置,请使用locations表示xml,classes表示已注释的类配置。

在你的情况下看起来像春天选择GenericXmlContextLoader进行上下文加载,你没有指定位置,所以ApplicationConext将从" classpath:/ com / example /< 加载你的 _test_class_name > -context.xml"

这是good article

答案 1 :(得分:0)

添加类似这样的内容

@ContextConfiguration(locations = {"/test-spring.xml"})

其中xml包含测试上下文(在最简单的情况下,它与应用程序上下文相同)来加载/自动装载所有依赖项