abhinav.varshney
abhinav.varshney

Reputation: 51

How to mock Environment Interface

I have to fetch path from the property file using Environment interface. In Junits I am not able to mock the Environment Interface. Below is my code. I want something random if I will call the method mentioned. How can I do it?

@Mock
    private Class object;
 @InjectMocks
    Class2 object2;

Mockito.when(object.getFilePath()).thenReturn("Random String");

Upvotes: 5

Views: 13542

Answers (2)

J-J
J-J

Reputation: 5871

If you are using Mockito, you can do it as follows.

import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
class SampleMockitoTest {
    
    @Mock
    private Environment mockEnvironment;
    
    @Test
    public void sampleTest() {
        //use mockEnvironment here
        when(environment.getProperty("yourKey")).thenReturn("yourValue");
    }
}

Upvotes: 2

davidxxx
davidxxx

Reputation: 131346

As said in my comment, you don't need Mockito, you can use MockEnvironment class to mock Environment from Spring.
You can set values in this way :

    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("yourKeyOne", "yourValue1");
    environment.setProperty("yourKeyTwo", "yourValue2");

And according to your need, you can use this environment variable. For example, here is with an AnnotationConfigWebApplicationContext instance :

    AnnotationConfigWebApplicationContext context = new  AnnotationConfigWebApplicationContext();
    context.setEnvironment(environment);

Upvotes: 8

Related Questions