java - Mockito 使用 Spring Boot 模拟 Java @Value

标签 java spring spring-boot unit-testing mockito

您好,我的 Spring Boot 项目有这个简单的代码:

@Component
public class UserRowMapper implements RowMapper<User> {
    @Value("${bug.value}")
    private String id;
    @Value("${wrong.value}")
    private String userName;

    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        return User.builder()
                .id(rs.getInt(id))
                .userName(rs.getString(userName)).build();
    }
}

我想要的是创建一个简单的 Mockito 测试来检查 @Value 字符串,如下所示:


@ExtendWith(MockitoExtension.class)
class UserRowMapperTest {
    @Mock
    Environment environment;
    @Mock
    ResultSet resultSet;
    @InjectMocks
    UserRowMapper userRowMapper;

    @Test
    void testMapRow() {
        when(environment.getProperty("user.id")).thenReturn("id");
        when(environment.getProperty("user.userName")).thenReturn("userName");
        try {
            final User user = userRowMapper.mapRow(resultSet, anyInt());
            
            // check if its ok
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

但是我找不到一种简单的方法来检查我注入(inject)的值是否是我所期望的。

有什么想法吗?

最佳答案

不幸的是,Spring的@Value没有模拟机制。但是,您可以使用 ReflectionUtils 来使用简单的解决方法。根据 JavaDoc,它用于此目的:

ReflectionTestUtils is a collection of reflection-based utility methods for use in unit and integration testing scenarios.

There are often times when it would be beneficial to be able to set a non-public field, invoke a non-public setter method, or invoke a non-public configuration or lifecycle callback method when testing code involving

ReflectionTestUtils.setField(userRowMapper, "id", "my-id-value");
ReflectionTestUtils.setField(userRowMapper, "userName", "my-userName-value");

JavaDoc ReflectionTestUtils#setField(Object, String, Object) .

关于java - Mockito 使用 Spring Boot 模拟 Java @Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68622921/

相关文章:

Java 文本字段聚焦

java:如何在不知道对象类型的情况下调用arraylist上的方法

java - 类型 : Often this message means that you are missing a { BEFORE this line 非法开始

java - Spring 依赖注入(inject) : How to Instantiate Class based on system property?

java - 如何在 Spring 使用 EnableScheduling 注释在运行时重新启动计划任务?

logging - Spring Boot - 设置使用 Java Util Logging (jul) 的外部 jar 的日志记录级别

spring - 如何在 Mac 上安装 spring boot CLI?

java 。工件部署 Tomcat 8 期间出错

spring - 如何在bootJar中有条件地启用launchScript()?

java - 如何从 gradle.properties 获取属性到 application.yaml