Mock classes with traits
Is there any library that provides tools for mocking classes with traits (both can be statefull)?
Simplified example:
trait T {
var xx: List[Int] = List[Int]()
def t(x: Int) {
xx ::= x //开发者_运维问答throws NPE, xx == null, even after implicit initialization
}
}
class A extends T {
}
class Testable(a: A) {
def bar() {
a.t(2)
}
}
@Test def testFoo() {
val a: A = mock[A]
val testable = new Testable(a)
testable.bar()
verify(a).t(2)
}
Paul Butcher has been working on Borachio, a Scala mocking library. It supports mocking of traits, classes, functions and objects. See the following blogs for more information:
http://www.paulbutcher.com/2011/02/announcing-borachio-native-scala-mocking/ http://www.paulbutcher.com/2011/07/power-mocking-in-scala-with-borachio/
Well ... I don't have an answer, but I think I can offer a hint at where the problem is coming from. I took a look at A.class and found this (de.schauderhaft.testen is the package I used):
// Method descriptor #21 (I)V
// Stack: 2, Locals: 2
public bridge void t(int x);
0 aload_0 [this]
1 iload_1 [x]
2 invokestatic de.schauderhaft.testen.T$class.t(de.schauderhaft.testen.T, int) : void [26]
5 return
Line numbers:
[pc: 0, line: 13]
Local variable table:
[pc: 0, pc: 6] local: this index: 0 type: de.schauderhaft.testen.A
[pc: 0, pc: 6] local: x index: 1 type: int
I'm no byte code expert but this
2 invokestatic de.schauderhaft.testen.T$class.t(de.schauderhaft.testen.T, int) : void [26]
looks like the call to t(Int) is actually a called to a static method and you can't mock static methods. PowerMock would help, but probably ugly to use.
I just released ScalaMock 2.0. As well as functions and interfaces, ScalaMock can mock:
- Classes
- Singleton and companion objects (static methods)
- Object creation (constructor invocation)
- Classes with private constructors
- Final classes and classes with final methods
- Operators (methods with symbolic names)
- Overloaded methods
精彩评论