c# - 将模拟参数传递给模拟接口(interface)

标签 c# asp.net-mvc nunit moq

我正在使用带有最小起订量的 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/

相关文章:

c# - Windows 应用商店应用程序中的文字描边

c# - 微软的 botframework 是免费的吗?

c# - 添加/启用装饰器后如何刷新/更新wpf窗口

asp.net-mvc - EditorFor ListView 错误

c# - 从 ASP.NET MVC 中的布局调用操作方法

asp.net-mvc - MVC4 捆绑 : Minification failed because of css3-feature?

c# - Nunit:检查两个对象是否相同

c# - 是否可以在匿名函数中设置断点?

unit-testing - 使用日期时间的 NUnit 参数化测试

.net - 对 Winforms 事件驱动架构进行单元测试