Can't mock an extension method wtih JustMock [duplicate] - c#

I am writing a test that depends on the results of an extension method but I don't want a future failure of that extension method to ever break this test. Mocking that result seemed the obvious choice but Moq doesn't seem to offer a way to override a static method (a requirement for an extension method). There is a similar idea with Moq.Protected and Moq.Stub, but they don't seem to offer anything for this scenario. Am I missing something or should I be going about this a different way?
Here is a trivial example that fails with the usual "Invalid expectation on a non-overridable member". This is a bad example of needing to mock an extension method, but it should do.
public class SomeType {
int Id { get; set; }
}
var ListMock = new Mock<List<SomeType>>();
ListMock.Expect(l => l.FirstOrDefault(st => st.Id == 5))
.Returns(new SomeType { Id = 5 });
As for any TypeMock junkies that might suggest I use Isolator instead: I appreciate the effort since it looks like TypeMock could do the job blindfolded and inebriated, but our budget isn't increasing any time soon.

Extension methods are just static methods in disguise. Mocking frameworks like Moq or Rhinomocks can only create mock instances of objects, this means mocking static methods is not possible.

If you can change the extension methods code then you can code it like this to be able to test:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
public static class MyExtensions
{
public static IMyImplementation Implementation = new MyImplementation();
public static string MyMethod(this object obj)
{
return Implementation.MyMethod(obj);
}
}
public interface IMyImplementation
{
string MyMethod(object obj);
}
public class MyImplementation : IMyImplementation
{
public string MyMethod(object obj)
{
return "Hello World!";
}
}
So the extention methods are only a wrapper around the implementation interface.
(You could use just the implementation class without extension methods which are sort of syntactic sugar.)
And you can mock the implementation interface and set it as implementation for the extensions class.
public class MyClassUsingExtensions
{
public string ReturnStringForObject(object obj)
{
return obj.MyMethod();
}
}
[TestClass]
public class MyTests
{
[TestMethod]
public void MyTest()
{
// Given:
//-------
var mockMyImplementation = new Mock<IMyImplementation>();
MyExtensions.Implementation = mockMyImplementation.Object;
var myClassUsingExtensions = new MyClassUsingExtensions();
// When:
//-------
var myObject = new Object();
myClassUsingExtensions.ReturnStringForObject(myObject);
//Then:
//-------
// This would fail because you cannot test for the extension method
//mockMyImplementation.Verify(m => m.MyMethod());
// This is success because you test for the mocked implementation interface
mockMyImplementation.Verify(m => m.MyMethod(myObject));
}
}

I know this question hasn't been active for about a year but Microsoft released a framework to handle exactly this called Moles.
Here are a few tutorials as well:
DimeCasts.net
Nikolai Tillman's Tutorial

I created a wrapper class for the extension methods that I needed to mock.
public static class MyExtensions
{
public static string MyExtension<T>(this T obj)
{
return "Hello World!";
}
}
public interface IExtensionMethodsWrapper
{
string MyExtension<T>(T myObj);
}
public class ExtensionMethodsWrapper : IExtensionMethodsWrapper
{
public string MyExtension<T>(T myObj)
{
return myObj.MyExtension();
}
}
Then you can mock the wrapper methods in your tests and code with your IOC container.

For extension methods I normally use the following approach:
public static class MyExtensions
{
public static Func<int,int, int> _doSumm = (x, y) => x + y;
public static int Summ(this int x, int y)
{
return _doSumm(x, y);
}
}
It allows to inject _doSumm fairly easy.

Best thing you can do is to provide a custom implementation for the type that has the extension method, e.g:
[Fact]
public class Tests
{
public void ShouldRunOk()
{
var service = new MyService(new FakeWebHostEnvironment());
// Service.DoStuff() internally calls the SomeExtensionFunction() on IWebHostEnvironment
// Here it works just fine as we provide a custom implementation of that interface
service.DoStuff().Should().NotBeNull();
}
}
public class FakeWebHostEnvironment : IWebHostEnvironment
{
/* IWebHostEnvironment implementation */
public bool SomeExtensionFunction()
{
return false;
}
}

