我有一個單元測試裝置,我試圖在ASP.NET MVC控制器上測試ControllerAction,這個控制器用於Web應用程序的成員函數。我試圖嘲笑測試的HttpContext。被測試的ControllerAction實際上在HttpContext上設置了屬性,例如Session值,Response.Cookies值等。這不是所有的代碼,但這裏是我試圖運行的測試的粗略示例:用Moq嘲弄HttpContextBase
[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)這是否會是一個更好的方法?
謝謝。
是的,謝謝,但我使用Moq 3.1.416.3,所以它確實有助於查看該版本的語法。主要是因爲,顯然,如果我理解正確,「設置」屬性在3.x中有很大的不同。感謝這個例子。 – 2009-08-04 15:48:02
用安裝替換Expect,它應該按原樣工作。 – 2009-08-04 16:21:35