简体   繁体   English

Scala模拟对象创建

[英]Scala Mock Object Creation

Is there a way to create an object of a given type that overrides a subset of methods and throws runtime exceptions for the rest of the methods? 有没有一种方法可以创建给定类型的对象,该对象将覆盖方法的子集并为其余方法抛出运行时异常?

It doesn't even need to have access to any implementation of the superclass. 它甚至不需要访问超类的任何实现。 It just needs to have the same type at compiletime and runtime. 它只需要在编译时和运行时具有相同的类型。

That pretty much is what a ScalaMock mock object does out of the box — methods you've set expectations on do whatever the expectations tell them to do, all others throw an ExpectationException. 这几乎就是ScalaMock模拟对象开箱即用的功能-您已将期望值设置为的方法可以执行期望值告诉他们执行的任何操作,所有其他方法都抛出ExpectationException。

What's your use-case? 您的用例是什么?

As Paul said, ScalaMock is a good way to go. 正如保罗所说,ScalaMock是一个不错的选择。

But I wanted to point out that you're just describing basic inheritance: 但我想指出的是,您只是在描述基本继承:

class OriginalClass {
  def methodToRun() = { println("called OriginalClass.methodToRun") }
  def methodNotToRun() = { println("called OriginalClass.methodNotToRun") }
}

class MockOriginalClass extends OriginalClass {
  override def methodToRun() = super.methodToRun()
  override def methodNotToRun() = throw new RuntimeException("you weren't supposed to run this!")
}

Then, in your code, where you were expecting an OriginalClass object you can pass in a MockOriginalClass and it will throw errors when you call the wrong things. 然后,在您的代码中,当您期望有一个OriginalClass对象时,您可以传递MockOriginalClass ,当您调用错误的东西时它将抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM