, 그렇지 않으면 요청이 null이 될 것입니다, 또한 당신의 HttpContext를 구성해야합니다. ,
/// <summary>
/// A Class to allow simulation of SessionObject
/// </summary>
public class MockHttpSession : HttpSessionStateBase
{
Dictionary<string, object> m_SessionStorage = new Dictionary<string, object>();
public override object this[string name]
{
get {
try
{
return m_SessionStorage[name];
}
catch (Exception e)
{
return null;
}
}
set { m_SessionStorage[name] = value; }
}
}
public class RequestParams : System.Collections.Specialized.NameValueCollection
{
Dictionary<string, string> m_SessionStorage = new Dictionary<string, string>();
public override void Add(string name, string value)
{
m_SessionStorage.Add(name, value);
}
public override string Get(string name)
{
return m_SessionStorage[name];
}
}
public class MockServer : HttpServerUtilityBase
{
public override string MapPath(string path)
{
return @"C:\YourCodePathTowherever\" + path;
}
}
마지막 :
private Mock<ControllerContext> GetContextBase()
{
var fakeHttpContext = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new MockHttpSession();
var server = new MockServer();
var parms = new RequestParams();
var uri = new Uri("http://TestURL/Home/Index");
var fakeIdentity = new GenericIdentity("DOMAIN\\username");
var principal = new GenericPrincipal(fakeIdentity, null);
request.Setup(t => t.Params).Returns(parms);
request.Setup(t => t.Url).Returns(uri);
fakeHttpContext.Setup(t => t.User).Returns(principal);
fakeHttpContext.Setup(ctx => ctx.Request).Returns(request.Object);
fakeHttpContext.Setup(ctx => ctx.Response).Returns(response.Object);
fakeHttpContext.Setup(ctx => ctx.Session).Returns(session);
fakeHttpContext.Setup(ctx => ctx.Server).Returns(server);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);
return controllerContext;
}
지지 클래스의 라인을 따라 있습니다 : 당신은 당신이 당신의 테스트 케이스의 시작 부분에 전화 컨트롤러의 기능에 뭔가를을 설정할 수 있습니다 :)
작업을
// Arrange
HomeController controller = new HomeController();
controller.ControllerContext = GetContextBase().Object;
당신에게 Request 객체를 줄 것이다 : 당신의 시험 방법의 상단에, 그냥이 호출을 추가 당신이해야
[편집]
이름 공간은 다음과 같습니다
using System.Security.Principal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
당신이 디버깅 할 때, 어떤 객체가 null? Request 객체를 설정 했습니까? –
creatcustomer 메소드의 NewCustomer 객체는 testmethod에 설정된 ID와 날짜로 채워집니다. – user3754602
디버그 모드로 테스트를 실행하면 NewCustomer와 Request가 null이 아니십니까? Moq를 사용할 때 당신은 당신의 요청 객체를 포함하여 HttpContext를 설정해야합니다. –