EzDev.org

NSubstitute

NSubstitute - A friendly substitute for .NET mocking libraries. NSubstitute: A friendly substitute for .NET mocking libraries


How to use NSubstitute to mock a lazy class

//Assert
Lazy<INotificationService> notificationService = Substitute.For<Lazy<INotificationService>>();
Service target = new Service(repository, notificationService);

//Act
target.SendNotify("Message");

//Arrange
notificationService.Received().Value.sendNotification(null, null, null, null);

The above code throws an exception.

The lazily-initialized type does not have a public, parameterless constructor

I am using C# 4.0 and NSubstitute 1.2.1


Source: (StackOverflow)

Is it recommended to mock concrete class

Most of the examples given in mocking framework website is to mock Interface. Let say NSubstitute that I'm currently using, all their mocking examples is to mock interface.

But in reality, I saw some developer mock concrete class instead. Is it recommended to mock concrete class?


Source: (StackOverflow)

NSubstitute: Checking received methods with array arguments

I want to verify that a method on my NSubstitute mock is called with a particular array argument.

Say the interface, IProcessor, has a method void ProcessSomething(Foo[] something]). Say my class under test is named Commander. I set up my test like this:

//prepare
var processor = Substitute.For<IProcessor>;
var commander = new Commander(processor);
var foo1 = new Foo("alpha");
var foo2 = new Foo("bravo");
var foos = new [] {foo1, foo2};

//act
commander.DoSomething(foo1, foo2);

//verify
processor.Received().ProcessSomething(foos);  // FAILS

The Received() call fails with:

NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching:
    ProcessSomething(Foo[])
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
    ProcessSomething(*Foo[]*)

So this looks like ProcessSomething was called with some array other than foos, right?

Well, if I instead test this like, where I capture the argument value using Arg.Do(), it succeeds:

//prepare
//... as before
var actualFoos = null;

processor.ProcessSomething(Arg.Do<Foo[]>(x => actualFoos = x));

//act
commander.DoSomething(foo1, foo2);

//verify
Assert.That(actualFoos, Is.EqualTo(foos));   // SUCCEEDS

So capturing the argument and comparing it for equality (with NUnit in this example) works, but verifying the received call fails.

Is this a bug in NSubstitute, or am I using it wrong?


Source: (StackOverflow)

How can I create and populate my mock classes with Autofixture?

Currently I'm using EF6 to implement my repositories inside a UnitOfWork. I also have created an In-Memory mock implementations (MockUnitOfWork & MockRepository) so that I can use them in unit tests, however I now have to deal with the tedious setup of the objects.

Isn't this what Autofixture is designed to do? How would I go about getting a MockUnitOfWork that I can use in my tests that contains Foo and Barr repositories that are populated? I'm using NSubstitute for my mocking framework.

IUnitOfWork

public interface IUnitOfWork
{
    void Save();
    void Commit();
    void Rollback();

    IRepository<Foo> FooRepository { get; }
    IRepository<Bar> BarRepository { get; }
}

IRepository

public interface IRepository<TEntity> where TEntity : class
{
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string         includeProperties = "");

    IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null);
    TEntity GetByID(object id);

    void Insert(TEntity entity);
    void Delete(object id);
    void Delete(TEntity entityToDelete);
    void Update(TEntity entityToUpdate);
}

Source: (StackOverflow)

NSubstitute DbSet / IQueryable

So EntityFramework 6 is a lot better testable then previous versions. And there are some nice examples on the internet for frameworks like Moq, but the case is, I prefer using NSubstitute. I've got the "non-query" examples translated to work with the use of NSubstitute, but I can't get my head around the 'query-test'.

How does Moq's items.As<IQueryable<T>>().Setup(m => m.Provider).Returns(data.Provider); translate to NSubstitute? I thought something like ((IQueryable<T>) items).Provider.Returns(data.Provider); but that didn't work. I've also tried items.AsQueryable().Provider.Returns(data.Provider); but that didn't work either.

The exeption I'm getting is:

"System.NotImplementedException : The member 'IQueryable.Provider' has not been implemented on type 'DbSet1Proxy' which inherits from 'DbSet1'. Test doubles for 'DbSet`1' must provide implementations of methods and properties that are used."

So let me quote the code example from the link above. This code sample uses Moq to mock the DbContext and DbSet.

