Reputation: 4651
How do can I mock a member variables of a class?
It seems this FooA()
is never called.
Note: I am beginner in moq (and rusty in C#) so please bear with me ;-)
Unhandled Exception: Moq.MockVerificationException: The following setups were not matched: IA a => a.FooA()
Here is the source code:
using Moq;
namespace TestMock
{
interface IA {
void FooA();
}
class A : IA {
public void FooA() { }
}
class B {
public void FooB() {
a.FooA();
}
IA a = new A();
}
class Program
{
static void Main(string[] args)
{
// Arrange
var mockA = new Mock<IA>();
mockA.Setup(a => a.FooA());
var mockB = new Mock<B>();
// Act
B b = new B();
b.FooB();
// Assert
mockA.VerifyAll();
}
}
}
Upvotes: 2
Views: 2635
Reputation: 247561
B
in its original form is tightly coupled to dependency IA
which makes it difficult to mock when testing.
Refactor B
to depend on IA
via constructor injection. (Explicit Dependencies Principle)
class B {
IA a;
public B(IA a) {
this.a = a;
}
public void FooB() {
a.FooA();
}
}
Now inject the mocked dependency in the test and verify behavior
[TestMethod]
public void TestMoq() {
// Arrange
var mockA = new Mock<IA>();
mockA.Setup(a => a.FooA());
// Act
B b = new B(mockA.Object);
b.FooB();
// Assert
mockA.VerifyAll();
}
Upvotes: 2