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: 987 · Posted: 2023-02-23

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh