Unit test a void method with Mock? - c#

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());

Related

Moq: How to attach to a delegate property of an object, when that object is a mock?

I have an object I want to test, and a dependency for it which I am mocking. The dependency has a public delegate property which functions essentially like an event. (I cannot change the code of the dependency.) How do I mock the dependency, then trigger its delegate property?
My situation:
/* The thing I am mocking */
public interface IUserLoginReporter {
public delegate void UserLoggedIn(string userName);
UserLoggedIn OnUserLoggedIn { get; set; }
}
/* The thing I am testing */
public class UserService {
public UserService(IUserLoginReporter reporter)
{
reporter.OnUserLoggedIn += RefreshLastSeenTime;
}
public void RefreshLastSeenTime(string username)
{
...
}
}
As you can see, the UserLoginReporter has a delegate property which it will invoke when the user logs in. The UserService attaches its RefreshLastSeenTime to this delegate, so we take some actions in response.
Here is essentially the test I wrote:
[Fact]
public void DelegateGetsInvoked()
{
// Given
var mockReporter = new Mock<IUserLoginReporter>();
var userService = new UserService(mockReporter.Object);
// When
mockReporter.OnUserLoggedIn("abc");
// Then
// ... verify userService took correct actions ...
}
I am getting a null-reference exception on the line just under // When.
Ideally if the interface is as simple as described in your example, you are better off just creating a simple implementation for your test.
However, the following will allow the delegate to be invoked and call the attached delegate within the subject under test
//Arrange
var mock = new Mock<IUserLoginReporter>();
mock.SetupAllProperties(); //<--Automatically allow properties to be modifiable
UserService subject = new UserService(mock.Object);
string input = "I am working";
//Act
mock.Object.OnUserLoggedIn(input);
//Assert
mock.Verify(_ => _.OnUserLoggedIn);
//...assert expected behavior
What you are trying to assert was not stated so whether that is possible is left to be seen.

How do I write a unit test for this method that is called inside a loop?

I'm trying to test a method using xUnit and Moq.
The public void DoSomeWork_Verify_GetJsonDataString_is_called() test is failing. Please can someone let me know what I am missing in the test/mocking. The GetJsonDataString is an API call that returns a JSON string.
public class A
{
private readonly IData _data;
private readonly IApiCall _apiCall;
public A (IData data, IApiCall apiCall)
{
_data = data;
_apiCall = apiCall;
}
public void DoSomeWork
{
var apps = _data.GetListOfApps(); // test on this method call is passing
foreach(var app in apps)
{
if(string.IsNullOrEmpty(app.AppId)) continue;
string jsonString = _apiCall.GetJsonDataString("ApiEndpoint" + app.AppId);
// how do I test this method call? Note: I'm not using async, this is just a console app.
}
}
}
//MyTest
public class TestA
{
private readonly Mock<IData> _data;
private readonly Mock<IApiCall> _apicall;
public TestA()
{
_data = new Mock<IData>;
_apiCall = new Mock<IApiCall>;
}
public void DoSomeWork_Verify_GetListOfApps_is_called()
{
_data.Setup(x => x.GetListOfApps());
var sut = new A(_data.Object, _apiCall.Object);
sut.DoSomeWork();
_data.Verify(x => x.GetListOfApps(), Times.AtLeastOnce); // this passes
}
public void DoSomeWork_Verify_GetJsonDataString_is_called()
{
_apicall.Setup(x => x.GetJsonDataString(It.IsAny<string>()));
var sut = new A(_data.Object, _apiCall.Object);
sut.DoSomeWork();
_apicall.Verify(x => x.GetJsonDataString(It.IsAny<string>()), Times.AtLeastOnce); // Failing
}
}
You need to mock GetListOfApps so that it actually returns something for you to loop over. To do that you need to make use of the Returns method.
Assuming the method returns a List<App> your setup could look like the following:
_data.Setup(x => x.GetListOfApps())
.Returns(new List<App> { new App { AppId = "X" } });
Now your method will recieve data to loop over and the method you are trying to verify will be called.
Note that while you are setting up GetJsonDataString, you aren't giving it a return value. By default Moq will return null but you should probably mock that with a return value as well.
_data.Setup(x => x.GetJsonDataString(It.IsAny<string>()))
.Returns("some string");
There are also overloads of Returns that accept a factory function and will take the arguments passed to the mocked function as input. You can use this if you want/need the return result to vary based on the input parameters.
_data.Setup(x => x.GetJsonDataString(It.IsAny<string>()))
.Returns(strParam => "some string" + strParam);
Now when you're verifying, I'd advise against using It.IsAny when you can. Otherwise you are saying that you don't care how it's called. Suppose we wanted to verify it actually got called with the mocked value from above (AppId="X") you would do this:
_apicall.Verify(x => x.GetJsonDataString("ApiEndPointX"), Times.Once);
Now you've got a test that's not just checking whether or not the method was called, but actually validating it got called with the expected values.
Side note: there is no reason for your test class to accept parameters in its constructor, especially of type Mock<>. You aren't even using them! And technically this should fail to even execute since you don't have an IClassFixture set up. You can get rid of the constructor completely (and assign the fields directly) or just remove the parameters:
public TestA()
{
_data = new Mock<IData>();
_apiCall = new Mock<IApiCall>();
}

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.

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