3

我有这个代码,

@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) 中不存在。 springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ... 37 更多

如何正确运行我的程序?</p>

4

2 回答 2

1

来自@ContextConfiguration文档:

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

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

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

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

所以你可以直接用属性指定上下文加载器。loader导航到locations用于 xml 和classes带注释的类配置的直接配置。

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

这是一篇关于它的好文章

于 2017-02-16T08:30:40.050 回答
0

添加这样的东西

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

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

于 2017-02-16T08:23:01.917 回答