How to fake an action<> with FakeItEasy - c#

I'm working with the FakeItEasy library to create fakes for my unit tests.
I have a ClassUnderTest on which I want to test the method MethodToTest(Data dataObject). This method is calling a method of an interface which I want to fake:
public interface IFoo
{
void Execute(Action<IDataAccess> action);
}
public class ClassUnderTest
{
private IFoo _foo;
public ClassUnderTest(IFoo foo)
{
_foo = foo;
}
public void MethodToTest(Data dataObject)
{
_foo.Execute(dataAccess => dataAccess.Update(dataObject));
}
}
public interface IDataAccess
{
void Update(Data data);
}
public class Data
{
public int Property { get; set; }
}
In my unit tests I want to check if the test method calls the interface correctly (with the correct property value):
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var foo = A.Fake<IFoo>(x => x.Strict());
A.CallTo(() => foo.Execute(dataAccess => dataAccess.Update(A<Data>.That.Matches(d => d.Property == 20))));
var cut = new ClassUnderTest(foo);
cut.MethodToTest(new Data { Property = 20 });
}
}
But something is configured wrong in this test. I get the exception:
Test method TestProject1.UnitTest1.TestMethod1 threw exception:
FakeItEasy.ExpectationException: Call to non configured method "Execute" of strict fake.
Does somebody have an idea of how I have to configure the CallTo() statement correctly?

The updated example really helps, #rhe1980.
First some notes about the test you supplied:
the A.CallTo method doesn't do anything - it's not setting up behaviour (with a .Invokes or a .Returns or even a .DoesNothing) or verifying that the method has been called (for example with .MustHaveHappened).
Comparing Actions appears to be tough. I did find some advice over at Compare Delegates Action<T>, but if it were me, I'd take a slightly different tack.
Instead of attempting to compare the Action delegate to a reference model, I figured I could emulate this by capturing the action supplied to Execute and then running it on an IDataAccess and see what the action does. Fortunately, we have FakeItEasy to help with that!
I had success with this test:
[TestMethod]
public void TestMethod1()
{
// Arrange
var foo = A.Fake<IFoo>(x => x.Strict());
var fakeDataAccess = A.Fake<IDataAccess>();
A.CallTo(() => foo.Execute(A<Action<IDataAccess>>.Ignored))
.Invokes((Action<IDataAccess> action)=>action(fakeDataAccess));
var cut = new ClassUnderTest(foo);
// Act
cut.MethodToTest(new Data { Property = 20 });
// Assert
A.CallTo(() => fakeDataAccess.Update(A<Data>.That.Matches(d => d.Property == 20)))
.MustHaveHappened();
}
I hope it helps.

