提前致谢!
SQL中的应用程序表:
AppID | ApplicationName
----------------------------
1 | MyCoolApplication
2 | MyOtherApplication
创建了Application类的实体:
public class Application
{
public int AppID { get; set; }
public string ApplicationName { get; set; }
}
单元测试中的模拟部分如下:
var mockDb = Substitute.For<MyCoolApplicationsEntities>();
var applications = new List<Application>
{
new Application {AppID = 1, ApplicationName = "MyCoolApplication"},
new Application {AppID = 2, ApplicationName = "MyOtherApplication"},
};
var mockApplicationSet = Substitute.For<IDbSet<Application>, DbSet<Application>>();
mockApplicationSet.Provider.Returns(applications.AsQueryable().Provider);
mockApplicationSet.Expression.Returns(applications.AsQueryable().Expression);
mockApplicationSet.ElementType.Returns(applications.AsQueryable().ElementType);
mockApplicationSet.GetEnumerator().Returns(applications.AsQueryable().GetEnumerator());
mockApplicationSet.When(q => q.Add(Arg.Any<Application>()))
.Do(q => applications.Add(q.Arg<Application>()));
mockApplicationSet.When(q => q.Remove(Arg.Any<Application>()))
.Do(q => applications.Remove(q.Arg<Application>()));
mockDb.Applications.Returns(mockApplicationSet); //This is the line creating the error
完整的错误信息是:
Test method MyProjectName.Controllers.MyControllerTest.TestOfSectionImTesting threw exception: 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);
但是在我的环境中这并不起作用,因为应用程序不是一个方法。正如我所说的,在我的另一个站点中这个方法很好用,所以肯定是我漏掉了一些基本的东西。我在网上找到的信息对我的情况没有帮助。我已经更新了最新版本的 NSubstitute,并进行了卸载/重新安装,但仍然没有任何结果。
再次感谢您的帮助!
context.Applications.Returns(mockApplications)
现在应该可以正常工作了? - David Tchepak