To manipulate an application properties variable during testing using Mockito and Junit Jupiter, you can follow these steps:
- Create a test class for your Spring Boot application test.
- Use the
@SpringBootTest annotation on the test class to load the application context.
- Inject the
Environment object into your test class using the @Autowired annotation.
- Use Mockito to mock the
Environment object and manipulate the application properties.
Here's an example:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@SpringBootTest
public class MyApplicationTest {
@Autowired
private Environment environment;
@Mock
private Environment mockEnvironment;
@Test
public void testApplicationPropertyManipulation() {
// Mock the behavior of the application property
when(mockEnvironment.getProperty("my.property")).thenReturn("mocked value");
// Use the mocked environment instead of the actual environment
when(environment.getProperty("my.property")).thenReturn(mockEnvironment.getProperty("my.property"));
// Test your code that uses the application property
// ...
// Verify the interactions if needed
// ...
}
}
In this example, we have a test class MyApplicationTest that is annotated with @SpringBootTest to load the application context. We then inject the Environment object using @Autowired.
We also mock the Environment object using @Mock and MockitoExtension. We can then use Mockito's when method to mock the behavior of the application property, and use this mocked environment when testing our code.
By manipulating the mocked environment's behavior, we can control the value of the application property during testing.