Spring Boot @value 变量的 JUnit 测试

hel*_*ode 3 java junit spring mockito spring-boot

我正在尝试为在“if”中测试 2 个值的方法实现单元测试。我怎样才能做到这一点 ?

对于 valService.validate 部分,我调用 when.thenReturn 并且它工作正常,但是对于 equals 部分,我的测试无法变绿,当我调试时,我发现它没有通过 if 的第一部分,并且userTypeSpecific 具有值。

编辑:我从 app.properties 中获取带有 @value 的 userTypeSpecific 变量

我的控制器

@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);
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码:

@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());
    }



}
Run Code Online (Sandbox Code Playgroud)

hel*_*ode 6

我在 @Before 方法中找到了一种使用 ReflectionTestUtils.setField 的方法:

 @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        String userTypeSpecific ="spec";
        ReflectionTestUtils.setField(controller, "userTypeSpecific", userTypeSpecific);
    }
Run Code Online (Sandbox Code Playgroud)