gpt4 book ai didi

java - 测试使用同一类中的另一个方法的方法

转载 作者:行者123 更新时间:2023-11-30 10:20:30 24 4
gpt4 key购买 nike

最近我开始对我的应用程序进行单元测试,发现自己在我的一门类(class)中遇到了设计方面的难题。

我有一个连接到数据库的存储库类,它看起来有点像这样。

public interface Repository {
...
void register(Account account)
Account find(String email)
...
}

在实现中这样做:

public class RepositoryImpl implements Repository {
...
public void register(Account account) {
if (find(account.getEmail() != null) return;
// Account with same email already exists.
...
}
}

这在实际环境中运行良好,但在单元测试时情况就不同了。

我使用 Mockito 来模拟我的依赖项,但我似乎无法模拟实现类中的 find 方法。

所以我的第一个想法是在 register 方法中注入(inject)一个 Repository ,我可以伪造它,但这似乎有点奇怪,因为我提供了一个带有类的方法它是它自己的成员。

之后我想直接将find逻辑复制到register方法中,但这违反了DRY原则。

那么..关于解决这个设计问题有什么想法吗?我想这是一个常见的问题,因为在系统中拥有唯一的电子邮件是很标准的。

谢谢!

最佳答案

如果你想模拟被测类的方法,你需要监视它而不是使用具体的实现:

// arrange
Account acc = new Account();
RepositoryImpl repoSpy = Mockito.spy(new RepositoryImpl());

doReturn(acc).when(repoSpy).find(Mockito.any(String.class));

//act
repoSpy.register(acc);

// assert ..

多亏了 register 实现将被使用并且 find 方法将被模拟到你喜欢的样子。

关于java - 测试使用同一类中的另一个方法的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48172663/

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