I hava this code ,
@RunWith(SpringJUnit4ClassRunner.class)
public class JunitDemo {
@Test
public void testAssertArrayEquals() {
byte[] expected = "trial".getBytes();
byte[] actual = "trial".getBytes();
Assert.assertArrayEquals("fail", expected, actual);
}
}
and run the test, there are errors
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
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);
}
}
in fact,for this pojo, i do'nt need the xml config. and i will get other error
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
How to correctly run my program ?
From the @ContextConfiguration docs:
@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.
Annotation itself has property loader
and doc says:
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.
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.
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"
This is good article about it.