gpt4 book ai didi

java - 在服务测试中使用真实的组件

转载 作者:行者123 更新时间:2023-12-01 17:45:54 25 4
gpt4 key购买 nike

我正在测试具有 Autowiring 帮助程序组件的服务。该组件具有 Autowiring 的存储库。

在我的测试中,我想使用该组件助手,而不是模拟。我想为此模拟存储库。

但我无法让它发挥作用。

我测试的服务:

@Service
public class ServiceImpl{
@Autowired
private Helper helper;
}

具有 Autowiring 存储库的 Helper 类

@Component
public class Helper {
@Autowired
private Repository repo;
}

我的测试应该是这样的

@ExtendWith(MockitoExtension.class)
public class ServiceImplTest {

ServiceImpl service;

@Mock
private Repository repoMock;

@InjectMocks
private Helper helper;

}

我希望更好地重构整个事情,但不幸的是,这是不可能的......

欢迎任何帮助。

最佳答案

我更喜欢构造函数注入(inject)而不是字段注入(inject)。 (了解更多here)

在这种情况下,您的类将如下所示:

    @Component
public class Helper {
@Autowired
public Helper(Repository repo) {
this.repo = repo;
}
}

@Service
public class ServiceImpl{
@Autowired
public ServiceImpl(Helper helper) {
this.helper = helper;
}
}

这样您就可以轻松地使用模拟 Repository 对象创建真正的 Helper 对象:

    ServiceImpl service;

private Helper helper;

@Mock
private Repository repoMock;

@BeforeEach
void init() {
helper = new Helper(repoMock);
service = new ServiceImpl(helper);
}

关于java - 在服务测试中使用真实的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55379534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com