JUnit testing of spring boot @value variable

Viewed 6279

I am trying to implement unit test for a method that tests 2 values in an "if". How can I do that ?

For the valService.validate part, I call a when.thenReturn and it works fine, but for the equals part, my test is not able to go green and when I debug I see it is not passing the first part of the if and that userTypeSpecific has a null value.

EDIT : I get the userTypeSpecific variable with a @value from my app.properties

My controller

@Value("${app.usertype.specific}")
String userTypeSpecific;

@PostMapping(value = "decline")
@ResponseBody
public ResponseEntity<Boolean> declineUser(@RequestParam final String idUser, @RequestHeader("userType") String userType) {
    HttpStatus httpStatus = HttpStatus.FORBIDDEN;
    Boolean result = false;

    if (userTypeSpecific.equals(userType) && valService.validate(idUser, userType)) {
        result = this.service.declineUser(idUser);
        if (result){
            httpStatus = HttpStatus.OK;
        }
    }
    return ResponseEntity.status(httpStatus).body(result);
}

Here is my test code :

@SpringBootTest
@ExtendWith(SpringExtension.class)
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {"app.usertype.specific=spec",})
public class UserControllerTest {
    @Mock
    IUserService service;

    @Value("${app.usertype.specific}")
    String userType;

    @Mock
    IValService valservice;

    @InjectMocks
    UserController controller;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Configuration
    static class Config {
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    }

    @Test
    public void testDeclineUser() {
        String idUser= "123";

        Assert.assertEquals("TEST userType", "gae", userType);
        when(valservice.validate(any(),any())).thenReturn(Boolean.TRUE);
        when(service.declineUser(idUser)).thenReturn(true);

        ResponseEntity<Boolean> resultStatus = controller.declineUser(idUser, userType);

        verify(this.service,times(1)).declinePieceJustif(numeroDemande);
        Assert.assertEquals("HTTP status test, HttpStatus.OK, resultStatus.getStatusCode());
        Assert.assertEquals ("Boolean status test", true, resultStatus.getBody());
    }



}
2 Answers

I found a way with ReflectionTestUtils.setField in the @Before method :

 @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        String userTypeSpecific ="spec";
        ReflectionTestUtils.setField(controller, "userTypeSpecific", userTypeSpecific);
    }
Related