c# - How to Mock SystemClock.Instance.GetCurrentInstant()? [duplicate] - c#

I am pretty new to use moq. I am into creating some unit test case to HttpModule and everything works fine until I hit a static property as follows
this.applicationPath = (HttpRuntime.AppDomainAppVirtualPath.Length > 1) ? HttpRuntime.AppDomainAppVirtualPath : String.Empty;
I do not know how create mocks for static class and property like HttpRuntime.AppDomainAppVirtualPath. The context, request and response have been mocked well with sample code I get from moq. I will appreciate if somebody can help me on this.

Moq can't fake static members.
As a solution you can create a wrapper class (Adapter Pattern) holding the static property and fake its members.
For example:
public class HttpRuntimeWrapper
{
public virtual string AppDomainAppVirtualPath
{
get
{
return HttpRuntime.AppDomainAppVirtualPath;
}
}
}
In the production code you can access this class instead of HttpRuntime and fake this property:
[Test]
public void AppDomainAppVirtualPathTest()
{
var mock = new Moq.Mock<HttpRuntimeWrapper>();
mock.Setup(fake => fake.AppDomainAppVirtualPath).Returns("FakedPath");
Assert.AreEqual("FakedPath", mock.Object.AppDomainAppVirtualPath);
}
Another solution is to use Isolation framework (as Typemock Isolator) in which you can fake static classes and members.
For example:
Isolate.WhenCalled(() => HttpRuntime.AppDomainAppVirtualPath)
.WillReturn("FakedPath");
Disclaimer - I work at Typemock

You cannot Moq static methods with Moq.
This is not a bad thing in reality, static methods and classes do have their place but for logic they make unit testing difficult. Naturally you'll run into them when using other libraries. To get around this you'll need to write an adapter (wrapper) around the static code, and provide an interface. For example:
// Your static class - hard to mock
class StaticClass
{
public static int ReturnOne()
{
return 1;
}
}
// Interface that you'll use for a wrapper
interface IStatic
{
int ReturnOne();
}
Note, I've ommited the concrete class that uses IStatic for the production code. All
it would be is a class which uses IStatic and your production code would make use of this class, rather than StaticClass above.
Then with Moq:
var staticMock = new Mock<IStatic>();
staticMock.Setup(s => s.ReturnOne()).Returns(2);

As mentioned in previous answers, you can't use MoQ on static methods, and if you need to, your best shot is to create a wrapper around the static class.
However, something I've discovered recently is the Moles project. From the homepage; "Moles allows to replace any .NET method with a delegate. Moles supports static or non-virtual methods." It might be useful for your current situation.

Best solution I have found so far is Telerik's JustMock - unfortunately only the paid for version allows mocking of statics.
While the idea of wrapping statics is a good one - you can't always do this. If you want to test some code that uses some static classes already then it's not always possible to switch out and use a wrapper. In this case JustMock looks a reasonable solution and I'm probably going to use it on some solutions in the near future.

You can use Microsoft Fakes for this. It will definitely solve the issue.
Refer to https://msdn.microsoft.com/en-us/library/hh549175.aspx

Using Microsoft Fakes as suggested by #Sujith is a viable solution. Here is how you actually do it:
Find System.Web in your reference of your test project and right click
Choose "Add". This adds reference System.Web.4.0.0.0.Fakes
Use following code:
using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create())
{
System.Web.Fakes.ShimHttpRuntime.AppDomainAppVirtualPathGet = () => "/";
// Do what ever needs the faked AppDomainAppVirtualPath
}

Related

Nsubstitute testing if a private class's method was called

