Search code examples
javajunitmockito

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 ?


Solution

  • 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