I have a class A
which contains an instance of class B
, and function foo
of A
calls function set
of B
, which updates the state of B
. Here is a code example (in Javascript):
A = function () {
this.init = function (b) {
this.b = b
}
this.foo = function (val) {
this.b.set(val)
}
this.bar = function () {
return this.b.get()
}
}
B = function () {
this.set = function (val) {
this.v = val
}
this.get = function () {
return this.v
}
}
How do I unit-test the foo
function, while keeping the test for A
non-dependent on the implementation of B
(using mocks and stubs and what not)?
I figured out the best way to do this, while making sure that A's test doesn't depend on its implementation, would be to create a mock B that has a working get
and set
, but writes to a temporary variable.
Code example to test A:
// Mock B
b = new function () {
this.set = function (val) {
this.v = val
}
this.get = function () {
return this.v
}
}
// Create an instance of A with Mock B
a = new A().init(b)
// Test A
// ...