public void GetAllBlogs_orders_by_name()
{
  // Arrange
  var data = new List<Blog>
  {
     new Blog { Name = "BBB" },
     new Blog { Name = "ZZZ" },
     new Blog { Name = "AAA" },
  }.AsQueryable();

  var mockSet = new Mock<DbSet<Blog>>();
  mockSet.As<IQueryable<Blog>>().Setup(m => m.Provider).Returns(data.Provider);
  mockSet.As<IQueryable<Blog>>().Setup(m => m.Expression).Returns(data.Expression);
  mockSet.As<IQueryable<Blog>>().Setup(m => m.ElementType).Returns(data.ElementType);
  mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

  var mockContext = new Mock<BloggingContext>();
  mockContext.Setup(c => c.Blogs).Returns(mockSet.Object);

  // ...
}

And this is how far I come with NSubstitute

public void GetAllBlogs_orders_by_name()
{
  // Arrange
  var data = new List<Blog>
  {
     new Blog { Name = "BBB" },
     new Blog { Name = "ZZZ" },
     new Blog { Name = "AAA" },
  }.AsQueryable();

  var mockSet = Substitute.For<DbSet<Blog>>();
  // it's the next four lines I don't get to work
  ((IQueryable<Blog>) mockSet).Provider.Returns(data.Provider);
  ((IQueryable<Blog>) mockSet).Expression.Returns(data.Expression);
  ((IQueryable<Blog>) mockSet).ElementType.Returns(data.ElementType);
  ((IQueryable<Blog>) mockSet).GetEnumerator().Returns(data.GetEnumerator());

  var mockContext = Substitute.For<BloggingContext>();
  mockContext.Blogs.Returns(mockSet);

  // ...
}

So the question is; How does one Substitute a property of IQueryable (like Provider)?


Source: (StackOverflow)

NSubstitute - TestFixture 1 causes AmbiguousArgumentsException in TestFixture 2

I am writing C# unit tests using NUnit and NSubstitute. I am testing a class which will attempt to retrieve objects from a config provider implementing the following interface:

public interface IConfigProvider<T> {
    T GetConfig(int id);
    T GetConfig(string id);
}

The class being tested only uses the int version of GetConfig so in the SetUpFixture I do the following to set up a mocked config provider that will always return the same dummy object:

