我需要测试并模拟控制器内部找到的方法.是否可以在控制器内部模拟一个方法,而无需使用NSubstitute框架实现接口.
这是我的Controller页面代码.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Syncfusion.Cluster.Manager
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
int result = Sum(7, 7);
return View();
}
public virtual int Sum(int a, int b)
{
return 0;
}
}
}
这是我的测试代码,在我调试它时,控制器内总是发现’0′.控制器内的Sum函数不会被覆盖.
using System;
using NUnit.Framework;
using Manager;
using Base.Classes.Models.SecurityBase;
using NSubstitute;
using BaseProject;
using System.Web.Mvc;
using System.Web.Http;
namespace NSubstituteControllerSupport
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var controller = new HomeController();
//var actionMethod = Substitute.For<HomeController>();
//actionMethod.Sum(Arg.Any<int>(), Arg.Any<int>()).Returns(14);
//var actual = controller.Index();
var validation = Substitute.ForPartsOf<HomeController>();
validation.When(x => x.Sum(a: Arg.Is(7), b: Arg.Is(7))).DoNotCallBase();
validation.Sum(7, 7).Returns(14);
var actuals = controller.Index();
}
}
}
这是我的类库项目的测试代码,我成功地模拟了一个没有实现接口的方法.
[Test]
public void TestMethod2()
{
#region variableDecleration
var adHost = new ActiveDirectoryHost();
adHost.AdPath = @"C:\User\Security\1.0.0.0";
adHost.CnNames = "CN=USERS";
adHost.DomainName = "USER.COM";
adHost.DomainPath = "DC=USER,DC=COM";
adHost.Fqn = "HOSTNAME.USER.COM.USER.COM";
adHost.HostName = "hostname.user.com";
adHost.OuPath = "OU=NewSecur";
adHost.SuperGroupName = "usergroup_1";
adHost.IpAddress = "xxx.xx.xx.x";
var adUserName = "username";
var adPassword = "password";
#endregion variableDecleration
var validation = Substitute.ForPartsOf<ValidationHandler>();
validation.GetUserGroupList(userName: Arg.Is(adUserName ), recursive: Arg.Is(false), adHost: Arg.Is(adHost), adUsername: Arg.Is(adUserName), adPassword: Arg.Is(adPassword)).Returns("usergroup_1,usergroup_2");
var isUserInGroup = validation.IsUserMemberOfGroup(adUsername, "usergroup_1", adHost, adUserName, adPassword);
Assert.That(isUserInGroup, Is.EqualTo(true));
}
最佳答案 以下应该做的工作:
// arrange
var controller = Substitute.For<HomeController>();
controller.Sum(7, 7).Returns(14);
// act
var actual = controller.Index();
// assert
...