【问题标题】:How do I unit test an ASP.NET MVC controller that uses DotNetOpenId?如何对使用 DotNetOpenId 的 ASP.NET MVC 控制器进行单元测试?
【发布时间】:2009-06-09 19:56:27
【问题描述】:

我有一个 AccountController,其构造函数采用从我的自定义 IOpenIdAuthentication 接口派生的对象。默认情况下,这是一个包装 OpenIdRelyingPartyOpenIdAuthenticationService 对象。界面如下所示:

public interface IOpenIdAuthentication {
    IAuthenticationResponse Response { get; }
    IAuthenticationRequest CreateRequest(string identifier);
}

我可以模拟 IAuthenticationResponse

_mockResponse = new Mock<IAuthenticationResponse>(MockBehavior.Loose);
_mockResponse.SetupGet(r => r.ClaimedIdentifier).Returns(identifier);
_mockResponse.SetupGet(r => r.Status)
    .Returns(AuthenticationStatus.Authenticated);
// ... removed the formatting of 'friendlyId' ...
_mockResponse.SetupGet(r => r.FriendlyIdentifierForDisplay).Returns(friendlyId);

但是,我不确定如何模拟 IAuthenticationRequest,因为它看起来要复杂得多。有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc unit-testing mocking moq dotnetopenauth


    【解决方案1】:

    这并不复杂。如果您只进行身份验证,那么模拟 RedirectToProvider() 就足够了。在最简单的情况下,它看起来像:

    _mockRequest = new Mock<IAuthenticationRequest>(MockBehavior.Strict);
    _mockRequest.Setup(r => r.RedirectToProvider());
    

    希望对你有帮助

    【讨论】:

    • 啊,谢谢!我以前没有使用过模拟框架,所以我不确定是否必须模拟对象的每个部分。
    • 如果您是 Moq 新手,请注意 MockBehavior.Loose 和 MockBehavior.Strict 之间的区别。 Moq 库中有很多自动模拟功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2010-11-26
    • 1970-01-01
    • 2014-02-08
    相关资源
    最近更新 更多