IConfigProvider<ConfigType> configProvider = Substitute.For<IConfigProvider<ConfigType>>();
configProvider.GetConfig(Arg.Any<int>()).Returns<ConfigType>(new ConfigType(/* args */);

This runs absolutely fine if that TestFixture is the only one being run. However, in a different TestFixture in the same assembly, I check for received calls like this:

connection.Received(1).SetCallbacks(Arg.Any<Action<Message>>(), Arg.Any<Action<long>>(), Arg.Any<Action<long, Exception>>());

If these Received tests run before the config provider tests, then the config tests fail in the SetUpFixture with an AmbiguousArgumentsException:

Here.Be.Namespace.ProfileManagerTests+Setup (TestFixtureSetUp):
SetUp : NSubstitute.Exceptions.AmbiguousArgumentsException : Cannot determine argument specifications to use.
Please use specifications for all arguments of the same type.
at NSubstitute.Core.Arguments.NonParamsArgumentSpecificationFactory.Create(Object argument, IParameterInfo parameterInfo, ISuppliedArgumentSpecifications suppliedArgumentSpecifications)
at System.Linq.Enumerable.<SelectIterator>d__7`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at NSubstitute.Core.Arguments.MixedArgumentSpecificationsFactory.Create(IList`1 argumentSpecs, Object[] arguments, IParameterInfo[] parameterInfos)
at NSubstitute.Core.Arguments.ArgumentSpecificationsFactory.Create(IList`1 argumentSpecs, Object[] arguments, IParameterInfo[] parameterInfos, MatchArgs matchArgs)
at NSubstitute.Core.CallSpecificationFactory.CreateFrom(ICall call, MatchArgs matchArgs)
at NSubstitute.Routing.Handlers.RecordCallSpecificationHandler.Handle(ICall call)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at NSubstitute.Routing.Route.Handle(ICall call)
at NSubstitute.Proxies.CastleDynamicProxy.CastleForwardingInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IConfigProvider`1Proxy.GetConfig(Int32 id)
at Here.Be.Namespace.ProfileManagerTests.Setup.DoSetup()

What's really confusing me is that I can observe this effect even between test runs - if I use the NUnit GUI to run the Received tests alone, and then run the config tests alone, the config tests will fail. If I then immediately run the config tests again, they will pass.

Things I've tried:

  • Adding configProvider.GetConfig(Arg.Any<string>()).Returns... as well, in case the overloading was the problem.
  • I've read the NSubstitute docs on argument matching, but I can't find a solution there. If it is a case of having to supply argument matchers for both the int and string versions of the method, I can't work out how to do that.

As it happens, the tests I'm using will only ever call the GetConfig method with values of 0 or 1, so I can just provide Returns specifications for those two values and not use matching at all, but I want to understand how to fix this more generally.


Source: (StackOverflow)

Check calls Received() for async method

When I run the following code:

[Test]
public async Task Can_Test_Update()
{
    var response = await _controller.UpdateAsync(Guid.NewGuid());
    response.Valid.Should().BeTrue();

    _commands.Received().UpdateAsync(
        Arg.Is<Something>(
            l => l.Status == Status.Updated)); 
}

If I add "await" preceding the "_commands.Received().UpdateAsync", it throws a null reference exception. How can I stop this happening, or is await not necessary?


Source: (StackOverflow)

NSubstitute - async - call is not awaited

I am trying to verify that an asynchronous method was called with the correct parameters. However, I get the warning:

"Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call". This warning appears on the line of code underneath the //Assert comment (below).

My test using NSubstitute is as follows:

[Test]
public async Task SimpleTests()
{
  //Arrange
  var request = CreateUpdateItemRequest();

  databaseHelperSub.ExecuteProcAsync(Arg.Any<DatabaseParams>()).Returns(Task.FromResult((object)null));

  //Act      
  await underTest.ExecuteAsync(request);

  //Assert
  databaseHelperSub.Received().ExecuteProcAsync(Arg.Is<DatabaseParams>(
    p => p.StoredProcName == StoredProcedureName
         && p.Parameters[0].ParameterName == "Param1"
         && p.Parameters[0].Value.ToString() == "Value1"
         && p.Parameters[1].ParameterName == "Param2"
         && p.Parameters[1].Value.ToString() == "Value2"));
}

The unit under test method underTest.ExecuteAsync(request) calls ExecuteProcedureAsync and performs the await:

var ds = await DatabaseHelper.ExecuteProcAsync(dbParams);

Due to the fact that with NSubstitute, the Received() is required after the execution of the unit under test. Whereas in RhinoMocks, you can expect for a call to occur before the unit under test is executed. RhinoMocks can return the Task.FromResult() whereas NSubstitute cannot.

The RhinoMocks equivalent that works is this:

[Test]
        public async Task SimpleTest()
        {
            // Arrange
            var request = new UpdateItemRequest();

            databaseHelperMock.Expect(m => m.ExecuteProcAsync(Arg<DatabaseParams>.Matches(
                p =>   p.StoredProcName == StoredProcedureName
                    && p.Parameters[0].ParameterName == "Param1"
                    && p.Parameters[0].Value.ToString() == "Value1"
                    && p.Parameters[1].ParameterName == "Param2"
                    && p.Parameters[1].Value.ToString() == "Value2
                ))).Return(Task.FromResult<object>(null));

            // Act
            await underTest.ExecuteAsync(request);

        }

I have seen that there is a workaround where you can add an extension method to remove the issue:

  public static class TestHelper
  {
    public static void IgnoreAwait(this Task task)
    {

    }
  }

Meaning my test line for NSubstitute can be executed as follows and the warning goes away:

databaseHelperSub.Received().ExecuteProcAsync(Arg.Is<DatabaseParams>(
        p => p.StoredProcName == StoredProcedureName
             && p.Parameters[0].ParameterName == "Param1"
             && p.Parameters[0].Value.ToString() == "Value1"
             && p.Parameters[1].ParameterName == "Param2"
             && p.Parameters[1].Value.ToString() == "Value2")).IgnoreAwait();
    }

However, I assumed there must be a better solution out there for this?


Source: (StackOverflow)

How stable is NSubstitute?

My company is looking to standardize on an Isolation Framework. I was looking at MS Stubs (cause Moles seemed cool and I thought I would keep it in the same framework). However, Stubs is not quite ready for prime time yet (it is still a bit buggy in normal functionality).

So now I am looking at what else is out there. I have looked at Moq and Rhino mocks. While doing that, I came across the fabulous comparisons done by Richard Banks. In that he shows NSubstitute. I really like what I see there.

