如何使用 MockitoSugar 模拟对象(单例)方法? [英] How can I use MockitoSugar to mock an object (singleton) method?

查看:63
本文介绍了如何使用 MockitoSugar 模拟对象(单例)方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala 有没有办法使用 MockitoSugar 来模拟 object 的方法,它是一个 scala 单例?

Is there a way in scala to use MockitoSugar in order to mock a method of an object that is a scala singleton?

推荐答案

处理单例以进行模拟的最佳方法是首先对单例本身的结构进行一些修改.使用 trait 来定义操作,然后让对象像这样扩展 trait:

Your best bet to deal with singletons for mocking is to first do a little rework on the structure of the singleton itself. Use a trait to define the operations and then have the object extend the trait like so:

trait Fooable{
  def doFoo:String = "foo"
}

object Foo extends Fooable

然后,在任何需要 Foo 对象的类中,将其声明为输入或可以设置的内容(DI),但将其声明为特征,而不是像这样:

Then, in any class that needs the Foo object, declare it as an input or something that can be set (DI), but decalare it as the trait instead like this:

class MyFooUser(foo:Fooable = Foo){

}

默认情况下它使用对象,但是在为您的测试构建时,您可以给它一个模拟的 Fooable 代替.有很多方法可以处理将 Fooable 放入您的类中(这是一个),而这实际上不在此答案的范围内.答案实际上是首先使用特征来定义方法,然后让对象扩展该特征,然后在任何需要它的类中将其称为特征.这将使您能够有效地模拟它.

That way by default it uses the object, but when constructing for your tests, you can give it a mocked Fooable instead. There are a bunch of ways to handle getting the Fooable into your classes (this is one) and that's not really in scope for this answer. The answer really is about using a trait first to define the methods and then having the object extend that trait and then referring to it as the trait in any class that needs it. That will allow you to mock it effectively.

这篇关于如何使用 MockitoSugar 模拟对象(单例)方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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