Search code examples
javaunit-testingspring-mvcspring-restcontroller

Spring MVC Controller Unit Testing : How do I set private instance boolean field?


I have a Spring MVC REST controller class that has a private instance boolean field injected via @Value ,

@Value("${...property_name..}")
private boolean isFileIndex;

Now to unit test this controller class, I need to inject this boolean.

How do I do that with MockMvc?

I can use reflection but MockMvc instance doesn't give me underlying controller instance to pass to Field.setBoolean() method.

Test class runs without mocking or injecting this dependency with value always being false. I need to set it to true to cover all paths.

Set up looks like below.

@RunWith(SpringRunner.class)
@WebMvcTest(value=Controller.class,secure=false)
public class IndexControllerTest {

    @Autowired
    private MockMvc mockMvc;
 ....
}

Solution

  • You can use @TestPropertySource

    @TestPropertySource(properties = {
        "...property_name..=testValue",
    })
    @RunWith(SpringRunner.class)
    @WebMvcTest(value=Controller.class,secure=false)
    public class IndexControllerTest {
    
        @Autowired
        private MockMvc mockMvc;
    
    }
    

    You can also load your test properties form a file

    @TestPropertySource(locations = "classpath:test.properties")
    

    EDIT: Some other possible alternative

    @RunWith(SpringRunner.class)
    @WebMvcTest(value=Controller.class,secure=false)
    public class IndexControllerTest {
    
        @Autowired
        private MockMvc mockMvc;
    
        @Autowired 
        private Controller controllerUnderTheTest;
    
    
        @Test
        public void test(){
            ReflectionTestUtils.setField(controllerUnderTheTest, "isFileIndex", Boolean.TRUE);
    
            //..
        }
    
    }