【问题标题】:@RunWith(SpringJUnit4ClassRunner.class) Can not load an ApplicationContext with a NULL 'contextLoader'@RunWith(SpringJUnit4ClassRunner.class) 无法使用 NULL 'contextLoader' 加载 ApplicationContext
【发布时间】:2017-07-05 05:22:11
【问题描述】:

我有这个代码,

@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:无法加载 带有 NULL 'contextLoader' 的 ApplicationContext。考虑注释 使用@ContextConfiguration 的测试类。 在 org.springframework.util.Assert.notNull(Assert.java:112) 在 org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:276) 在 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 更多

如何正确运行我的程序?

【问题讨论】:

  • 您的应用中有@Configuration 类吗?或者你使用基于 xml 的配置?

标签: spring junit springjunit4classrunner


【解决方案1】:

来自@ContextConfiguration 文档:

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

注释本身有属性loader 并且文档说:

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

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

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

在您的情况下,看起来像 spring 选择 GenericXmlContextLoader 进行上下文加载,您没有指定位置,因此 ApplicationConext 将从“classpath:/com/example/your _test_class_name>-context.xml"

这是good article关于它的。

【讨论】:

    【解决方案2】:

    添加类似的东西

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

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

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 2021-06-22
      • 1970-01-01
      • 2015-10-07
      • 2013-04-30
      • 2021-05-05
      • 2012-08-29
      • 2018-01-23
      相关资源
      最近更新 更多