Related

How to mock a private static inner class?

I'd like to ask a question which bother me a lot...
How can I mock the return value of MyPublicStaticMethod_C?? MyPrivateStaticClass_B is really private and static
public static partial class MyPublicStaticClass_A
{
private static partial class MyPrivateStaticClass_B
{
public static int MyPublicStaticMethod_C(string para)
{
//...
}
//...
}
}
I'm going to be slightly unhelpful here and say that you shouldn't mock that.
When writing tests you should only test your public interface, not your private. The private stuff is implementation specific and your tests shouldn't care about that.
If you have a public method that calls your private method and you feel that you need to mock the private method in order to properly test your class - that is a code smell. You should refactor your code and take in the inner private class as an interface, that way you can mock it.
If you do figure out a way to mock this in its current state, it will most likely not really give you a better tested system - however it will get you brittle tests that are hard to maintain.
You must reference the private type through the reflection API using GetNestedType(). Then you can use the non-public mocking API to arrange the method. Here's a working example:
public static partial class MyPublicStaticClass_A
{
public static int Test(string str)
{
return MyPrivateStaticClass_B.MyPublicStaticMethod_C(str);
}
private static partial class MyPrivateStaticClass_B
{
public static int MyPublicStaticMethod_C(string para)
{
return 1;
}
}
}
[TestMethod]
public void ShouldArrangeInnerPrivateClassMethod()
{
var privateType = typeof(MyPublicStaticClass_A).GetNestedType("MyPrivateStaticClass_B", BindingFlags.NonPublic);
Mock.NonPublic.Arrange<int>(privateType, "MyPublicStaticMethod_C").Returns(5);
var result = MyPublicStaticClass_A.Test(null);
Assert.Equal(5, result);
}
But, yeah, having such code should be a last resort - only if refactoring is impossible or unfeasible.

NSubstitute mock extension method

I want to do mock extension method, but it does not work. How can this be done?
public static class RandomExtensions
{
public static IEnumerable<int> NextInt32s(this System.Random random, int neededValuesNumber, int minInclusive, int maxExclusive)
{
// ...
}
}
[Fact]
public void Select()
{
var randomizer = Substitute.For<DefaultRandom>();
randomizer.NextInt32s(3, 1, 10).Returns(new int[] { 1, 2, 3 });
}
NSubstitute can not mock extension methods as per Sriram's comment, but you can still pass a mocked argument to an extension method.
In this case, the Random class has virtual methods, so we can mock that directly with NSubstitute and other DynamicProxy-based mocking tools. (For NSubstitute in particular we need to be very careful mocking classes. Please read the warning in the documentation.)
public static class RandomExtensions {
public static IEnumerable<int> NextInt32s(this System.Random random, int neededValuesNumber, int minInclusive, int maxExclusive) { /* ... */ }
}
public class RandomExtensionsTests {
[Test]
public void Select()
{
const int min = 0, max = 10;
var randomizer = Substitute.For<Random>();
randomizer.Next(min, max).Returns(1, 2, 3);
var result = randomizer.NextInt32s(3, 0, 10).ToArray();
Assert.AreEqual(new[] {1, 2, 3}, result);
}
}
Yes you can mock if you create an interface such as IRandom and extend the interface instead of the actual implementation. Then you should be able mock the interface in your test class.
public interface IRandom
{
}
public class Random : IRandom
{
}
public static class RandomExtensions
{
public static string NextInt32s(
this IRandom random,
int neededValuesNumber,
int minInclusive,
int maxExclusive)
{
}
}
In your test class add:
IRandom randomizer = Substitute.For<IRandom>();
var result = randomizer.NextInt32s(3,0,10);
By this process you are just mocking the interface not the actual class.
As an extension to other answers, here is how I got round it.
Imagine there is an interface IDoStuff and there is a library that extends IDoStuff. You have a class MyClass that implements IDoStuff and somewhere someone uses the extension method against the interface. It looks like this;
using System;
interface IDoStuff
{
string SayHello();
}
class MyClass : IDoStuff
{
public string SayHello()
{
return "Hello";
}
}
// somewhere someone wrote an extension method for IDoStuff
static class DoStuffExtensions
{
static string SayHelloToBob(this IDoStuff other)
{
return other.SayHello() + " Bob";
}
}
class UserOfIDoStuff
{
void UseIDoStuff(IDoStuff incoming)
{
Console.WriteLine(incoming.SayHelloToBob());
}
}
You want to mock IDoStuff but you cannot mock the extension method SayHelloToBob. What you can do is to create another interface that implements IDoStuff but also includes SayHelloToBob.
interface IDoStuffWithExtensions : IDoStuff
{
string SayHelloToBob();
}
class MyClass : IDoStuffWithExtensions
{
public string SayHello()
{
return "Hello";
}
// Wrap / internalise the extension method
public string SayHelloToBob()
{
return DoStuffExtensions.SayHelloToBob(this);
}
}
class UserOfIDoStuff
{
void UseIDoStuff(IDoStuffWithExtensions incoming)
{
Console.WriteLine(incoming.SayHelloToBob());
}
}
Now you can happily mock IDoStuffWithExtensions.
According to SOLID principle dependence inversion defines that lower level model should not be depended high level model but depended on abstract like interface and mocking concept is mainly used to mock interface so that low level model is not tested.

