0

I have a class (ConfigurationReaderUtil) that loads an XML config file to beans (with the simpleframework). There is an other class (let's name it as XXX class) that uses the beans that are loaded by the ConfigurationReaderUtil.
I want to test the class XXX. It is important to test the wrong cases when there are invalid data in the XML config file. So at the moment I have a XML file in the src/test/resource that can be used to test the successful cases. I'd also need more XML file in the src/test/resource for testing the wrong cases.
However I have something like this in the ConfigurationReaderUtil:

InputStream in = new ClassPathResource(Constants.PATH_TEMPLATE_CONFIG_XML).getInputStream();
templatesBean = serializer.read(TemplatesBean.class, in);

So what I'd need is to load different XML files for different unit tests. I really don't know how I could achieve this. Can I define somehow in the unit test which test XML file I need? However in this case how should I write the ConfigurationReaderUtil class?
Hmm, this is the dilemma...
Thanks, V.

1 Answer 1

1

You're doing it wrong. Your XXX class doesn't deal with XML parsing. It deals with beans that are read by another class from an XML resource. So, the unit test of XXX shouldn't use XML files as inputs, but instances of beans that would normally be created by the other class, but that you should create by hand in the unit test of XXX:

@Test
public void testWithInvalidInput() {
    SomeBean invalid = new SomeBean();
    invalid.setValue("invalidValue");
    XXX xxx = new XXX();
    xxx.doSomeWork(invalid);
    // now check that doSomeWork does the right thing
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi JB Nizet, thanks for the reply. My XXX class just calls a method of the ConfigurationReaderUtil and it doesn't deal with XML parsing or io operations. All these things are handled in the ConfigurationReaderUtil. I want to test some bad situation when there is incorrect data in the config file and how they are handled in the XXX class. So I thought I need a correct config file and some incorrect one. I don't know how to control in the unit test which config file is loaded. I should define more ConfigurationReaderUtil beans in the Spring contex XML and setting the path of xml as a property?
I understand that. You should test XXX in isolation. So, make ConfigurationReaderUtil a Spring bean that is injected into XXX. In your unit test, inject a mock instance that will return invalid data, without even reading any file, just by returning a hard-coded invalid bean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.