Don't have much experience with testing, trying to change that by testing libraries I've made recently.
Using nunit with nsubstitute for this.
So the situation I have is a class like this:
class MyClassToTest {
private ISomeOtherClass MyPrivateClass { get;set }
public MyClassToTest() {
MyPrivateClass = new SomeOtherClass();
}
public void DoSomething() {
MyPrivateClass.SayHello();
}
}
Now, a test for the DoSomething method would be to see if the method SayHello() was actually called on the ISomeOtherClass instance.
The problem is that it's private, when looking up the best way to test this, the only thing that came up was to make the property internal and set the InternalsVisibleToAttribute to the assembly the tests are in.
While this solution works and the external interface for my library is still ok, the correct accessor for this property in the context of the library would still be private.
The test I'd write is after making it interal:
public void MyTest() {
var objPrivateClass = Substitute.For<ISomeOtherClass>();
var obj = new MyClassToTest();
obj.MyPrivateClass = objPrivateClass;
obj.DoSomething();
objPrivateClass.Received().SayHello();
}
Is there a better way to test this without me having to modify my original code to make it testable?
It might be setting InternalsVisibleToAttribute and making the property internal is the correct thing here, but a couple of hours ago I didn't know about the existence of InternalsVisibleToAttribute so thought it best to ask :)
To answer the exact question, You can use reflection to reach private members, but that is a fragile and rather slow solution.
The best advice I can give you is that private things should stay private; test an object's behavior through its public interface. So if is too big and hard to test, just refactor it to be testable. Think of the Single Responsibility Principle and the Inversion of Control principles.
Edit 1.: You are probably looking for the concept of Dependency Injection. This should be alright most of the times; however when we talk about highly reusable libraries (you mentioned you are making a lib), other solutions may fit better for the users of your library (e.g. creating a Facade or rethinking your design).

How to write unit test for private method in c# using moq framework?

I want to write unit test for private method in C# using moq framework, I've search in StackOverFlow and Google, but I cannot find the expected result. Please help me if you can.
You can't, at least not with Moq.
But more importantly, you shouldn't.
First off, you don't test methods, you test behaviours. Second, in order to test behaviours, you exercise a type's public API and verify the outcomes of that exercise.
Private methods are implementation details. You don't want to verify how things get done, you want to verify that things do get done.
In the AssemblyInfo.cs of your project add
[assembly: InternalsVisibleTo("Namespace.OfYourUnitTest.Project")]
then you make the method internal instead of private.
It has the benefit of avoiding to make it public.
However as pointed by dcastro, some people strongly disagree with this way of testing.
Perhaps you shouldn't (see other answers for why), but you can do this using Microsoft's Visual Studio Test Tools. A simplified example is given below.
Given the following class which you want to test:
public class ClassToTest
{
private int Duplicate(int n)
{
return n*2;
}
}
You can use the following code to test the private Duplicate method:
using Microsoft.VisualStudio.TestTools.UnitTesting;
// ...
[TestMethod]
public void MyTestMethod()
{
// Arrange
var testClass = new ClassToTest();
var privateObject = new PrivateObject(testClass);
// Act
var output = (int) privateObject.Invoke("Duplicate", 21);
// Assert
Assert.AreEqual(42, output);
}
Simply, you don't. Private methods are not visible to other classes.
There are a number of ways around this:
Treat the private as part of the method you're testing, cover it in their unit tests. Think of the public methods as black boxes and test their operations.
Make it protected and inherit your test class from the class you're testing (or use a partial - same idea)
Make it public (which if you're coding to an interface doesn't actually expose it to your consumers)
For public methods (option three) it is possible to partial mock the class where you can replace the method. In Moq you can do this like this:
var moq = new Mock<MyClass>();
moq.CallBase = true;
moq.Setup(x => x.MyPublicMethodToOverride()).Returns(true);
There are more details here.
Moq supports mocking protected methods. Changing the methods to protected, instead of private, would allow you to mock their implementation.
The following is from Moq Quickstart Documentation (deep link):
Setting expectations for protected members (you can't get IntelliSense
for these, so you access them using the member name as a string).
Assuming the following class with a protected function should be
mocked:
public class CommandBase {
protected virtual int Execute(); // (1)
protected virtual bool Execute(string arg); // (2)
}
// at the top of the test fixture
using Moq.Protected;
// In the test, mocking the `int Execute()` method (1)
var mock = new Mock<CommandBase>();
mock.Protected()
.Setup<int>("Execute")
.Returns(5);
// If you need argument matching, you MUST use ItExpr rather than It
// planning on improving this for vNext (see below for an alternative in Moq 4.8)
// Mocking the `bool Execute(string arg)` method (2)
mock.Protected()
.Setup<bool>("Execute",
ItExpr.IsAny<string>())
.Returns(true);
Moq 4.8 and later allows you to set up protected members through a
completely unrelated type that has the same members and thus provides
the type information necessary for IntelliSense to work. Pickin up the
example from the bullet point above, you can also use this interface
to set up protected generic methods and those having by-ref
parameters:
// Completely unrelated Interface (CommandBase is not derived from it) only created for the test.
// It contains a method with an identical method signature to the protected method in the actual class which should be mocked
interface CommandBaseProtectedMembers
{
bool Execute(string arg);
}
mock.Protected().As<CommandBaseProtectedMembers>()
.Setup(m => m.Execute(It.IsAny<string>())) // will set up CommandBase.Execute
.Returns(true);

