待测类中的模拟类

Mock class in class under test(待测类中的模拟类)
本文介绍了待测类中的模拟类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如何在我正在测试的班级中使用 Mockito 模拟其他班级?

How I can mock with Mockito other classes in my class which is under test?

例如:

MyClass.java

MyClass.java

class MyClass {
    public boolean performAnything() {
        AnythingPerformerClass clazz = new AnythingPerformerClass();
        return clazz.doSomething();        
    }
}

AnythingPerformerClass.java

AnythingPerformerClass.java

class AnythingPerformerClass {
    public boolean doSomething() {
        //very very complex logic
        return result;
    }
}

并测试:

@Test
public void testPerformAnything() throws Exception {
    MyClass clazz = new MyClass();
    Assert.assertTrue(clazz.performAnything());
}

我可以欺骗 AnythingPerformerClass 以从 AnythingPerformerClass 中排除不必要的逻辑吗?我可以覆盖 doSomething() 方法以简单返回 truefalse 吗?

Can I spoof AnythingPerformerClass for excluding unnecessary logic from AnythingPerformerClass? Can I override doSomething() method for simple return true or false?

为什么我指定 Mockito,因为我需要它来使用 Robolectric 进行 Android 测试.

Why I specify Mockito, because I need it for Android testing with Robolectric.

推荐答案

你可以重构 MyClass 让它使用 依赖注入.您可以将类的实例传递给 MyClass 的构造函数,而不是让它创建一个 AnythingPerformerClass 实例,如下所示:

You could refactor MyClass so that it uses dependency injection. Instead of having it create an AnythingPerformerClass instance you could pass in an instance of the class to the constructor of MyClass like so :

class MyClass {

   private final AnythingPerformerClass clazz;

   MyClass(AnythingPerformerClass clazz) {
      this.clazz = clazz;
   }

   public boolean performAnything() {         
     return clazz.doSomething();        
   }
}

然后你可以在单元测试中传入模拟实现

You can then pass in the mock implementation in the unit test

@Test
public void testPerformAnything() throws Exception {
   AnythingPerformerClass mockedPerformer = Mockito.mock(AnythingPerformerClass.class);
   MyClass clazz = new MyClass(mockedPerformer);
   ...
}

或者,如果您的 AnythingPerformerClass 包含状态,那么您可以将 AnythingPerformerClassBuilder 传递给构造函数.

Alternatively, if your AnythingPerformerClass contains state then you could pass a AnythingPerformerClassBuilder to the constructor.

这篇关于待测类中的模拟类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)