Spring Boot 单元测试无法 mock @Value 标注的字段
Spring Boot 大约 456 字代码
@Service
public class HiServiceImpl implements HiService {
@Value("${server.port}")
int port;
@Override
public int sayHi() {
System.out.println("HiServiceImpl sayHi: " + port);
return port;
}
}
解决方法
使用Spring Boot Test
包下的ReflectionTestUtils
,反射设置字段。
import org.springframework.test.util.ReflectionTestUtils;
@Mock
HiService hiService;
@Test
void test() {
ReflectionTestUtils.setField(hiService, "port", 100);
}
阅读 96 · 发布于 2023-02-23
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Spring Boot 在拦截器中获取 Controller 中的注解阅读 185
-
IDEA 滚轮调节字体大小阅读 2265
-
Nginx 负载均衡 WebSocket 请求阅读 1917
-
Arthas 使用 tt 命令抓取调用异常、调用耗时、传入参数、返回参数阅读 3119
-
MySQL 索引条件下推阅读 956
-
IDEA Cannot resolve plugin org.apache.maven.plugins:maven-clean-plugin:2.5阅读 1956
-
Linux -bash: rz: command not found阅读 1906
-
MySQL Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root阅读 3709
-
Nginx 开启 HTTP2.0阅读 2087
-
GoLand 提示 Receiver has generic name阅读 1946