mock object for unit testing rather more related to OOP question

My application has the following project structure: There is the Business Logic project and the UnitTesting project where the methods from the Business Logic are tested. No mocking or testing framework are used (we rely on Visual Studio unit tests and we implement our own mock objects).
In the Business Logic let's say I have the following method:
public static void SomeMethod ()
{
....
if (cond1)
if (cond2)
SendMail();
}
I want to unit test that. I don't want to unit test the sending of the mail, rather the mail is sent under the correct circumstances. So I was thinking to do something like
public class MailSender : ISmtpMail
{
// stuff
}
public class FakeMailSender : ISmtpMail
{
//
static bool SendMail ()
{
return true;
}
}
The problem is that I don't know how to enforce the usage of the FakeMailSender in the unit test project or in the unit test methods which look something like :
[TestMethod]
public static void SomeMethod_Test()
{
// some mock initialization
BusinessLogic.SomeMEthod ();
// checks
}
without changing the BusinessLogic method signature or injecting code (which is undesired)
It's not clear where your first method "lives". It seems to me that:
Your SendMail method shouldn't be static, which makes all kinds of test double injection tricky to say the least
You should inject ISmtpMail into whatever needs to send mail.
You say you want to do it "without injecting code" - why not? The "mail sending" service is clearly a dependency: your code will be clearer, less tightly coupled, and easier to test if you inject that depedency, whether explictly or with the help of a DI container.
The problem is that you're using static methods. There's no clean way of configuring that singleton instance to use different services.
Consider this. Make your SomeMethod non-static and inject the required services into the business logic instance:
private ISmtpMail _smtpMail;
public BusinessLogic(ISmtpMail smtpMail)
{
_smtpMail = smtpMail;
}
public void SomeMethod()
{
...
_smtpMail.Send();
}
Your test code will then be able to enforce which service to use:
[TestMethod]
public static void SomeMethod_Test()
{
// some mock initialization
var bl = new BusinessLogic(new FakeMailSender());
bl.SomeMethod();
// checks
}
For production code, I strongly encourage you to look at some of the excellent Dependency Injection frameworks out there, e.g. Autofac, which makes the service injections happen more or less by magic.
With statics you can use commercial library like Typemock. However, if you are forced to use that it means you have a bad design, probably even misunderstanding the concept of oop. I'd recommend to refactor and use the injection as Jon Skeet and Peter Lillevold already suggested.
First of all you should avoid using any static mocking, and use classical injection pattern as already suggested.
But if you really want to mock static methods (for example, in cases when you can't change this code because this code reside in third-party library), you can use Moles.
Suppose you have following MailSender class:
namespace MyNamespace {
class MailSender
{
public static bool SendMail() {...}
}
}
Moles can generate "mole" for this class with Action delegate witch would be called instead of original method every time your code calls this original method. And than you could write following test:
[TestMethod]
public static void SomeMethod_Test()
{
// After that all calls to MyNamespace.MailSender.SendMail whould
// return true
MyNamespace.Moles.MMailSender.SendMail = () => true;
BusinessLogicClass.SomeMethod();
}
BTW, Moles can also help you mocking not only static methods and non-virtual methods with moles, but this tool can generate similar stub classes for testing interfaces or classes with virtual methods.

Mock static property with moq

I am pretty new to use moq. I am into creating some unit test case to HttpModule and everything works fine until I hit a static property as follows
this.applicationPath = (HttpRuntime.AppDomainAppVirtualPath.Length > 1) ? HttpRuntime.AppDomainAppVirtualPath : String.Empty;
I do not know how create mocks for static class and property like HttpRuntime.AppDomainAppVirtualPath. The context, request and response have been mocked well with sample code I get from moq. I will appreciate if somebody can help me on this.
Moq can't fake static members.
As a solution you can create a wrapper class (Adapter Pattern) holding the static property and fake its members.
For example:
public class HttpRuntimeWrapper
{
public virtual string AppDomainAppVirtualPath
{
get
{
return HttpRuntime.AppDomainAppVirtualPath;
}
}
}
In the production code you can access this class instead of HttpRuntime and fake this property:
[Test]
public void AppDomainAppVirtualPathTest()
{
var mock = new Moq.Mock<HttpRuntimeWrapper>();
mock.Setup(fake => fake.AppDomainAppVirtualPath).Returns("FakedPath");
Assert.AreEqual("FakedPath", mock.Object.AppDomainAppVirtualPath);
}
Another solution is to use Isolation framework (as Typemock Isolator) in which you can fake static classes and members.
For example:
Isolate.WhenCalled(() => HttpRuntime.AppDomainAppVirtualPath)
.WillReturn("FakedPath");
Disclaimer - I work at Typemock
You cannot Moq static methods with Moq.
This is not a bad thing in reality, static methods and classes do have their place but for logic they make unit testing difficult. Naturally you'll run into them when using other libraries. To get around this you'll need to write an adapter (wrapper) around the static code, and provide an interface. For example:
// Your static class - hard to mock
class StaticClass
{
public static int ReturnOne()
{
return 1;
}
}
// Interface that you'll use for a wrapper
interface IStatic
{
int ReturnOne();
}
Note, I've ommited the concrete class that uses IStatic for the production code. All
it would be is a class which uses IStatic and your production code would make use of this class, rather than StaticClass above.
Then with Moq:
var staticMock = new Mock<IStatic>();
staticMock.Setup(s => s.ReturnOne()).Returns(2);
As mentioned in previous answers, you can't use MoQ on static methods, and if you need to, your best shot is to create a wrapper around the static class.
However, something I've discovered recently is the Moles project. From the homepage; "Moles allows to replace any .NET method with a delegate. Moles supports static or non-virtual methods." It might be useful for your current situation.
Best solution I have found so far is Telerik's JustMock - unfortunately only the paid for version allows mocking of statics.
While the idea of wrapping statics is a good one - you can't always do this. If you want to test some code that uses some static classes already then it's not always possible to switch out and use a wrapper. In this case JustMock looks a reasonable solution and I'm probably going to use it on some solutions in the near future.
You can use Microsoft Fakes for this. It will definitely solve the issue.
Refer to https://msdn.microsoft.com/en-us/library/hh549175.aspx
Using Microsoft Fakes as suggested by #Sujith is a viable solution. Here is how you actually do it:
Find System.Web in your reference of your test project and right click
Choose "Add". This adds reference System.Web.4.0.0.0.Fakes
Use following code:
using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create())
{
System.Web.Fakes.ShimHttpRuntime.AppDomainAppVirtualPathGet = () => "/";
// Do what ever needs the faked AppDomainAppVirtualPath
}

