gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:18:27 29 4
gpt4 key购买 nike

您好,我的 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com