If I understood your intentions correctly, you need to use something as follows:
A.CallTo(() => foo.Execute(A<Action<IDataAccess>>.Ignored).MustHaveHappened();

Related

Can't form a Moq test to spoof context access

Completely new to Moq and mock testing in general. I'm trying to follow a tutorial but fit it to my needs, which is spoofing some database access through entityFrameworkCore contexts. How do I setup and test the response for my database returning either a 0 or an arbitrary number?
To clarify, I want to test that providing "Whatever" to my DoSomething method will return a 0 and also that providing any other string will produce an entry Id. Of course the Id is dependent on database increments in real life, so I need to just set an arbitrary number as a response and test that this is returned. This is a very minified example of my real method, of course.
I've minimised the setup as much as possible:
Interface:
public interface ITestClass
{
int DoSomething(string thing);
}
Implementation:
public class TestClass : ITestClass
{
private readonly TestContext _testContext;
public TestClass(TestContext testContext)
{
_testContext = testContext;
}
public int DoSomething(string thing)
{
if (thing == "Whatever") return 0;
Item i = new Item()
{
Thing = thing
};
_testContext.Add(i);
_testContext.SaveChanges();
return i.Id;
}
}
Context:
public class TestContext : DbContext
{
public TestContext(DbContextOptions<TestContext> options) : base(options) { }
}
Table / model class:
public class Item
{
public int Id { get; set; }
public string Thing { get; set; }
}
I've ignored connection strings because the whole point is to test the method without connecting to a database, right? And finally here's my attempt at mocking which I'm completely clueless about, tbh:
public void Test1()
{
var mock = new Mock<ITestClass>();
mock.Setup(m => m.DoSomething("Whatever"));
// Assert returns 0
mock.Setup(m => m.DoSomething("ValidString"));
// Assert returns arbitrary 12345 - where do I spoof this number?
}
I think you have a fundamental misunderstanding of how mocking is used. Lets look at your test
public void Test1()
{
var mock = new Mock<ITestClass>();
mock.Setup(m => m.DoSomething("Whatever"));
// Assert returns 0
mock.Setup(m => m.DoSomething("ValidString"));
// Assert returns arbitrary 12345 - where do I spoof this number?
}
Now when you use Setup on a mock, you are also to use Returns, ReturnsAsync, or Throws to tell the mock what you want it to return when you provide these values. So your setup for DoSomething should look like this
mock.Setup(m => m.DoSomething(It.Is<string>(i => i == "ValidString"))).Returns(12345);
But there should be an obvious problem here. If we are explicitly telling it exactly what to give us for a given input, then what are we really testing? Just the mock itself at that point. This isn't how mocks are intended to be used. So a rule, never mock the thing you are testing. Instead you mock its dependencies. In this case, the only one is the TestContext. Instead, we actually want to test the DoSomething method, so we create a real instance of that class to test.
You didn't specify which testing framework you are using, so I wrote mine with NUnit
[Test]
public void Test1()
{
// Mock the dependency
Mock<ITestContext> mockContext = new Mock<ITestContext>();
mockContext.Setup(m => m.Add(It.IsAny<Item>()))
.Returns(true);
mockContext.Setup(m => m.SaveChanges())
.Returns(true);
// Inject the dependency
TestClass testClass = new TestClass(mockContext.Object);
int result = testClass.DoSomething("Whatever");
// Verify the methods on the mock were called once
mockContext.Verify(m => m.Add(It.IsAny<Item>()), Times.Once);
mockContext.Verify(m => m.SaveChanges(), Times.Once);
// Assert that the result of the operation is the expected result defined elsewhere
Assert.That(result, Is.EqualTo(ExpectedResult));
}
Testing that a mock returns what you set it up to return offers no value. We want to test the real deal, mocking just makes that possible when the dependencies are complex. They are a stand-in the for backend systems and complex object graphs that the real system uses in practice and nothing more. The magic is that it allows us to only set up the parts of the mock that we need, the specific function calls and property access that the class which is dependent on it relies, without having to worry about setting up the entire class and all of its dependencies and so on.

How do i write a failing test to add another branch in an if statement without external state

With this code:
Public class Processor {
Public Processor(Ifoo colloborator, Ibar otherCollobotator)
Public void Process() {
// if (newFoo)
// new action
If (foo)
this.colloborator.doSomething();
If (bar)
this.colloborator.doSomethingElse();
Else this.otherColloborator.doSomethingCompletelyDiffetent();
}
I want to add a another branch at the top to do something else (commented out). I know one way to do it, it involves verifying, or not, calls on colloborators using an appropriate mock/spy.
And to be clear I have done this already, succesfully and with TDD 'without' introducing another colloborator.
How would you tackle this? From a test first perspective?
I think eventually it could be refactored with something called pluggable object/adapter.
Assuming your new action also calls the collaborator, you can mock it out.
Example with RhinoMocks:
[TestMethod]
public void Test()
{
//Arrange
ICollaborator mock = MockRepository.GenerateMock<ICollaborator>();
Processor myProc = new Processor(mock, ...);
//Act
myProc.Process();
//Assert
mock.AssertWasCalled(x => x.MethodToBeCalled);
}
This will of course fail if you do not change your Process method.
Just like you said, you'd need to check that when condition is true, new action is called, and when condition is false, then new action is not called. So, first we'd define our new interface:
public interface INewAction
{
void NewAction();
}
Then, we modify our processor (note that we DID NOT yet add the new if branch):
public class Processor {
private readonly INewAction _newAction;
public Processor(Ifoo colloborator, Ibar otherCollobotator, INewAction newAction)
{
// whatever we had before
_newAction = newAction;
}
public void Process() {
if (foo)
this.colloborator.doSomething();
of (bar)
this.colloborator.doSomethingElse();
else this.otherColloborator.doSomethingCompletelyDiffetent();
}
Now we write our test cases:
[TestClass]
public class ProcessorTests
{
[TestMethod]
public void Process_GivenNewFoo_CallsNewAction()
{
// arrange 'newfoo' condition
// mockout our processor, e.g.
var mockNewAction = new Mock<INewAction>(); // this is Moq, for others use appropriate syntax, e.g. Substitute.For<INewAction>() for NSubstitute etc.
mockNewAction.Setup(x => x.NewAction()).Verifiable();
var target = new Processor(null, null, mockNewAction.Object);
target.Process();
mockNewAction.Verify(x => x.NewAction(), Times.Once);
}
[TestMethod]
public void Process_GivenNewFoo_False_DoesNotCallNewAction()
{
// arrange 'newfoo' condition to be false
// mockout our processor, e.g.
var mockNewAction = new Mock<INewAction>(); // this is Moq, for others use appropriate syntax, e.g. Substitute.For<INewAction>() for NSubstitute etc.
mockNewAction.Setup(x => x.NewAction()).Verifiable();
var target = new Processor(null, null, mockNewAction.Object);
target.Process();
mockNewAction.Verify(x => x.NewAction(), Times.Never);
}
}
When we run them, the second test will pass -> well, this is expected, because essentially the behaviour is if NOT newfoo then don't call it. But the first test WILL fails (as is the TDD approach).
And now we modify the Processor again, just the Process() method:
public void Process() {
if(newFoo)
{
_newAction.NewAction();
}
if (foo)
this.colloborator.doSomething();
of (bar)
this.colloborator.doSomethingElse();
else this.otherColloborator.doSomethingCompletelyDiffetent();
}
At this point both the tests pass and we completed the TDD cycle.

Verifying generic method called using Moq

I'm having trouble verifying that mock of IInterface.SomeMethod<T>(T arg) was called using Moq.Mock.Verify.
I'm can verify that method was called on a "Standard" interface either using It.IsAny<IGenericInterface>() or It.IsAny<ConcreteImplementationOfIGenericInterface>(), and I have no troubles verifying a generic method call using It.IsAny<ConcreteImplementationOfIGenericInterface>(), but I can't verify a generic method was called using It.IsAny<IGenericInterface>() - it always says that the method was not called and the unit test fails.
Here is my unit test:
public void TestMethod1()
{
var mockInterface = new Mock<IServiceInterface>();
var classUnderTest = new ClassUnderTest(mockInterface.Object);
classUnderTest.Run();
// next three lines are fine and pass the unit tests
mockInterface.Verify(serviceInterface => serviceInterface.NotGenericMethod(It.IsAny<ConcreteSpecificCommand>()), Times.Once());
mockInterface.Verify(serviceInterface => serviceInterface.NotGenericMethod(It.IsAny<ISpecificCommand>()), Times.Once());
mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.IsAny<ConcreteSpecificCommand>()), Times.Once());
// this line breaks: "Expected invocation on the mock once, but was 0 times"
mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.IsAny<ISpecificCommand>()), Times.Once());
}
Here is my class under test:
public class ClassUnderTest
{
private IServiceInterface _service;
public ClassUnderTest(IServiceInterface service)
{
_service = service;
}
public void Run()
{
var command = new ConcreteSpecificCommand();
_service.GenericMethod(command);
_service.NotGenericMethod(command);
}
}
Here is my IServiceInterface:
public interface IServiceInterface
{
void NotGenericMethod(ISpecificCommand command);
void GenericMethod<T>(T command);
}
And here is my interface/class inheritance hierarchy:
public interface ISpecificCommand
{
}
public class ConcreteSpecificCommand : ISpecificCommand
{
}
It is a known issue in the Moq 4.0.10827 which is a current release version. See this discussion at GitHub https://github.com/Moq/moq4/pull/25. I have downloaded its dev branch, compiled and referenced it and now your test passes.
I'm going to wing it. Since GenericMethod<T> requires that a T argument be provided, would it be possible to do:
mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.Is<object>(x=> typeof(ISpecificCommand).IsAssignableFrom(x.GetType()))), Times.Once());