How to unit test a method with a `using` statement?

How can I write a unit test for a method that has a using statement?
For example let assume that I have a method Foo.
public bool Foo()
{
using (IMyDisposableClass client = new MyDisposableClass())
{
return client.SomeOtherMethod();
}
}
How can I test something like the code above?
Sometimes I choose not to use using statement and Dispose() an object manually. I hope that someone will show me a trick I can use.
If you construct the IMyDisposableClass using a factory (injected into the parent class) rather than using the new keyword, you can mock the IMyDisposable and do a verify on the dispose method call.
public bool Foo()
{
using (IMyDisposableClass client = _myDisposableClassFactory.Create())
{
return client.SomeOtherMethod();
}
}
If you already have your code and are asking how to test it, then you're not writing your tests first...so aren't really doing TDD.
However, what you have here is a dependency. So the TDD approach would be to use Dependency Injection. This can be made easier using an IoC container like Unity.
When doing TDD "properly", your thought processes should run as follows in this sort of scenario:
I need to do a Foo
For this I will rely on an external dependency that will implement an interface (new or pre-existing) of IMyDisposableClass
Therefore I will inject an IMyDisposableClass into the class in which Foo is declared via its constructor
Then you would write one (or more) tests that fail, and only then would you be at the point where you were writing the Foo function body, and determine whether you needed to use a using block.
In reality you might well know that yes, you will use a using block. But part of the point of TDD is that you don't need to worry about that until you've proven (via tests) that you do need to use an object that requires this.
Once you've determined that you need to use a using block you would then want to write a test that fails - for example using something like Rhino Mocks to set an expectation that Dispose will get called on a mock object that implements IMyDisposableClass.
For example (using Rhino Mocks to mock IMyDisposableClass).
[TestFixture]
public class When_calling_Foo
{
[Test]
public void Should_call_Dispose()
{
IMyDisposableClass disposable = MockRepository
.GenerateMock<IMyDisposableClass>();
Stuff stuff = new Stuff(disposable);
stuff.Foo();
disposable.AssertWasCalled(x => x.Dispose());
}
}
Class in which your Foo function exists, with IMyDisposableClass injected as a dependency:
public class Stuff
{
private readonly IMyDisposableClass _client;
public Stuff(IMyDisposableClass client)
{
_client = client;
}
public bool Foo()
{
using (_client)
{
return _client.SomeOtherMethod();
}
}
}
And the interface IMyDisposableClass
public interface IMyDisposableClass : IDisposable
{
bool SomeOtherMethod();
}
Your question doesn't make sense. If you are using TDD, then you should already have a test for what you have written. Requirements, then tests, then design, then development. Either your code passes your tests, or it doesn't.
Now, if your question is how to unit test the above piece of code, then that's another question completely, and I think the other posters have answered it up there.
Sometimes I think there are more buzzwords than developers :)
Wrapper methods like that aren't unit-testable, because you can't specify the relevant preconditions or post-conditions.
To make the method testable, you'll have to pass an IMyDisposableClass instance into the method or into the class hosting Foo (and make the host class itself implement IDisposable), so you can use a test double instead of the real thing to verify any interactions with it.
Your question doesn't make sense. If you are doing TDD, then the method that you posted is already fully tested, otherwise it couldn't even exist in the first place. So, your question doesn't make sense.
If, on the other hand, the method that you posted does already exist, but isn't fully tested, then you aren't doing TDD anyway, and your question about TDD doesn't make sense, either.
In TDD, it is simply impossible for untested code to exist. Period.
You could also change the method signature to allow passing in a mock for unit testing. This would provide an alternative to using a factory, which would also need to be unit tested. DI into the method as opposed to the class constructor may be preferable here.
public bool Foo(IMyDisposableClass mock = null)
{
using (IMyDisposableClass client = mock ?? new MyDisposableClass())
{
return client.SomeOtherMethod();
}
}
If you are testing Foo, then you should be looking at the output of Foo, not worrying about the disposal of the class it is using internally.
If you want to test MyDisposableClass' dispose method to see if it is working, that should be a separate unit test built against MyDisposableClass.
You don't need to unit test the using { } block, since that is part of the language. You either trust that it's working, or don't use C#. :) I don't see the need to write a unit test to verify that Dispose() is being called.
Without a specification for Foo, how can we say how to test it?
Get the specification for Foo.
Write tests to ensure that it meets all specifications and requirements (or a reasonable subset- some functions could require practically infinite amounts of data to test).
I believe you have a second, implicit question in there - which is how to test that use of your MyDisposableClass correctly Disposes of the object when it is freed by exiting an using clause. This is a separate test issue, and shouldn't be combined with the test of Foo, since the specification of Foo shouldn't reference implementation specific details such as the use of your MyDisposabeClass.
I think the other posters have answered this question, so I won't further elaborate.

Categories

Resources