我已配置MockingKernel
以模拟依赖项:
[TestFixture]
public class TestsFixture
{
private NSubstituteMockingKernel IoCKernel;
public UsersTests()
{
this.IoCKernel = new NSubstituteMockingKernel();
}
[SetUp]
public void SetUp()
{
this.IoCKernel.Reset();
}
[Test]
public void AddUserTest()
{
var mock = this.IoCKernel.Bind<Core.Configuration.ICoreConfiguration>().ToMock();
mock.Setup( <<<<<<< How to substitute methods of this mocked objects??????
m =>
m.UserIdentities
.Returns(new List<UserIdentity>() {new UserIdentity("user1")}
);
Core.Kernel coreKernel = this.IoCKernel.Get<Core.Kernel>();
}
}
根据this documentation,我需要调用Setup
方法来替换方法。然而,Setup
方法不可用。
有什么想法吗?
我看过文档。我要问一些例子。不过,我认为文档有点差。
修改
我试过这个:
public void Test() {
Core.Configuration.UserIdentity userConfiguration = Core.Configuration.UserIdentity.Create("u1", "p1");
IEnumerable<Core.Configuration.UserIdentity> configurationUsers = new List<Core.Configuration.UserIdentity>() { userConfiguration };
this.IoCKernel.Get<Core.Configuration.ICoreConfiguration>().UserIdentities.Returns(configurationUsers);
//Testing
Core.Kernel kernel = this.IoCKernel.Get<Core.Kernel>();
kernel.Received(1).AddUser(Arg.Any<Core.Identity.UserIdentity>());
}
尽管如此,我现在在最后一行收到此NSubstitute.Exceptions.NotASubstituteException
异常消息:
NSRestitute扩展方法,如.Received()只能在使用Substitute.For()和相关方法创建的对象上调用。
正如你所看到的,我试图测试AddUser
方法至少被调用一次。必须根据我的AddUser
实施调用Core.Kernel
。
答案 0 :(得分:3)
这是一个有效的例子:
using Ninject;
using Ninject.MockingKernel.NSubstitute;
using NSubstitute;
using NUnit.Framework;
namespace ClassLibrary1
{
[TestFixture]
public class MyTests
{
[Test]
public void Test1()
{
using (var kernel = new NSubstituteMockingKernel())
{
var substitute = kernel.Get<IDummyService>();
substitute.ReturnInt().Returns(1);
var instance = kernel.Get<DummyClass>();
Assert.AreEqual(1, instance.Calc());
substitute.Received(1).ReturnInt();
}
}
public interface IDummyService
{
int ReturnInt();
}
public class DummyClass
{
private IDummyService _dummyService;
public DummyClass(IDummyService dummyService)
{
_dummyService = dummyService;
}
public int Calc()
{
return _dummyService.ReturnInt();
}
}
}
}
使用以下包:
PM> Get-Package
Id Versions ProjectName
-- -------- -----------
Ninject {3.2.2.0} ClassLibrary1
Ninject.MockingKernel {3.2.2.0} ClassLibrary1
Ninject.MockingKernel.NSubstitute {3.2.2.0} ClassLibrary1
NSubstitute {1.10.0.0} ClassLibrary1
NUnit {3.6.0} ClassLibrary1