Verify a method call using Moq

I am fairly new to unit testing in C# and learning to use Moq. Below is the class that I am trying to test.
class MyClass
{
SomeClass someClass;
public MyClass(SomeClass someClass)
{
this.someClass = someClass;
}
public void MyMethod(string method)
{
method = "test"
someClass.DoSomething(method);
}
}
class Someclass
{
public DoSomething(string method)
{
// do something...
}
}
Below is my TestClass:
class MyClassTest
{
[TestMethod()]
public void MyMethodTest()
{
string action="test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.SetUp(a => a.DoSomething(action));
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
mockSomeClass.Verify(v => v.DoSomething(It.IsAny<string>()));
}
}
I get the following exception:
Expected invocation on the mock at least once, but was never performed
No setups configured.
No invocations performed..
I just want to verify if the method "MyMethod" is being called or not. Am I missing something?
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Verify method has been called with IEnumerable containing 'x' elements with Moq

I have a repository with an Add method that takes an IEnumerable as parameter:
public void Add<T>(T item) where T : class, new(){}
In a unittest I want to verify that this method is called with an IEnumerable that contains exactly the same amount of elements as another IEnumerable
[Test]
public void InvoicesAreGeneratedForAllStudents()
{
var students = StudentStub.GetStudents();
session.Setup(x => x.All<Student>()).Returns(students.AsQueryable());
service.GenerateInvoices(Payments.Jaar, DateTime.Now);
session.Verify(x => x.Add(It.Is<IEnumerable<Invoice>>(
invoices => invoices.Count() == students.Count())));
}
Result of the unit test:
Moq.MockException :
Expected invocation on the mock at least once, but was never performed:
x => x.Add<Invoice>(It.Is<IEnumerable`1>(i => i.Count<Invoice>() == 10))
No setups configured.
What am I doing wrong?
From your code example you haven't set up the x => x.Add on the Moq
session.Setup(x => x.Add(It.IsAny<IEnumerable>());
Unless the Setup for x.All is meant to be x.Add? If so, you need to match the Verify and Setup exactly - a good way to do that is to extract it to a common method that returns an Expression.
EDIT: Added a sample, I have changed the signature of Add as I can't see how you could pass a collection otherwise.
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Mock<Boo> moqBoo = new Mock<Boo>();
moqBoo.Setup(IEnumerableHasExpectedNumberOfElements(10));
// ACT
moqBoo.Verify(IEnumerableHasExpectedNumberOfElements(10));
}
private static Expression<Action<Boo>> IEnumerableHasExpectedNumberOfElements(int expectedNumberOfElements)
{
return b => b.Add(It.Is<IEnumerable<Invoice>>(ie => ie.Count() == expectedNumberOfElements));
}
}
public class Boo
{
public void Add<T>(IEnumerable<T> item) where T : class, new()
{
}
}
public class Invoice
{
}
Also, a good way to debug these things is to set your Mock up with MockBehavior.Strict and then you'll be informed by the invoked code what you need to configure.

Categories