我有一个 MVC4 网络应用程序,我现在正在对其进行单元测试。它为数据库部分使用 Entity Framework 。我正在使用 NSubstitute 来模拟数据库。这段代码基本上是从另一个运行良好的站点复制和粘贴的,所以我希望我只是遗漏了一些非常简单的东西。
提前致谢!
SQL 中的应用程序表:
AppID | ApplicationName
----------------------------
1 | MyCoolApplication
2 | MyOtherApplication
实体创建了应用程序类:
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 并卸载/重新安装,但仍然一无所获。
再次感谢您!
最佳答案
NSubstitute 不能模拟非虚拟成员。 (有 quite a few caveats to substituting for classes 。)
MyCoolApplicationsEntities.Applications
需要是虚拟的,.Returns()
才能工作。
关于c# - MVC4 单元测试 NSubstitute 找不到要返回的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27301977/