I am using nuit with moq to test my controllers.
I use a session class which has an interface and an HttpContext is injected into the constructor using ninject. like this
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;
}
I think in order to test the controller I have mock the HttpContext first and then pass that object into the the construtor of the mocked ISession. I have this so far
[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");
}
which builds but nunit returns the following error when the test is run
System.NotSupportedException : Type to mock must be an interface or an abstract or non-sealed class.
Thanks for all help.
Have your session take a HttpContextBase in the constructor and use that as the type of the property. You should still be able to pass a concrete HttpContext the the session in production code.
public class SessionService : ISession
{
public HttpContextBase Context { get; set; }
public SessionService(HttpContextBase context)
{
this.Context = context;
}
}
Then fix your unit test by passing "mockHttpContext.Object" to the session constructor and that it mocks the 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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With