moq only one method in a class

I'm using moq.dll
When I mock a class(all the IRepository interface) i use this line code
int state = 5;
var rep = new Mock<IRepository>();
rep.Setup(x => x.SaveState(state)).Returns(true);
IRepository repository = rep.Object;
but in this case i mock all the function in repository class.
Then all the methods in class repository are substituted with the methods setup of Mock dll
I want use all the methods defined in class repository(the real class) and mock only one function(SaveState)
How can I do this? Is possible?
You can create an instance of the real repository, then use the As<>() to obtain the desired interface, which you can then override with the setup, like this:
var mockRep = new Mock<RealRepository>(ctorArg1, ctorArg2, ...)
.As<IRepository>();
mockRep.Setup(x => x.SaveState(state)).Returns(true);
Then mockRep.Object as the repository dependency to the class under test.
Note that you will only be able to Mock methods on the Interface*, or virtual methods, in this way.
Update : *This might not work in all scenarios, since .Setup will only work on virtual methods, and C# interface implementations are "virtual" and sealed by default. And using As() will prevent the partial mock behaviour.
So it appears that the RealRepository concrete class will need to implement the IRepository interface with virtual methods in order for the partial mock to succeed, in which case CallBase can be used for the wire-up.
public interface IRepo
{
string Foo();
string Bar();
}
public class RealRepo : IRepo
{
public RealRepo(string p1, string p2) {Console.WriteLine("CTOR : {0} {1}", p1, p2); }
// ** These need to be virtual in order for the partial mock Setups
public virtual string Foo() { return "RealFoo"; }
public virtual string Bar() {return "RealBar"; }
}
public class Sut
{
private readonly IRepo _repo;
public Sut(IRepo repo) { _repo = repo; }
public void DoFooBar()
{
Console.WriteLine(_repo.Foo());
Console.WriteLine(_repo.Bar());
}
}
[TestFixture]
public class SomeFixture
{
[Test]
public void SomeTest()
{
var mockRepo = new Mock<RealRepo>("1st Param", "2nd Param");
// For the partially mocked methods
mockRepo.Setup(mr => mr.Foo())
.Returns("MockedFoo");
// To wireup the concrete class.
mockRepo.CallBase = true;
var sut = new Sut(mockRepo.Object);
sut.DoFooBar();
}
}
I came to this page because I had exactly the same problem: I needed to mock a single method, which was relying on many external sources and could produce one of three outputs, while letting the rest of the class do its work. Unfortunately the partial mock approach proposed above did not work. I really don't know why it did not work. However, the main problem is that you can't debug inside such mocked class even if you put break points where you want. This is not good because you might really need to debug something.
So, I used a much simpler solution: Declare all methods that you want to mock as virtual. Then inherit from that class and write one-liner mock overrides to return what you want, for example:
public class Repository
{
/// <summary>
/// Let's say that SaveState can return true / false OR throw some exception.
/// </summary>
public virtual bool SaveState(int state)
{
// Do some complicated stuff that you don't care about but want to mock.
var result = false;
return result;
}
public void DoSomething()
{
// Do something useful here and assign a state.
var state = 0;
var result = SaveState(state);
// Do something useful with the result here.
}
}
public class MockedRepositoryWithReturnFalse : Repository
{
public override bool SaveState(int state) => false;
}
public class MockedRepositoryWithReturnTrue : Repository
{
public override bool SaveState(int state) => true;
}
public class MockedRepositoryWithThrow : Repository
{
public override bool SaveState(int state) =>
throw new InvalidOperationException("Some invalid operation...");
}
That's all. You can then use your mocked repos during unit tests AND you can debug anything you need. You can even leave the protection level below public so that not to expose what you don't want to expose.

