Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mock Environment interface?

I am trying to test my service which looks like :

import org.springframework.core.env.Environment;

@Service
public class MyService {
@Autowired Environment env;
...
...
}

How do I mock Environment Interface, or else how do I create one?

like image 410
storm_buster Avatar asked Nov 05 '13 15:11

storm_buster


2 Answers

Spring provides mocks for property sources and the environment. Both of these can be found in the org.springframework.mock.env package of the spring-test module.

  • MockPropertySource: available since Spring Framework 3.1 -- Javadoc
  • MockEnvironment: available since Spring Framework 3.2 -- Javadoc

These are briefly documented in the reference manual in the Mock Objects section of the testing chapter.

Regards,

Sam

like image 129
Sam Brannen Avatar answered Oct 01 '22 11:10

Sam Brannen


Using Mockito, you should be able to do it somewhat like the code below. Note that you need to either provide accessors so that you can set the Environment field at runtime. Alternatively, if you only have a couple of autowired fields, it can be cleaner to define a constructor where you can inject the Environment.

import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

public class MyServicetest {

    // Define the Environment as a Mockito mock object
    @Mock Environment env;

    MyService myService;

    @Before
    public void init() {
        // Boilerplate for initialising mocks 
        initMocks();

        // Define how your mock object should behave
        when(this.env.getProperty("MyProp")).thenReturn("MyValue");

        // Initialise your service
        myService = new MyServiceImpl();

        // Ensure that your service uses your mock environment
        myService.setEnvironment(this.env);
    }

    @Test
    public void shouldDoSomething() {
        // your test
    }

}
like image 35
Steve Avatar answered Oct 01 '22 11:10

Steve