Reputation: 177
I am using MockitoJUnit library to test my controller. there are some variables which are declared as:
@Value("${mine.port}")
private Integer port;
when I run my test, it could not find the value mine.port in the resource folder as properties file. My controller is no problem to run, but the port number is null when I run my contoller junit test.
I used below annotation on my class:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(classes = myControl.class)
@WebAppConfiguration
@AutoConfigureMockMvc
I used below method in my junit test
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(myController)
.build();
}
@Test
public void getName() throws Exception {
MockHttpServletRequestBuilder request =
MockMvcRequestBuilders.get("/service")
.contentType(MediaType.APPLICATION_JSON_VALUE);
MvcResult result = mockMvc.perform(request)
.andExpect(status().isOk()).andReturn(); }
I am confused, does anyone know if I am missing some settings? thx!
Upvotes: 1
Views: 819
Reputation: 131326
No one of the specified annotations will start a Spring container :
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(classes = myControl.class)
@WebAppConfiguration
@AutoConfigureMockMvc
To write a test slice focused on the controller don't use a Mockito runner : @RunWith(MockitoJUnitRunner.class)
otherwise you could not start a Spring container. MockitoJUnitRunner
is for unit tests, not integration tests.
To know when and how to write unit and integration tests with Spring Boot you could read this question.
Instead of, use the @WebMvcTest
annotation with a Spring runner such as :
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@WebMvcTest
public class WebLayerTest {
...
}
You can rely on this Spring guide to have more details.
Upvotes: 2