简体   繁体   中英

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.

What's your use-case?

As Paul said, ScalaMock is a good way to go.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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