Mock Method call from another Method using Moq - c#

I am trying to create Unit test for below two methods using MsTest. I am fairly new to this, and so far have referred to different posts on the Topic.
Code Requirement
Create a Timer Based Function (Azure)
Execute Method 1 and Method 2 in the order to get the Output.
Test Requirement
Ability to be able to create Unit test cases for each Class/Method with no external dependency (Fake/Mock)
To Fit this Code under Test can be update as code is not yet Live.
Open to other tools/Nugets beyond Moq to support the Test requirement.
When I try to run the Unit test, it does not mock Method 2 instead executes it. I need help in debugging the code.
public class Job: IJob
{
//Method 1
public List<TableEntity> GetJob()
{
var a = Get<T>("static value"); //Mock this to Test Method GetJob
return a.Result;
}
//Method 2
public async Task<List<T>> Get<T>(string tableName) where T : ITableEntity, new()
{
var t = new List<T>();
//add data to T
return t;
}
}
Interface
public interface IJob
{
List<TableEntity> GetJob();
Task<List<T>> Get<T>(string tableName) where T : ITableEntity, new();
}
Test Code
private readonly Mock<IJob> _mockIJob = new Mock<IJob>();
readonly Job _job = new Job();
public void NotThrow_Error_When_JobFound()
{
//Arrange
var jobs = new J.TableEntity()
{
FolderName = "FolderName",
Timestamp = DateTimeOffset.Now
};
var jobList = Task.FromResult(new List<TableEntity>() { jobs });
_mockIJob.Setup(c => c.Get<TableEntity>(""))
.Returns(jobList);
//Act
var actualResult = _job.GetJob();
//Assert
Assert.AreEqual(jobList, actualResult);
}

I think when simplifying the code some things got lost in translation (e.g, var a = Get<T>("static value"); no idea what T refers here) but with small modifications I think you would be able to achieve what you are trying.
In order for the mock to be used you need the mocked object instance so you will need to remove reference to concrete instance:
private readonly Mock<IJob> _mockIJob = new Mock<IJob>();
// readonly Job _job = new Job(); // This should not be used.
In order to use a concrete method1 with the mocked method2, you will need to mock the Job concrete class.
private readonly Mock<Job> _mockJob = new Mock<Job>();
In order for the proxy class to "take over" a method it should be declared as virtual:
//Method 2
public virtual List<T> Get<T>(string tableName) where T : TableEntity, new()
{
var t = new List<T>();
//add data to T
return t;
}
While mocking the method you should use the It.IsAny<string>() specification otherwise your test method is using a mock with "" parameter whereas the method1 is using "static value" parameter, so it will not match the proxy method.
so putting this all together:
private readonly Mock<Job> _mockJob = new Mock<Job>();
[Fact]
public void NotThrow_Error_When_JobFound()
{
//Arrange
var jobs = new TableEntity()
{
FolderName = "FolderName",
Timestamp = DateTimeOffset.Now
};
var jobList = new List<TableEntity>() { jobs };
_mockJob.Setup(c =>
c.Get<TableEntity>(It.IsAny<string>()))
.Returns(() =>
{
// easier to visualize the breakpoint.
return jobList;
});
//Act
var actualResult = _mockJob.Object.GetJob();
//Assert
Assert.Equal(jobList, actualResult);
}
Hope it helps.

It will not be possible the way you approach it. What you are attempting is to execute a test on an instance of a concrete class and, at the same time, to mock the instance.
I am not going to deliberate on whether GetJob method should exist in the current class or be moved elsewhere. For the solution in the current form the simplest way to achieve testability (and perhaps reduce duplication in the future) would be by declaring GetJob as extension method on IJob interface:
public static class IJobExtensions
{
public static List<TableEntity> GetJob(this IJob job)
{
var a = job.Get<T>("static value"); //Mock this to Test Method GetJob
return a.Result;
}
}
The unit test would then look like this:
private readonly Mock<IJob> _mockIJob = new Mock<IJob>();
public void NotThrow_Error_When_JobFound()
{
//Arrange
var jobs = new J.TableEntity()
{
FolderName = "FolderName",
Timestamp = DateTimeOffset.Now
};
var jobList = Task.FromResult(new List<TableEntity>() { jobs });
_mockIJob.Setup(c => c.Get<TableEntity>(""))
.Returns(jobList);
//Act
var actualResult = _mockIJob.Object.GetJob();
//Assert
Assert.AreEqual(jobList, actualResult);
}