Static repository... can't use DI, what to do?

I am in a situation where we need to modify what is being returned from the static repository in a 3rd party open-source application (NopCommerce). The problem is that they use static repositories, so I can't merely inherit an interface and DI my own repository. I'm trying to do this without modifying the NopCommerce code-base... any fresh ideas?
Edit: I want NopCommerce to use my repos, rather than have my code use theirs.
You could abstract away their stuff by creating an interface of your own and a class implementation that delegates to NopCommerce. Then have your code use the interface instead of directly accessing NopCommerce's classes. You can modify the output of NopCommerce inside your class before the result is returned to your application.
And as an added bonus you could also mock the interface to do some tests that didn't require the full-blown repository implementations.
Something like this, in code:
public interface IRepository
{
MyItem GetItem(int id);
}
public class MyNopCommerceWrapper : IRepository
{
public MyItem GetItem(int id)
{
// I have no idea what NopCommerce API looks like, so I made this up.
var myItem = NopCommerce.GetItem(id);
ModifyMyItem(myItem);
return myItem;
}
}
We are currently on a really, really tight deadline, and this problem was not forseen. So I am thinking of first starting with a poor man's static interface/poor man's DI like the following (so I don't have to modify the entire solution). Then at a later time, when we are not-so-pressed for time, change over to use an interface and dependency injection and submit a patch to NopCommerce:
// Poor-man's static interface (DI).
public static class OriginalBuiltInStaticClass {
private static IMyNewClass _myNewClass;
public static void Inject(IMyNewClass myNewClass) {
_myNewClass = myNewClass;
A = _myNewClass.A;
B = _myNewClass.B;
C = _myNewClass.C;
}
public static Action A = CopySimpleRenameBuiltInStaticClass.A;
public static Func<int, string> B = CopySimpleRenameBuiltInStaticClass.B;
public static Action C = CopySimpleRenameBuiltInStaticClass.C;
}
// Original vendor class which was copied and renamed.
public static class CopySimpleRenameBuiltInStaticClass {
public static void A() {
Console.WriteLine("OriginalBuiltInStaticClass.A()");
}
public static string B(int id) {
Console.WriteLine("OriginalBuiltInStaticClass.B()");
return id.ToString();
}
public static void C() {
Console.WriteLine("OriginalBuiltInStaticClass.C()");
}
}
// Creating an interface to merge into trunk of NopCommerce (convert static repositories)
public interface IMyNewClass {
void A();
string B(int id);
void C();
}
// Implementation of interface.
public class MyNewClass : IMyNewClass {
public void A() {
Console.WriteLine("MyNewClass.A()");
}
public string B(int id) {
Console.WriteLine("MyNewClass.B()");
return id.ToString();
}
public void C() {
CopySimpleRenameBuiltInStaticClass.C();
}
}
Any thoughts?
Sounds like a job for Facade.

How do I use Moq to mock an extension method?

I am writing a test that depends on the results of an extension method but I don't want a future failure of that extension method to ever break this test. Mocking that result seemed the obvious choice but Moq doesn't seem to offer a way to override a static method (a requirement for an extension method). There is a similar idea with Moq.Protected and Moq.Stub, but they don't seem to offer anything for this scenario. Am I missing something or should I be going about this a different way?
Here is a trivial example that fails with the usual "Invalid expectation on a non-overridable member". This is a bad example of needing to mock an extension method, but it should do.
public class SomeType {
int Id { get; set; }
}
var ListMock = new Mock<List<SomeType>>();
ListMock.Expect(l => l.FirstOrDefault(st => st.Id == 5))
.Returns(new SomeType { Id = 5 });
As for any TypeMock junkies that might suggest I use Isolator instead: I appreciate the effort since it looks like TypeMock could do the job blindfolded and inebriated, but our budget isn't increasing any time soon.
Extension methods are just static methods in disguise. Mocking frameworks like Moq or Rhinomocks can only create mock instances of objects, this means mocking static methods is not possible.
If you can change the extension methods code then you can code it like this to be able to test:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
public static class MyExtensions
{
public static IMyImplementation Implementation = new MyImplementation();
public static string MyMethod(this object obj)
{
return Implementation.MyMethod(obj);
}
}
public interface IMyImplementation
{
string MyMethod(object obj);
}
public class MyImplementation : IMyImplementation
{
public string MyMethod(object obj)
{
return "Hello World!";
}
}
So the extention methods are only a wrapper around the implementation interface.
(You could use just the implementation class without extension methods which are sort of syntactic sugar.)
And you can mock the implementation interface and set it as implementation for the extensions class.
public class MyClassUsingExtensions
{
public string ReturnStringForObject(object obj)
{
return obj.MyMethod();
}
}
[TestClass]
public class MyTests
{
[TestMethod]
public void MyTest()
{
// Given:
//-------
var mockMyImplementation = new Mock<IMyImplementation>();
MyExtensions.Implementation = mockMyImplementation.Object;
var myClassUsingExtensions = new MyClassUsingExtensions();
// When:
//-------
var myObject = new Object();
myClassUsingExtensions.ReturnStringForObject(myObject);
//Then:
//-------
// This would fail because you cannot test for the extension method
//mockMyImplementation.Verify(m => m.MyMethod());
// This is success because you test for the mocked implementation interface
mockMyImplementation.Verify(m => m.MyMethod(myObject));
}
}
I know this question hasn't been active for about a year but Microsoft released a framework to handle exactly this called Moles.
Here are a few tutorials as well:
DimeCasts.net
Nikolai Tillman's Tutorial
I created a wrapper class for the extension methods that I needed to mock.
public static class MyExtensions
{
public static string MyExtension<T>(this T obj)
{
return "Hello World!";
}
}
public interface IExtensionMethodsWrapper
{
string MyExtension<T>(T myObj);
}
public class ExtensionMethodsWrapper : IExtensionMethodsWrapper
{
public string MyExtension<T>(T myObj)
{
return myObj.MyExtension();
}
}
Then you can mock the wrapper methods in your tests and code with your IOC container.
For extension methods I normally use the following approach:
public static class MyExtensions
{
public static Func<int,int, int> _doSumm = (x, y) => x + y;
public static int Summ(this int x, int y)
{
return _doSumm(x, y);
}
}
It allows to inject _doSumm fairly easy.
Best thing you can do is to provide a custom implementation for the type that has the extension method, e.g:
[Fact]
public class Tests
{
public void ShouldRunOk()
{
var service = new MyService(new FakeWebHostEnvironment());
// Service.DoStuff() internally calls the SomeExtensionFunction() on IWebHostEnvironment
// Here it works just fine as we provide a custom implementation of that interface
service.DoStuff().Should().NotBeNull();
}
}
public class FakeWebHostEnvironment : IWebHostEnvironment
{
/* IWebHostEnvironment implementation */
public bool SomeExtensionFunction()
{
return false;
}
}

Categories