Spring Boot 单元测试无法 mock @Value 标注的字段
Spring Boot About 456 words代码
@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);
}
Views: 1,330 · Posted: 2023-02-23
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...