Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
 ....
}
like image 424
Sabir Khan Avatar asked Sep 16 '25 21:09

Sabir Khan


1 Answers

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);

        //..
    }

}
like image 56
Peter Jurkovic Avatar answered Sep 18 '25 16:09

Peter Jurkovic