我有一个单元测试工具,其中我试图测试用于Web应用程序成员资格功能的ASP.NET MVC控制器上的ControllerAction。我正在尝试为测试模拟HttpContext。受测试的ControllerAction实际上在HttpContext上设置属性,例如Session值、Response.Cookies值等。这不是所有代码,但这是我试图运行的测试的大致示例:
[Test]
public void ValidRegistrationDataSuccessfullyCreatesAndRegistersUser()
{
var context = new Mock<HttpContextBase>() {DefaultValue = DefaultValue.Mock};
context.SetupAllProperties();
var provider = new Mock<MembershipProvider>(new object[] {context.Object});
var controller = new AccountController(context.Object, provider.Object);
// This just sets up a local FormCollection object with valid user data
// in it to use to attempt the registration
InitializeValidFormData();
ActionResult result = controller.Register(_registrationData);
Assert.IsInstanceOfType(typeof(ViewResult), result);
// Here is where I'd like to attempt to do Assertions against properties
// of the HttpContext, like ensuring that a Session object called "User"
// exists, and new auth cookie exists on the Response.Cookies collection.
// So far I've been unable to successfully check the values of those properties.
// I've been unsuccessful in getting those properties setup correctly on my
// mock object so that my ControllerAction can actually *set* their values,
// and that I can make assertions on them afterwards. The above code actually
// generates a StackOverflowException (which I've reported) on the
// context.SetupAllProperties() call. What am I doing wrong, or what do I need
// to do to be able to set and assert on those context properties?
}
我不确定自己做错了什么,但如果有人能指点一下我该怎么设置这个模拟的HttpContextBase对象,使得我的控制器可以在其属性上设置值,并且我可以对这些属性进行断言,以确保我的ControllerAction正在按照我的需要执行。
我是否走错了方向?我知道MVC控制器有一个ControllerContext属性,可以用于设置Session等值,但我无法想象如何在没有注入的情况下模拟它。有没有其他方法可以做到这一点?(我还需要将该上下文传递给我的MembershipProvider)这种方法会更好吗?
谢谢。