3
votes

I am learning Spring and am working on a unit test, with the beans being specified in an XML config file. I am wondering how I tell it to use a file on the file system.

The following code* will run:

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("beans.xml")
public class CDPlayerTest {
    ...
}

The beans.xml file is in the same package as the test class.

But when using

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/Users/pabernathy/pworkspace/springtraining/beans.xml")
public class CDPlayerTest {
    ...
}

It gives me this error message:

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [Users/pabernathy/pworkspace/springtraining/beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [Users/pabernathy/pworkspace/springtraining/beans.xml] cannot be opened because it does not exist

I can assure you, the file does exist.

Does anyone know how to specify an arbitrary XML file for the Spring beans?

*based on the example in chapter 2 of Spring in Action

2

2 Answers

1
votes

If you look at the error message closely, you'll see that spring stripped away the leading slash on the file path. By default, spring assumes the file exists in the class path somewhere. Try this:

@ContextConfiguration("file:/Users/pabernathy/pworkspace/springtraining/beans.xml")

file: overrides the default spring behavior and informs spring that it is an absolute path.

1
votes

try annotating like this

@ContextConfiguration(locations={"file://beans.xml"}). if that wont work just specify the whole path as @ContextConfiguration(locations={"file://users/blah/blah/beans.xml"}) and you should be good.