不调用模拟函数,而是使用真实函数

Mocked function is not called, instead is used real function

我开始研究mocking。我希望该测试在调用时会失败(仅用于学习目的)。

MathUtils class:

public class MathUtils {

  public int addWithHelper(int a, int b) {
        MathUtilsHelper mathUtilsHelper = new MathUtilsHelper();
        return mathUtilsHelper.addNumbers(a,b);
    }
}

还有我的 MathUtilsHelper:

public class MathUtilsHelper {

     int addNumbers(int a, int b) {
         return a + b;
     }
}

Class MathUtilsTest

@Test
void itShouldAddNumberFromHelper() {

     MathUtilsHelper mathUtilsHelperMocked = Mockito.mock(MathUtilsHelper.class);
     when(mathUtilsHelperMocked.addNumbers(5,3)).thenReturn(999); // this doesn't works !!!!!!

     int add = mathUtils.add(5, 3);
     assertEquals(8, add); // should throw error

}

感谢您的帮助!

您的实用程序 class 每次都会创建一个新的助手实例,因此永远不会使用模拟。

老实说,我不确定你为什么需要 util class,但如果你想让它更容易测试,请更改它,以便在构造函数中传入帮助程序的实例而不是在 util class 中实例化它。换句话说,依赖注入。

这样你就可以创建 mock,并通过传入 mock 创建 util class 的实例。

MathUtils 中没有 mocked 对象,你对 MathUtils 做如下操作 class:

public class MathUtils {
  public MathUtilsHelper mathUtilsHelper;

  public MathUtils(MathUtilsHelper mathUtilsHelper ){
     this.mathUtilsHelper=mathUtilsHelper;
  }

  public int addWithHelper(int a, int b) {
     return mathUtilsHelper.addNumbers(a,b);
  }
}

在初始化测试时试试这个:

@Test
void itShouldAddNumberFromHelper() {

   MathUtilsHelper mathUtilsHelperMocked = Mockito.mock(MathUtilsHelper.class);
   when(mathUtilsHelperMocked.addNumbers(5,3)).thenReturn(999);
   mathUtils= new MathUtils(mathUtilsHelperMocked);

   int add = mathUtils.addWithHelper(5, 3);
   assertEquals(8, add);

}