gpt4 book ai didi

spring - @RunWith(SpringJUnit4ClassRunner.class) 无法加载带有 NULL 的 ApplicationContext 'contextLoader'

转载 作者:行者123 更新时间:2023-12-02 09:58:37 27 4
gpt4 key购买 nike

我有这个代码,

@RunWith(SpringJUnit4ClassRunner.class)
public class JunitDemo {

@Test
public void testAssertArrayEquals() {

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

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

并运行测试,出现错误

Caused by: java.lang.IllegalArgumentException: Can not load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration. at 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 more

然后,我找到了与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配置。我会得到其他错误

Caused by: java.io.FileNotFoundException: class path resource [/JunitDemo-context.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ... 37 more

如何正确运行我的程序?

最佳答案

来自@ContextConfiguration文档:

@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.

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

If not specified, the loader will be inherited from the first superclass that is annotated with @ContextConfiguration and specifies an explicit loader. If no class in the hierarchy specifies an explicit loader, a default loader will be used instead.

The default concrete implementation chosen at runtime.

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

在您的情况下,Spring 选择 GenericXmlContextLoader 进行上下文加载,您没有指定位置,因此 ApplicationConext 将从“classpath:/com/example/<您的_test_class_name>-context.xml”

这是good article关于它。

关于spring - @RunWith(SpringJUnit4ClassRunner.class) 无法加载带有 NULL 的 ApplicationContext 'contextLoader',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42268181/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com