java - Mockito 和 JUnit5 依赖测试问题
问题描述
我有一个名为 Secret() 的类,它有一个名为 Word() 的关联类。此类 Secret() 处理它通过名为 getWord() 的方法从 Word() 类接收到的单词。问题是我想模拟该 getWord() 方法进行测试,但我不能。我应该得到一个真实的断言,但我得到了一个错误的断言
秘密课程:
public class Secret {
private String secret;
private Word word;
public Secret(){
this.word = new Word();
this.secret = word.getWord();
}
public String getSecret(){
return this.secret;
}
//more methods...
}
单词类:
public class Word {
private String word;
public Word(){
this.word = getFromFileRandom();
}
public String getFromFileRandom(){
Random random = new Random();
switch(random.nextInt(3)) {
case 0:
return "aabb";
case 1:
return "ccdd";
case 2:
return "eeff";
}
return "";
}
public String getWord(){
return this.word;
}
}
...和测试类
@ExtendWith(MockitoExtension.class)
public class Secretmethod Test {
@Mock
Word word;
@Test
public void test() throws IOException {
String stringMocked = "secreta";
when(this.word.getWord()).thenReturn(stringMocked);
Secret secret = new Secret();
assertThat(secret.getSecret(), is("secreta"));
}
}
感谢社区!
解决方案
Word
您类中的实例Secret
不是模拟的实例,您的类在Secret
每次实例化时都会创建一个新实例。
在你的类中创建一个新的构造函数Secret
:
public Secret(Word word){
this.word = word;
this.secret = word.getWord();
}
并在您的测试方法中传递您的模拟:
@Test
public void test() throws IOException {
String stringMocked = "secreta";
when(this.word.getWord()).thenReturn(stringMocked);
Secret secret = new Secret(this.word); // pass word mock here
assertThat(secret.getSecret(), is("secreta"));
}
推荐阅读
- python - STAN RuntimeError:初始化失败
- python - 代替 。在 json 文件中使用 _ 并使用 python 将其写入表
- c# - 如何在 C# 中解密 EncryptedXml?
- java - 想在eclipse上使用我自己的控制台,但是遇到一些unkown error for package not found
- angular - 为什么我在间隔内更改对象引用并且更改检测为onPush时UI不更新?
- select - 数据绑定点击事件不起作用
- gnuplot - gnuplot:事件直方图:timecolumn() 问题
- linux - 在 fzf 预览中使用 bat 突出显示行号
- laravel - 使用 Laravel 配置 Omnipay-stripe 以与 PCI SCA 一起使用
- python - 二维和一维 numpy 的笛卡尔积