Reputation: 5157
I am trying to return a statically declared array of NWatchNativeNode[], but Moq seems to actually be calling the real method that goes to the gets the real system data. Is the Setup in the below incorrect?
I want to make sure that when
GetNodesInCriticalCondition()
is called, criticalNodes1
is returned.
Unit Test Code
var criticalNodes1 = new NWatchNativeNode[]
{
factory.CreateNativeNode(NWatchNodeType.NetworkSwitch,
"MySwitch",
"MyAlias",
12345
),
factory.CreateNativeNode(NWatchNodeType.NetworkSwitch,
"MySwitch2",
"MyAlias2",
54321
),
};
var mock = new Mock<NWatchCasModelStatusScheduleEntry>(_application);
mock.Setup(x => x.GetNodesInCriticalCondition()).Returns(criticalNodes1);
var nodes = mock.Object.GetNodesInCriticalCondition();
Assert.AreEqual(2, nodes.Length); // This should return true
Upvotes: 0
Views: 731
Reputation: 12846
The most likely reason that the Mock
returns the real system data is that your method GetNodesInCriticalCondition()
is not declared virtual
.
In order for Moq
to be able to setup the method calls, these methods have to be virtual
, otherwise it cannot overwrite them and hence cannot intercept them, which results in the original method being called.
Edit:
If your method is internal
, you have to give access to it to your Unit Test project and to Moq.
You can do this by adding
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
and
[assembly: InternalsVisibleTo("TestProjectNameSpace")]
to the AssemblyInfo.cs
file of the project you are creating mocks for.
Upvotes: 1
Reputation: 1800
As per your request, here is a quick example of how to test with Moq.
Let us make some classes and interfaces to test to start with.
public interface IFoo
{
IEnumerable<int> GetFoos();
}
public class Foo : IFoo
{
public IEnumerable<int> GetFoos()
{
return Enumerable.Range(1, 10);
}
}
public class Bar
{
private readonly IFoo foo;
public Bar(IFoo foo)
{
this.foo = foo;
}
public IEnumerable<int> SquareFoos()
{
foreach(var item in foo.GetFoos())
{
yield return item * item;
}
}
}
Now, Bar
has a dependency on the IFoo
interface. Now we want to test the functionality of SquareFoos
on the Bar
class. This is our subject under test. What we want to mock is the IFoo
interface passed to the constructor of Bar
. This gives us the following unit test setup.
// Arrange
var mock = new Mock<IFoo>();
mock.Setup(m => m.GetFoos()).Returns(Enumerable.Range(1, 2));
var sut = new Bar(mock.Object);
// Act
var results = sut.SquareFoos().ToList();
// Assert
Assert.AreEqual(2, results.Count);
In this case we mock out what GetFoos
returns to allow us to test our Bar
class.
Upvotes: 0