当Controller类中的Action方法调用它时,我需要一个基类中存在的模拟方法。
以下是我的Controller类,操作方法Index()
调用基本方法GetNameNodeStatus()
。现在,当动作方法GetNameNodeStatus()
使用Nsubstitute模拟框架调用它时,如何模拟基类中存在的Index
。
using Cluster.Manager.Helper;
using Cluster.Manager.Messages;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace Cluster.Manager
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
ClusterMonitoring monitoring = new ClusterMonitoring();
string getStatus = monitoring.GetNameNodeStatus("", new Credential());
return View();
}
}
}
这是我的基类Clustermonitoring
namespace Cluster.Manager.Helper
{
public class ClusterMonitoring
{
public virtual string GetNameNodeStatus(string hostName, Credential credential)
{
return "Method Not Implemented";
}
}
}
这是我的测试课
namespace NSubstituteControllerSupport
{
[TestFixture]
public class UnitTest1
{
[Test]
public void ValidateNameNodeStatus()
{
var validation = Substitute.ForPartsOf<ClusterMonitoring>();
validation.When(actionMethod => actionMethod.GetNameNodeStatus(Arg.Any<string>(), Arg.Any<Credential>())).DoNotCallBase();
validation.GetNameNodeStatus("ipaddress", new Credential()).Returns("active");
var controllers = Substitute.For<HomeController>();
controllers.Index();
}
}
}
答案 0 :(得分:1)
ClusterMonitoring
。
ClusterMonitoring monitoring = new ClusterMonitoring();
这意味着无法替代它。您需要将ClusterMonitoring
作为依赖项注入控制器,以便能够在测试时将其替换掉。
接口后面的第一个抽象ClusterMonitoring
public interface IClusterMonitoring {
string GetNameNodeStatus(string hostName, Credential credential);
}
并让它继承该接口
public class ClusterMonitoring : IClusterMonitoring {
public virtual string GetNameNodeStatus(string hostName, Credential credential) { ... }
}
更新控制器以通过构造函数
获取依赖关系public class HomeController : Controller {
private readonly IClusterMonitoring monitoring;
public HomeController(IClusterMonitoring monitoring) {
this.monitoring = monitoring;
}
// GET: Home
public ActionResult Index() {
var status = monitoring.GetNameNodeStatus("", new Credential());
return View(status);
}
}
现在更新测试以将依赖注入到测试中的控制器
[TestFixture]
public class UnitTest1 {
[Test]
public void ValidateNameNodeStatus() {
//Arrange
var expected = "active";
var validation = Substitute.For<IClusterMonitoring>();
validation.GetNameNodeStatus("", new Credential()).Returns(expected);
var controller = new HomeController(validation);
//Act
var actual = controllers.Index() as ViewResult;
//Assert
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual.Model);
}
}