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?
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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With