Biplab Mitra
Biplab Mitra

Reputation: 337

Junit: How to test a method that read properties from a property file

Hi I have a class ReadProperty which has a method ReadPropertyFile of return type Myclass which read the parameter values from a property file and return Myclass object. I need help to test the ReadPropertyFile method with JUnit, if possible with mock files and mock object.

Here is my code.

import java.io.FileInputStream;
import java.util.Properties;

public class ReadProperty {

    public Myclass ReadPropertyFile(String fileName) {
        Myclass myclass = null;
        String testparam = null;

        FileInputStream fis = null;



        Properties prop = new Properties();
        try {
            fis = new FileInputStream(fileName);
            try {
                prop.load(fis);
                System.out.println("Load Property file : Success !");
            } catch (Exception ex) {
                System.out.println("Load Property file : Exception : " + ex.toString());
            }
            /*
             * loading the properties
             */
            try {
                testparam = prop.getProperty("testparam");
                System.out.println("testparam Type : " + testparam);
            } catch (Exception ex) {
                System.out.println("testparam Type : " + ex.toString());
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("Property file read fail : " + ex.toString());
            System.exit(1);
        }
        Myclass = new Myclass(testparam);
        return Myclass;
    } }

Upvotes: 6

Views: 12419

Answers (1)

kostja
kostja

Reputation: 61538

I don't think that you really need to mock anything here. You want to test if your property reader is able to access and read a file as you expect, so test exactly that. For regular properties it can go like this:

@Test
public void shouldReadPropFileFromSingleString() {

    final Properties p = PropertiesLoader
            .loadProperties("propfile");
    assertNotNull(p);
    assertFalse(p.isEmpty());
    for (final Entry<Object, Object> e : p.entrySet()) {
        assertEquals(expectedProperties.get(e.getKey()), e.getValue());
    }
}

For your case, you can adapt it:

@Test
public void shouldReadCorrectProp() {

    final MyClass p = ReadProperty
            .readPropertyFile("propfile");
    assertNotNull(p);
    assertEquals(expectedProperty, p);
}

You may also want to test the sad path - what happens if the property file is not found, are any fallback properties available etc.

BTW, I would advise changing the method name, since reading a property file is not the primary concern of your method - retrieving a property is. Better yet, decompose the method into a getProperty and a readPropertyFile method, where the first method calls the second. So you will have a cleaner design according to Separaton of Concerns

Upvotes: 3

Related Questions