However, after having been burned a bit by MS Stubs, I don't want to bet on an alpha/non-production ready Isolation Framework.

So, is NSubstitute ready for prime time? Or is it still a bit buggy?


Source: (StackOverflow)

What are NSubstitute limitations, specially vs MOQ?

I'm about to take a decision about the mocking library for my next project.

and because I'm new to those libraries I made a quick search

I found that MOQ is much popular than NSubstitute and I expect more help from the community specially here at SO

But I liked NSubstitute syntax more, also it has a nice docs.

So my question is "Is there any thing that I can achieve using MOQ I cant achieve using NSubstitute?"


Source: (StackOverflow)

Example of how to use AutoFixture with NSubstitute

I use NSubstitute a lot. And I love it.

I am just looking into AutoFixture. It seems great!

I have seen AutoFixture for NSubstitute and seen a few examples in Moq on how to use this feature.

But I can't seem to translate it into NSubstitute.

I tried this:

var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());  
var addDest = Substitute.For<IPerson>();

Using:

public interface IPersonEntity
{    
   int ID { get; set; }
   string FirstName { get; set;}
   string LastName { get; set;}
   DateTime DateOfBirth { get; set; }
   char Gender { get; set; }    
}

And I get an object, but none of the properties are populated (kind of the point of AutoFixture).

I also tried:

var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
var result = fixture.Create<IPersonEntity>();

That also gave me an object with no populated properties. (Note if I do the above with a PersonEntity class, then the properties are all populated.)

I am sure that there is a way to make this work, but I can't seem to find it.

So, given my IPersonEntity interface above, does anyone know how to use AutoFixture and NSubstitute to give me a populated IPersonEntity object?


Source: (StackOverflow)

Returning the result of a method that returns another substitute throws an exception in NSubstitute

I have run into a weird issue while using NSubstitute a few times and although I know how to work around it I've never been able to explain it.

I've crafted what appears to be the minimum required test to prove the problem and it appears to be something to do with using a method to create a substituted return value.

public interface IMyObject
{
    int Value { get; }
}

public interface IMyInterface
{
    IMyObject MyProperty { get; }
}

[TestMethod]
public void NSubstitute_ReturnsFromMethod_Test()
{
    var sub = Substitute.For<IMyInterface>();

    sub.MyProperty.Returns(MyMethod());
}

private IMyObject MyMethod()
{
    var ob = Substitute.For<IMyObject>();
    ob.Value.Returns(1);
    return ob;
}

When I run the above test I get the following exception:

Test method globalroam.Model.NEM.Test.ViewModel.DelayedAction_Test.NSubstitute_ReturnsFromMethod_Test threw exception: 
NSubstitute.Exceptions.CouldNotSetReturnException: Could not find a call to return from.
Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)).
If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member.
Return values cannot be configured for non-virtual/non-abstract members.

However, if I change the test method to return this:

sub.MyProperty.Returns((a) => MyMethod());

or this:

var result = MyMethod();
sub.MyProperty.Returns(result);

It works.

I'm just wondering if anyone can explain why this happens?


Source: (StackOverflow)

Can I get NSubstitute to auto mock my concrete classes?

I have an interface which I am mocking with 'NSubstitute' which contains properties that return concreate classes, that is the return value is not an interface. e.g

public interface ISomething
{
    SomeObj First { get; }
    SomeObj Second { get; }
}

The 'SomeObj' concrete class has a default constructor but 'NSubstitute' always returns 'null' for these properties. The class itself is not under my control so I cannot simply make it derive from an interface.

Can 'NSubstitute' mock these type of properties? Or is there a way to override the behaviour? Otherwise I have to manually initialise the mock before the test and that can be a lot of code (even if its reused through a common method).

Perhaps there is a simpler solution that I have over-looked?


Source: (StackOverflow)

How to substitute Object.ToString using NSubstitute?

When I try to use NSubstitute 1.7.1.0 to define behaviour of Object.ToString (which is a virtual method), NSubstitute is throwing an exception.

To reproduce:

[Test]
public static void ToString_CanBeSubstituted()
{
    var o = Substitute.For<object>();
    o.ToString().Returns("Hello world");

    Assert.AreEqual("Hello world", o.ToString());
}

The failure:

NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException : Could not find a call to return from.

Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)),
and that you are not configuring other substitutes within Returns() (for example, avoid this: mySub.SomeMethod().Returns(ConfigOtherSub())).