If I understand your problem correctly then you are looking for partial mocking. You want to use GetJob as it is but you want to mock Get<T>.
Prerequisite
The Get<T> should be marked as virtual to be able to mock it.
Test
//Arrange
...
var jobPartialMock = new Mock<Job>();
jobPartialMock.CallBase = true; //Use GetJob as it is
jobPartialMock
.Setup(job => job.Get<TableEntity>(It.IsAny<string>()))
.ReturnsAsync(new List<TableEntity>() { jobs }); // Mock `Get<T>`
//Act
var actual = jobPartialMock.Object.GetJob();
//Assert
...

Related

Mocking a Fluent interface using Moq

I have looked at a number of questions here on this subject but none seem to address the issue I'm having.
I've got code that looks a bit like this...
IBaseDataCollector<MyClass> myDataCollector;
myDataCollector = new Mock<IBaseDataCollector<MyClass>>();
systemUnderTest = new Thing(myDataCollector.Object);
And in my Thing class...
var collection = myDataCollector.SomeMethod()
.SomeSecondMethod()
.GetData();
where both SomeMethod() and SomeSecondMethod() return this (ie the instance of myDataCollector)
When I run my test I get a NullReferenceException on the like where I call myDataCollector.
I tried adding this in my test setup...
myDataCollector.Setup(_=> _.SomeMethod()),Returns(myDataCollector.Object);
but that wouldn't even compile, complaining that it "Could not resolve method 'Returns(IBaseDataCollector)'"
Now, if I refactor my Thing class to read...
myDataCollector.SomeMethod();
myDataCollector.SomeSecondMethod()
var collection = myDataCollector.GetData();
my test executes properly.
If this was it, I'd just refactor my code and get on with life, but, in reality, I need to call my code inside a SelectMany call...
var collection = list.SelectMany(_=> myDataCollector.SomeMethod()
.SomeSecondMethod(_)
.GetData());
Again, I know I could replace the SelectMany with, say, a ForEach and manually populate the collection with the results of each iteration of the call to GetData() so that I can get rid of the fluent element of the calls, but this means refactoring the code just to make the tests work, which feels wrong.
How should I be calling Setup() on my Mocked objects to make my fluent calls work?
Take a look at the following test code (I've invented some details to fill in the blanks). The mocked object instance should be available as a value to return from its own methods as shown.
public class UnitTestExample
{
[Fact]
public void UnitTestExample1()
{
var myClassInterfaceMock = new Mock<IInterface<MyClass>>();
var instance = myClassInterfaceMock.Object;
var myList = new List<MyClass>()
{
new MyClass() { Attribute = 1 }
};
myClassInterfaceMock.Setup(_ => _.SomeMethod()).Returns(instance);
myClassInterfaceMock.Setup(_ => _.SomeSecondMethod()).Returns(instance);
myClassInterfaceMock.Setup(_ => _.GetData()).Returns(myList);
var myDependentClass = new MyDependentClass(instance);
var result = myDependentClass.DoTheThing();
Assert.True(result.Count.Equals(1));
}
}
public interface IInterface<T>
{
IInterface<T> SomeMethod();
IInterface<T> SomeSecondMethod();
List<T> GetData();
}
public class MyClass
{
public int Attribute { get; set; }
}
public class MyDependentClass
{
private readonly IInterface<MyClass> _test;
public MyDependentClass(IInterface<MyClass> test)
{
_test = test;
}
public List<MyClass> DoTheThing()
{
return _test.SomeMethod().SomeSecondMethod().GetData();
}
}

Fake extension method using exact arguments

I am writing tests for our C# 7 application and struggle with mocking an Extension method. I am using TypeMock 8.6.10.3.
Here is a simplified example:
internal class InnerClass
{
private readonly string _description;
public InnerClass(string description)
{
_description = description;
}
public string GetDescription()
{
return _description;
}
}
internal class OuterClass
{
public void DoSthWithExtension(int someNumber)
{
var innerClass = new InnerClass("InnerClassDescription");
innerClass.Extension(someNumber);
}
}
internal static class Extensions
{
public static void Extension(this InnerClass innerClass, int someNumber)
{
var d = innerClass.GetDescription();
}
}
public void TestExtension()
{
// I want to fake the method "InnerClass.Extension()"
// which is called by "OuterClass.DoSthWithExtension()".
// I don't have access to the InnerClass instance though.
// So unfortunately I have to fake them all.
var fakedInnerClasses = Isolate.Fake.AllInstances<InnerClass>();
Isolate.WhenCalled(() => Extensions.Extension(fakedInnerClasses, 11)).WithExactArguments().DoInstead(
c =>
{
// The test doesn't go in here. The second parameter is correct,
// the first one obviously not. But what is expected as a first parameter then?
var oc2 = new OuterClass();
// Here I call InnerClass.Extension() again.
// The test should now go into the faked method underneath.
oc2.DoSthWithExtension(22);
});
Isolate.WhenCalled(() => Extensions.Extension(fakedInnerClasses, 22)).WithExactArguments().DoInstead(
c =>
{
// As above, the test code doesn't go in here.
});
// In here an instance of InnerClass is created and
// InnerClass.Extension(11) is called.
var oc1 = new OuterClass();
oc1.DoSthWithExtension(11);
}
As the this parameter of the Extension method I choose the faked instances of InnerClass. Thats what I assume is needed. But TypeMock does not bring me into the faked method. Obviously its the wrong parameter. But which one should I choose then?
Based on comments and updated question, the part that is confusing is why the other outer class is needed. The shown inner class has no dependency on the outer. Why would the mock then need to create a new outer class?
That aside, based on the docs its appears that you need to setup the extension class so that you can fake the static extension calls.
Isolate.Fake.StaticMethods(typeof(Extensions));
//...
Original answer
Do not fake the extension method in this case. You know what the extension method calls. so fake that.
public void TestExtension() {
//Arrange
string expected = "Fake result";
var fakedInnerClasses = Isolate.Fake.AllInstances<InnerClass>();
Isolate.WhenCalled(() => fakedInnerClasses.GetDescription())
.WillReturn(expected);
var subject = new OuterClass();
//Act
subject.DoSthWithExtension();
//Assert
//...
}
So now when the outer is called and the extension method invoked, it will be acting on the mock controlled by you.

Unit test a void method with Mock?

I want to test a void method with Mock.
public class ConsoleTargetBuilder : ITargetBuilder
{
private const string CONSOLE_WITH_STACK_TRACE = "consoleWithStackTrace";
private const string CONSOLE_WITHOUT_STACK_TRACE = "consoleWithoutStackTrace";
private LoggerModel _loggerModel;
private LoggingConfiguration _nLogLoggingConfiguration;
public ConsoleTargetBuilder(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration)
{
_loggerModel = loggerModel;
_nLogLoggingConfiguration = nLogLoggingConfiguration;
}
public void AddNLogConfigurationTypeTagret()
{
var consoleTargetWithStackTrace = new ConsoleTarget();
consoleTargetWithStackTrace.Name = CONSOLE_WITH_STACK_TRACE;
consoleTargetWithStackTrace.Layout = _loggerModel.layout + "|${stacktrace}";
_nLogLoggingConfiguration.AddTarget(CONSOLE_WITH_STACK_TRACE, consoleTargetWithStackTrace);
var consoleTargetWithoutStackTrace = new ConsoleTarget();
consoleTargetWithoutStackTrace.Name = CONSOLE_WITHOUT_STACK_TRACE;
consoleTargetWithoutStackTrace.Layout = _loggerModel.layout;
_nLogLoggingConfiguration.AddTarget(CONSOLE_WITHOUT_STACK_TRACE, consoleTargetWithoutStackTrace);
}
The thing is I am not sure how to test it. I have my primary code.
public class ConsoleTargetBuilderUnitTests
{
public static IEnumerable<object[]> ConsoleTargetBuilderTestData
{
get
{
return new[]
{
new object[]
{
new LoggerModel(),
new LoggingConfiguration(),
2
}
};
}
}
[Theory]
[MemberData("ConsoleTargetBuilderTestData")]
public void ConsoleTargetBuilder_Should_Add_A_Console_Target(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration, int expectedConsoleTargetCount)
{
// ARRANGE
var targetBuilderMock = new Mock<ITargetBuilder>();
targetBuilderMock.Setup(x => x.AddNLogConfigurationTypeTagret()).Verifiable();
// ACT
var consoleTargetBuilder = new ConsoleTargetBuilder(loggerModel, nLogLoggingConfiguration);
// ASSERT
Assert.Equal(expectedConsoleTargetCount, nLogLoggingConfiguration.AllTargets.Count);
}
Please guide me to the right direction.
It looks to me like you don't need a mock at all. You are testing AddNLogConfigurationTypeTagret. Not the constructor.
[Theory]
[MemberData("ConsoleTargetBuilderTestData")]
public void ConsoleTargetBuilder_Should_Add_A_Console_Target(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration, int expectedConsoleTargetCount)
{
// ARRANGE
var consoleTargetBuilder = new ConsoleTargetBuilder(loggerModel, nLogLoggingConfiguration);
// ACT
consoleTargetBuilder.AddNLogConfigurationTypeTagret();
// ASSERT
Assert.Equal(expectedConsoleTargetCount, nLogLoggingConfiguration.AllTargets.Count);
}
If you don't want to call AddNLogConfigurationTypeTagret yourself, it should be called in the constructor. This changes the test to this :
[Theory]
[MemberData("ConsoleTargetBuilderTestData")]
public void ConsoleTargetBuilder_Should_Add_A_Console_Target(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration, int expectedConsoleTargetCount)
{
// ARRANGE
// ACT
var consoleTargetBuilder = new ConsoleTargetBuilder(loggerModel, nLogLoggingConfiguration);
// ASSERT
Assert.Equal(expectedConsoleTargetCount, nLogLoggingConfiguration.AllTargets.Count);
}
and the class constructor should then be :
public ConsoleTargetBuilder(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration)
{
_loggerModel = loggerModel;
_nLogLoggingConfiguration = nLogLoggingConfiguration;
AddNLogConfigurationTypeTagret();
}
Please guide me to the right direction, I want two things. A) the method was called. B) two targets were added. So the expected count is 2.
A) If you wish to verify that method AddNLogConfigurationTypeTagret was called, then you need to test it on the code which is calling this method. E.g. something like the class ConsoleTargetBuilderClient which is an hypothetical example of a class which is using the ITargetBuilder (in your own code you should have some place where the class ConsoleTargetBuilder is used).
public class ConsoleTargetBuilderClient
{
private ITargetBuilder _builder;
public ConsoleTargetBuilderClient(ITargetBuilder builder)
{
_builder = builder;
}
public void DoSomething()
{
_builder.AddNLogConfigurationTypeTagret();
}
}
Then you can have a test which verifies that the method DoSomething called the method AddNLogConfigurationTypeTagret. For that purpose you can use a mock of ConsoleTargetBuilder because you test interaction with it. Test might look like this:
public void DoSomething_WhenCalled_AddNLogConfigurationTypeTagretGetsCalled()
{
// Arrange
bool addNLogConfigurationTypeTagretWasCalled = false;
Mock<ITargetBuilder> targetBuilderMock = new Mock<ITargetBuilder>();
targetBuilderMock.Setup(b => b.AddNLogConfigurationTypeTagret())
.Callback(() => addNLogConfigurationTypeTagretWasCalled = true);
ConsoleTargetBuilderClient client = new ConsoleTargetBuilderClient(targetBuilderMock.Object);
// Act
client.DoSomething();
// Assert
Assert.IsTrue(addNLogConfigurationTypeTagretWasCalled);
}
B) If you wish to verify that the targets were added you need to test the code itself (not mock of it). Test might look like this:
public void AddNLogConfigurationTypeTagret_WhenCalled_ConsoleTargetsAdded()
{
// Arrange
const int expectedConsoleTargetCount = 2;
var loggerModel = new LoggerModel();
var nLogLoggingConfiguration = new LoggingConfiguration();
var consoleTargetBuilder = new ConsoleTargetBuilder(loggerModel, nLogLoggingConfiguration);
// Act
consoleTargetBuilder.AddNLogConfigurationTypeTagret();
// Assert
Assert.AreEqual<int>(expectedConsoleTargetCount, nLogLoggingConfiguration.AllTargets.Count);
}
Note: google value-based vs. state-based vs. interaction testing.
Generally speaking, you shouldn't be mocking the class you want to test, you should be mocking it's dependencies. When you start mocking the class you're trying to test things often get entwined leading to brittle tests and it's difficult to determine if you're testing your code, or you mocking setup, or both.
The method AddNLogConfigurationTypeTagret is a public method on the class you're testing, so as #Philip has said, you should probably just be calling it from your test, or it should be called from your constructor. If you goal is for it to be called from your constructor, then I'd suggest that it should probably be a private method unless there's a reason for it to be called from outside the class.
As far as testing the effects of a void method call, you're interested in the state change caused by the method. In this instance, whether or not the _nLoggingConfiguration has two targets added with the correct attributes. You don't show us the nLoggingConfiguration.AllTargets property, but I would assume from the fact that you're using the Count property in your test, that you could simply inspect the items in the list to confirm that the correct name and layout have been added to the correct target type.
// Assert
targetBuilderMock.Verify(x => x.AddNLogConfigurationTypeTagret(), Times.Once());

