我正在使用带有最小起订量的 nuit 来测试我的 Controller 。
我使用具有接口(interface)的 session 类,并且使用 ninject 将 HttpContext 注入(inject)到构造函数中。 像这样
public class SessionService : ISession
{
public HttpContext Context { get; set; }
public SessionService(HttpContext context)
{
this.Context = context;
}
}
public interface ISession
{
HttpContext Context { get; set; }
}
public HomeController(ISession session)
{
_session = session;
}
我认为为了测试 Controller ,我首先模拟了 HttpContext,然后将该对象传递给模拟的 ISession 的构造函数。 到目前为止我有这个
[Test]
public void index_returns_view()
{
//arrange
var mockHttpContext = new Mock<HttpContext>();
var mockContext = new Mock<ISession>(mockHttpContext);
var c = new HomeController(mockContext.Object);
//act
var v = c.Index() as ViewResult;
//assert
Assert.AreEqual(v.ViewName, "Index", "Index View name incorrect");
}
构建但 nunit 在测试运行时返回以下错误
System.NotSupportedException :要模拟的类型必须是接口(interface)或抽象类或非密封类。
感谢所有帮助。
最佳答案
让您的 session 在构造函数中采用 HttpContextBase 并将其用作属性的类型。 您仍然应该能够在生产代码中的 session 中传递具体的 HttpContext。
public class SessionService : ISession
{
public HttpContextBase Context { get; set; }
public SessionService(HttpContextBase context)
{
this.Context = context;
}
}
然后通过将“mockHttpContext.Object”传递给 session 构造函数并模拟 HttpContextBase 来修复单元测试。
[Test]
public void index_returns_view()
{
//arrange
var mockHttpContext = new Mock<HttpContextBase>();
var mockContext = new Mock<ISession>(mockHttpContext.Object);
var c = new HomeController(mockContext.Object);
//act
var v = c.Index() as ViewResult;
//assert
Assert.AreEqual(v.ViewName, "Index", "Index View name incorrect");
}
关于c# - 将模拟参数传递给模拟接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8343301/