如何在测试中用资源解析@Value

thm*_*ker 1 java testing junit spring spring-boot

我有以下服务:

@Service
@RequiredArgsConstructor
public class Service {

    @Value("${filename}")
    private String filename;

    private final Repository repository;

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试测试它,为此我想filename使用以下特定值来解决application-test.yml

filename: a beautiful name
Run Code Online (Sandbox Code Playgroud)

到目前为止,我的测试如下:

@ExtendWith(MockitoExtension.class)
class ServiceTest {

    @Value("${filename}")
    private String filename;

    @Mock
    private Repository repository;

    @InjectMocks
    private Service service;

}
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能filename正确初始化?

g00*_*00b 5

由于您使用的是 Mockito,Spring 并没有真正参与引导您的测试,因此诸如@Value或 之类的事情application-test.yml毫无意义。

最好的解决方案是将filename属性添加Service到构造函数中(例如repository):

@Service
public class Service {
    private final String filename;
    private final Repository repository;

    // Now you don't need @RequiredArgConstructor
    public Service(@Value("${filename}") String filename, Repository repository) {
        this.filename = filename;
        this.repository.repository;
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许您通过在测试中调用构造函数来注入任何您想要的值:

@ExtendWith(MockitoExtension.class)
class ServiceTest {
    @Mock
    private Repository repository;

    private Service service;

    @BeforeEach
    void setUp() {
        // Now you don't need @InjectMocks
        this.service = new Service("my beautiful name", repository);
    }
}
Run Code Online (Sandbox Code Playgroud)