I need to test and mock a method found inside a controller. Is is possible to mock a method inside the controller, without implementing an interface using NSubstitute framework.
Here is my Controller page code.
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;
}
}
}
Here is my Test code and the Sum always found to be '0' inside the controller while I debugged it. The Sum function inside the controller is not get overrides.
using System;
using NUnit.Framework;
using Syncfusion.Cluster.Manager;
using Syncfusion.Cluster.Manager.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();
}
}
Here is my testing code for the Class Library project I successfully mocked a method without implementing an interface.
[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.SYNCFUSION.COM.SYNCFUSION.COM";
adHost.HostName = "hostname.syncfusion.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));
}
Aucun commentaire:
Enregistrer un commentaire