2009-12-09 22 views
26

我搜索了stackoverflow並搜索了幾個小時,但仍然沒有找到任何解決方案來解決我的「微不足道」問題。如何對已應用[Authorize]屬性的控制器方法進行單元測試?

如果您爲已過濾的[Authorize] ActionResult編寫單元測試,那麼如何解決該問題以假冒該用戶已通過身份驗證?

我有很多的過濾與[Authorize]ActionResult方法,我想測試我所有的ActionResult方法不管它們與[Authorize]或過濾。

的我是什麼意思一個簡單的例子:

[TestMethod] 
public void Create_Get_ReturnsView() 
{ 
// Arrange 
var controller = new UserController(); 
// Act 
var result = controller.Create(); 
// Assert 
Assert.IsNotNull(result as ViewResult); 
} 

[Authorize] 
public ActionResult Create() 
{ 
return View("Create"); 
} 

截至目前測試甚至不打,因爲[授權]過濾器,拋出異常的ActionResult的方法是:System.NullReferenceException: Object reference not set to an instance of an object.

+1

有些東西你沒有向我們展示。您顯示的測試不會執行任何*操作過濾器。也許你有代碼,但它不在你的問題。對於初學者來說,錯誤的整個調用堆棧如何? – 2009-12-09 22:11:21

回答

25

你需要爲你的控制器模擬一個上下文。嘗試使用Moq

你的安排則看起來像:

var controller = new UserController(); 
var mock = new Mock<ControllerContext>(); 
mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER"); 
mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true); 
controller.ControllerContext = mock.Object; 

你應該能夠然後做你&法斷言。

如果您還沒有,我會強烈建議通過NerdDinner作爲MVC站點的示例。

+0

Awsome,這工作完美...非常感謝 – Webking 2009-12-09 22:43:14

+0

我可能會爭辯說,你根本不需要真的測試這個。編寫ASP.NET MVC的團隊已經對該屬性進行了充分測試。您可以下載源代碼並親自查看。 – 2010-06-25 03:49:10

+8

這不是爲了測試'[Authorized]'屬性,而是繞過它來測試'ActionResult'方法 – AndyMcKenna 2011-11-11 21:34:00

相關問題