chrisleishman/jsmockito — Issue #8: mock doesn't mock but creates a spy instead
Author: EleotleCram
Created: 2011-11-15 14:22:36+00:00
State: open

Creating a mock with JsMockito doesn't create a mock, but creates a spy instead.

Consider:

with(JsMockito) {

var foo = {
bar: function() {
console.log("This is the real implementation of bar!");
}
}

console.log("foo.bar(): ");
foo.bar();

console.log("mockFoo.bar(): ");
var mockFoo = mock(foo);
mockFoo.bar();

console.log("spyFoo.bar(): ");
var spyFoo = spy(foo);
spyFoo.bar();
}
(jsbin source: http://jsbin.com/ayixov/4/edit)

The console output is (rather unexpectedly):

foo.bar():
This is the real implementation of bar!
mockFoo.bar():
This is the real implementation of bar!
spyFoo.bar():
This is the real implementation of bar!

(Please note that spy() and mock() both yield the same behaviour.)

Here is an equivalent program written in Java+Mockito:

package com.mycompany.app;

import static org.mockito.Mockito.*;

public class App {

static class Foo {
public void bar() {
System.out.println("This is the real implementation of bar!");
}
}

public static void main(String[] args) {
System.out.println("foo.bar(): ");
Foo foo = new Foo();
foo.bar();

System.out.println("mockFoo.bar(): ");
Foo mockFoo = mock(foo.getClass());
mockFoo.bar();

System.out.println("spyFoo.bar(): ");
Foo spyFoo = spy(foo);
spyFoo.bar();
}
}

(source code: http://www.megaupload.com/?d=DHWNHL5X)

Which yields the desired behaviour:

foo.bar():
This is the real implementation of bar!
mockFoo.bar():
spyFoo.bar():
This is the real implementation of bar!

(Please note the missing line "This is the real implementation of bar!" after `mockFoo.bar()' is invoked. This is to be expected, since mockFoo is expected to have mock implementations, i.e. stubs.)