I used to use Moq and AutoMoqer in unit tests, but my team has decided to change to NSubstitute. We use DI heavily, so I'd like to be able to ask for a target to test and have that target automatically given all mocked objects to its constructor, or in other words a DI container that passes in mocks. I also want to modify those mocked objects as necessary.
Example using Moq/AutoMoq/MSTest
[TestMethod]
public void ReturnSomeMethod_WithDependenciesInjectedAndD1Configured_ReturnsConfiguredValue()
{
const int expected = 3;
var diContainer = new AutoMoq.AutoMoqer();
var mockedObj = diContainer.GetMock<IDependency1>();
mockedObj
.Setup(mock => mock.SomeMethod())
.Returns(expected);
var target = diContainer.Resolve<MyClass>();
int actual = target.ReturnSomeMethod();
Assert.AreEqual(actual, expected);
}
public interface IDependency1
{
int SomeMethod();
}
public interface IDependency2
{
int NotUsedInOurExample();
}
public class MyClass
{
private readonly IDependency1 _d1;
private readonly IDependency2 _d2;
//please imagine this has a bunch of dependencies, not just two
public MyClass(IDependency1 d1, IDependency2 d2)
{
_d1 = d1;
_d2 = d2;
}
public int ReturnSomeMethod()
{
return _d1.SomeMethod();
}
}
Since my question was poorly worded and I have researched a bit more, I have found a way to get this working using NSubstitute/AutofacContrib.NSubstitute/XUnit:
[Fact]
public void ReturnSomeMethod_WithDependenciesInjectedAndD1Configured_ReturnsConfiguredValue()
{
const int expected = 3;
var autoSubstitute = new AutoSubstitute();
autoSubstitute.Resolve<IDependency1>().SomeMethod().Returns(expected);
var target = autoSubstitute.Resolve<MyClass>();
int actual = target.ReturnSomeMethod();
Assert.Equal(actual, expected);
}
public interface IDependency1
{
int SomeMethod();
}
public interface IDependency2
{
int NotUsedInOurExample();
}
public class MyClass
{
private readonly IDependency1 _d1;
private readonly IDependency2 _d2;
//please imagine this has a bunch of dependencies, not just two
public MyClass(IDependency1 d1, IDependency2 d2)
{
_d1 = d1;
_d2 = d2;
}
public int ReturnSomeMethod()
{
return _d1.SomeMethod();
}
}
I still have my original question. How can I do this using AutoFixture.AutoNSubstitute as a DI container?