Arsha
Arsha

Reputation: 125

How to load values from custom properties file for junit testing using Mockito?

I have written this test class to check a service. This is in folder test/java/example/demp/Test.java

@RunWith(MockitoJUnitRunner.class)
@TestPropertySource("classpath:conn.properties")

public class DisplayServiceTest {


@Value("${id}")
private String value; 


@Mock
private DisplayRepository DisplayReps;

@InjectMocks
private DisplayService DisplayService;

@Test
public void whenFindAll_thenReturnProductList() {

Menu m = new Menu()
m.setId(value); //when I print value its showing 0

List<Display> expectedDisplay = Arrays.asList(m);
doReturn(expectedDisplay).when(DisplayReps).findAll();
List<Display> actualDisplay = DisplayService.findAll();
assertThat(actualDisplay).isEqualTo(expectedDisplay);
}

My properties file This is in folder test/resources/conn.properties

id=2

What is the right way to set properties from custom properties file? Cause its not loading values ?

Upvotes: 2

Views: 19952

Answers (3)

Jose Tepedino
Jose Tepedino

Reputation: 1584

You could use just Mockito and JUnit 4. At the @Before method, call MockitoAnnotations.initMocks and load the properties file:

public class DisplayServiceTest {

    private String value;

    @Mock
    private DisplayRepository displayReps;

    @InjectMocks
    private DisplayService displayService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        Properties prop = loadPropertiesFromFile("conn.properties");
        this.value = prop.getProperty("id");
    }

    private Properties loadPropertiesFromFile(String fileName) {
        Properties prop = new Properties();
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream stream = loader.getResourceAsStream(fileName);
            prop.load(stream);
            stream.close();
        } catch (Exception e) {
            String msg = String.format("Failed to load file '%s' - %s - %s", fileName, e.getClass().getName(),
                    e.getMessage());
            Assert.fail(msg);
        }
        return prop;
    }

    @Test
    public void whenFindAll_thenReturnProductList() {

        System.out.println("value: " + this.value);

        Menu m = new Menu();
        m.setId(this.value); // when I print value its showing 0

        List<Display> expectedDisplay = Arrays.asList(m);

        Mockito.doReturn(expectedDisplay).when(this.displayReps).findAll();

        List<Display> actualDisplay = this.displayService.findAll();

        Assert.assertEquals(expectedDisplay, actualDisplay);
    }

}

Upvotes: 1

Mark Bramnik
Mark Bramnik

Reputation: 42431

Mockito is a mocking framework, so in general you can't load properties file with Mockito.

Now you've used @TestPropertySource which is a part of Spring Testing and it indeed allows loading properties file (that have nothing to do with mockito though). However using it requires running with SpringRunner and in general its good for integration tests, not for unit tests (Spring Runner among primarily loads Spring's application context).

So if you don't want to use spring here, you should do it "manually". There are many different ways to load Properties file from class path (with getClass().getResourceAsStream() to get the input stream pointing on the resource file and the read it into Properties by using Properties#load(InputStream) for example.

You can also use other thirdparties (not mockito), like apache commons io to read the stream with IOUtils class

If you want to integrate with JUnit 4.x you can even create a rule, described here

Upvotes: 2

second
second

Reputation: 4259

@TestPropertySource is a spring annotation, so you need to use the SpringRunner.
You can initialize Mockito using MockitoAnnotations.initMocks(this);, check the example below.

@RunWith(SpringRunner.class)
@TestPropertySource("classpath:conn.properties")
public class DisplayServiceTest {

    @Value("${id}")
    private String value; 

    // ...

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    // ...
}

Upvotes: 0

Related Questions