What do I supply to Moq for my Generate() method's delegate parameter?

I've got a legacy system that I'm in the midst of refactoring.
I have an object substantially as follows:
public class SUT
{
public delegate SaveStuff(SomeObject obj);
public void Generate(SaveStuff saver)
{
// Do stuff
var obj = new SomeObject();
saver(obj);
}
}
I'm very new to using Moq, and want to count the number of times 'saver' is called.
I've seen a number of examples here on SO, but am stumped on how to setup the test
[Test]
public void TestDelegateCall()
{
var sut = new SUT();
// Prepare SUT's State...
var callCount = 0;
sut.Generate(??);
Assert.AreEqual(callCount,2);
}
What goes where the ?? is ?
I dont know that you need to use MOQ here, I believe you could just do the following and take advantage of anonymous methods and closures :)
var callCount = 0
sut.Generate(obj=>callCount++);
If that does not work, then you can just use the explicit delegate setup:
var callCount = 0
SaveStuff actionCounter = delegate(SomeObject obj)
{
callCount++;
};
sut.Generate(actionCounter);

How can I assert that a particular method was called using NUnit?

How can I test that a particular method was called with the right parameters as a result of a test? I am using NUnit.
The method doesn't return anything. it just writes on a file. I am using a mock object for System.IO.File. So I want to test that the function was called or not.
More context is needed. So I'll put one here adding Moq to the mix:
pubilc class Calc {
public int DoubleIt(string a) {
return ToInt(a)*2;
}
public virtual int ToInt(string s) {
return int.Parse(s);
}
}
// The test:
var mock = new Mock<Calc>();
string parameterPassed = null;
mock.Setup(c => x.ToInt(It.Is.Any<int>())).Returns(3).Callback(s => parameterPassed = s);
mock.Object.DoubleIt("3");
Assert.AreEqual("3", parameterPassed);
You have to use some mocking framework, such as Typemock or Rhino Mocks, or NMocks2.
NUnit also has a Nunit.Mock, but it is not well-known.
The syntax for moq can be found here:
var mock = new Mock<ILoveThisFramework>();
// WOW! No record/reply weirdness?! :)
mock.Setup(framework => framework.DownloadExists("2.0.0.0"))
.Returns(true)
.AtMostOnce();
// Hand mock.Object as a collaborator and exercise it,
// like calling methods on it...
ILoveThisFramework lovable = mock.Object;
bool download = lovable.DownloadExists("2.0.0.0");
// Verify that the given method was indeed called with the expected value
mock.Verify(framework => framework.DownloadExists("2.0.0.0"));
Also, note that you can only mock interface, so if your object from System.IO.File doesn't have an interface, then probably you can't do. You have to wrap your call to System.IO.File inside your own custom class for the job.
By using a mock for an interface.
Say you have your class ImplClass which uses the interface Finder and you want to make sure the Search function gets called with the argument "hello";
so we have:
public interface Finder
{
public string Search(string arg);
}
and
public class ImplClass
{
public ImplClass(Finder finder)
{
...
}
public void doStuff();
}
Then you can write a mock for your test code
private class FinderMock : Finder
{
public int numTimesCalled = 0;
string expected;
public FinderMock(string expected)
{
this.expected = expected;
}
public string Search(string arg)
{
numTimesCalled++;
Assert.AreEqual(expected, arg);
}
}
then the test code:
FinderMock mock = new FinderMock("hello");
ImplClass impl = new ImplClass(mock);
impl.doStuff();
Assert.AreEqual(1, mock.numTimesCalled);
In Rhino Mocks where is a method called AssertWasCalled
Here is a way to use it
var mailDeliveryManager = MockRepository.GenerateMock<IMailDeliveryManager>();
var mailHandler = new PlannedSending.Business.Handlers.MailHandler(mailDeliveryManager);
mailHandler.NotifyPrinting(User, Info);
mailDeliveryManager.AssertWasCalled(x => x.SendMailMessage(null, null, null), o => o.IgnoreArguments());

Categories

Resources