If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member.
Return values cannot be configured for non-virtual/non-abstract members.

Correct use:
    mySub.SomeMethod().Returns(returnValue);

Potentially problematic use:
    mySub.SomeMethod().Returns(ConfigOtherSub());
Instead try:
    var returnValue = ConfigOtherSub();
    mySub.SomeMethod().Returns(returnValue);

Is there a way to make the above test pass?

Is the exception thrown from my naive test a bug or is it "By Design"?


Source: (StackOverflow)

Unable to cast object of type 'Castle.Proxies.XProxy' to type 'X' in WPF Designer

I've recently discovered the very useful design time attributes from Blend for a WPF component, which (among other things) allows you to set a DataContext only at design time. Awesome!

Combined with the DesignInstance attribute, you can set a type to be automatically created and bound to during design time, allowing you to use the Visual Studio Designer with some context as to what your WPF component will actually look like at run time. Its really nice, and I wish it hadn't taken me so long to discover.

Obviously, because I'm here and not living it up in programmer heaven I've encountered a problem while using these design time attributes.

I've created a design time wrapper around one my ViewModels, which has a parameterless constructor (so it can be created by the designer). Inside its constructor, it uses NSubstitute to mock out all of the dependencies injected into the ViewModel it inherits from.

Using this design time class in the designer results in an error much like the following:

Unable to cast object of type 'Castle.Proxies.XProxy' to type 'X'.

(With the X being replaced with one of my injected dependencies).

You can use the following minimal set of code to reproduce the problem.

Create a WPF Application in VS2013 targeting .NET Framework 4.5.1 (it might happen in previous versions too, I don't know) with the following files in it.

View.xaml

<Page 
    x:Class="DesignTimeNSubstituteIssue.Views.View"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:DesignTimeNSubstituteIssue_Views_DesignTime="clr-namespace:DesignTimeNSubstituteIssue.Views.DesignTime"
    mc:Ignorable="d" 
    d:DataContext="{d:DesignInstance Type=DesignTimeNSubstituteIssue_Views_DesignTime:DesignTimeViewModel, IsDesignTimeCreatable=True}">
    <Grid>
        <TextBlock Text="{Binding Message, FallbackValue=Design_Time_Message_Failed_Using_Fallback}"/>
    </Grid>
</Page>

ViewModel.cs

using DesignTimeNSubstituteIssue.Services;

namespace DesignTimeNSubstituteIssue.ViewModels
{
    public class ViewModel
    {
        public ViewModel(XDependency dependency)
        {
            _Dependency = dependency;
        }

        private readonly XDependency _Dependency;
        public string Message { get; protected set; }
    }
}

DesignTimeViewModel.cs

using DesignTimeNSubstituteIssue.Services;
using DesignTimeNSubstituteIssue.ViewModels;
using NSubstitute;

namespace DesignTimeNSubstituteIssue.Views.DesignTime
{
    public class DesignTimeViewModel : ViewModel
    {
        public DesignTimeViewModel()
            : base(Substitute.For<XDependency>())
        {
            Message = "This is a Design Time message.";
        }
    }
}

XDependency.cs

namespace DesignTimeNSubstituteIssue.Services
{
    public interface XDependency
    {

    }
}

Compile, close and reopen the solution and open View.xaml in the designer. It will work just fine. Then, close the designer, rebuild solution and open View.xaml in the designer again, and you will get the following error:

Unable to cast object of type 'Castle.Proxies.XDependencyProxy_1' to type 'DesignTimeNSubstituteIssue.Services.XDependency'.

When this error occurs, the designer stops using the specified DesignTimeViewModel, and falls back to having no DataContext at all.

The only way to fix this is to close and reopen the solution.

I suspect I know what is happening, but I don't know why its happening or how to fix it.

I think that on the first compile the designer is obtaining a reference to the assembly and caching it. When the second compile occurs, the assembly is rebuilt and is mostly the same, but the NSubstitute proxy is regenerated with a new suffix (like Castle.Proxies.XDependencyProxy_2 or something) which wasn't in the first assembly, so the designer doesn't know that that proxy actually implements the XDependency interface. This is purely conjecture on my part.

I can create a workaround by not using NSubstitute, and manually mocking the dependencies, but I'm interested to see if someone can shed some light on the subject.


Source: (StackOverflow)