如何在mockito中全局模拟方法调用? [英] How to globally mock method call in mockito?

查看:75
本文介绍了如何在mockito中全局模拟方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要全局模拟类方法.

I need to globally mock class method.

我的意思是,我无法创建模拟对象和存根方法.我的 api 不将此对象作为参数,因此我无法在函数调用中传递它,但是此类的对象是在这些函数中创建并在那里使用的.这就是为什么我需要在全球范围内模拟它.

I mean, i can't create mocked object and stub methods. My api doesn't take this object as an argument so i cant pass it inside function calls, but object of this class are created inside those functions and used there. That's why I need to mock it globally.

class A {
  public void methodA() {}  
}

我需要模拟 methodA().

I need to mock methodA().

我可以想象通过 mockito 实现几乎是不可能的.有谁知道如何实现这一目标?还是我应该重写我的代码?

I can imagine it might be nearly impossible to achive by mockito. Does anyone have idea how to achive this ? Or should i rewrite my code ?

推荐答案

你应该重写你的代码.

你写道:

这个类的对象在这些函数中创建并在那里使用

object of this class are created inside those functions and used there

如果您想要一个可测试的系统,这通常是一个坏主意.您提到的函数不应该自己创建对象,他们甚至不应该知道它们来自哪里或谁提供了该对象.

This is something which is generally a bad idea if you want to have a testable system. The functions you mention should not create the object themselves, ideed they should not even know where they come from or who is providing that object.

更好的方法是让这些函数与接口一起工作.然后,该接口的实现者将成为函数的参数或注入到该函数所属的对象中,例如通过一个控制器.

A better approach is by having those functions work with interfaces. Implementors for that interface will then be arguments to the function or be injected to the object to which that function belongs , for example via a contrcutor.

阅读关于控制反转依赖注入 处理这些问题.这些概念对于维护模块化和可测试的系统至关重要.许多应用程序开发框架提供了使用依赖注入开发应用程序的必要工具.

Read up about Inversion of control and Dependency Injection for those matters. These concepts are crucial to maintain a modular and thus testable system. Many frameworks for application development provide the necessary tools to develop applications using dependency injection.

这篇关于如何在mockito中全局模拟方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