我有以下服务:
@Service
@RequiredArgsConstructor
public class Service {
@Value("${filename}")
private String filename;
private final Repository repository;
}
我试着测试它,我想用application-test.yml
中的一个特定值来解析filename
:
filename: a beautiful name
到目前为止,我的测试如下:
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Value("${filename}")
private String filename;
@Mock
private Repository repository;
@InjectMocks
private Service service;
}
如何正确初始化filename
?
1条答案
按热度按时间n3schb8v1#
由于您使用的是Mockito,Spring并不真正参与测试的引导,因此像
@Value
或application-test.yml
这样的东西没有任何意义。最好的解决方案是将
Service
中的filename
属性添加到构造函数中(如repository
):这允许您通过在测试中调用构造函数来注入所需的任何值: