首页 > 解决方案 > 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"));
}
}

感谢社区!

标签: javaunit-testingmockitojunit5

解决方案


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

推荐阅读