本文介绍了@RunWith(SpringJUnit4ClassRunner.class)无法使用NULL'contextLoader'加载ApplicationContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码,

@RunWith(SpringJUnit4ClassRunner.class)
public class JunitDemo {

    @Test
    public void testAssertArrayEquals() {

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

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

并运行测试,有错误

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

then, i find a same Q with SO,the solution is

@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配置.我会收到其他错误

in fact,for this pojo, i do'nt need the xml config.and i will get other error

如何正确运行我的程序?

How to correctly run my program ?

推荐答案

来自 @ ContextConfiguration docs:

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

Annotation itself has property loader and doc says:

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

The default concrete implementation chosen at runtime.

因此您可以指定上下文.要导航到直接配置,请对XML使用locations,对带注释的类config使用classes.

So you can specify context loader directly with loader property. To navigate to direct configuration use locations for xml and classes for annotated class config.

在您看来是弹簧选择GenericXmlContextLoader进行上下文加载的情况下,您无需指定位置,因此ApplicationConext将从"classpath:/com/example/< _test_class_name >-context.xml"

In you case looks like spring chosen GenericXmlContextLoader for context loading, you don't specify location so ApplicationConext will be loaded from "classpath:/com/example/<your_test_class_name>-context.xml"

这是关于它的好文章.

这篇关于@RunWith(SpringJUnit4ClassRunner.class)无法使用NULL'contextLoader'加载ApplicationContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:47