我还有最后一节课,大概是这样的:

public final class RainOnTrees{

   public void startRain(){

        // some code here
   }
}

我在其他一些类中使用这个类,像这样:

public class Seasons{

   RainOnTrees rain = new RainOnTrees();

   public void findSeasonAndRain(){

        rain.startRain();

    }
}

在我的JUnit测试类Seasons.java中,我想模拟RainOnTrees类。我怎么能用Mockito做到这一点?


当前回答

为运行mockito成功添加这些依赖项:

testImplementation org.mockito: mockito-core: 2.24.5 testImplementation“org.mockito: mockito-inline: 2.24.5”

其他回答

对我们来说,这是因为我们从koin-test中排除了mockito-inline。一个gradle模块实际上需要这个,并且由于某些原因,它只在发布版本中失败了(IDE中的调试版本可以工作):-P

我也有同样的问题。由于我试图模拟的类是一个简单的类,所以我只是创建了它的一个实例并返回该实例。

试一试:

Mockito.mock(SomeMockableType.class,AdditionalAnswers.delegatesTo(someInstanceThatIsNotMockableOrSpyable));

这对我很管用。"SomeMockableType.class"是你想要模拟或监视的对象的父类,而someInstanceThatIsNotMockableOrSpyable是你想要模拟或监视的实际类。

详情请点击这里

没有尝试final,但私有,使用反射删除修饰符工作!已经进一步检查,它不为最终工作。

Mockito 2现在支持final类和方法!

但就目前而言,这只是一个“孵化”功能。它需要一些步骤来激活它,这些步骤在Mockito 2中的新内容中描述:

Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to enable mockability of these types. As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line: mock-maker-inline After you created this file, Mockito will automatically use this new engine and one can do : final class FinalClass { final String finalMethod() { return "something"; } } FinalClass concrete = new FinalClass(); FinalClass mock = mock(FinalClass.class); given(mock.finalMethod()).willReturn("not anymore"); assertThat(mock.finalMethod()).isNotEqualTo(concrete.finalMethod()); In subsequent milestones, the team will bring a programmatic way of using this feature. We will identify and provide support for all unmockable scenarios. Stay tuned and please let us know what you think of this feature!