junit 测试中如何利用资源解决@Value问题

mwyxok5s  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(137)

我有以下服务:

@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

n3schb8v

n3schb8v1#

由于您使用的是Mockito,Spring并不真正参与测试的引导,因此像@Valueapplication-test.yml这样的东西没有任何意义。
最好的解决方案是将Service中的filename属性添加到构造函数中(如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;
    }
}

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

@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);
    }
}

相关问题