2012-02-05 62 views
1

我想为我创建的Web服务编写一些单元测试。问题是,该服务正在使用基于成员资格和角色提供者的身份验证和授权。服务内部的方法使用ServiceSecurityContext.Current.Identity来访问有关当前用户的信息。测试使用IdentityPrincipal的WCF服务

现在我不确定我该如何测试这样的服务?我可以以某种方式模拟ServiceSecurityContext吗?或者,也许我应该在我的测试项目中创建HostedService,并在测试启动时运行它?或者,也许我不应该测试它呢?

回答

1

我建议将这个属性隐藏在自己的接口后面,以便轻松嘲讽并将此类的一个实例注入到您的服务中。这也将使您能够更改检索当前身份的机制,而不会影响许多代码文件。

public interface IUserProvider 
{ 
    IIdentity Identity { get; } 
} 

public class UserProvider : IUserProvider 
{ 
    public IIdentity Identity 
    { 
    get { return ServiceSecurityContext.Current.Identity; } 
    } 
} 
+0

不幸的是,这将行不通,因为我使用像annotions“[的PrincipalPermission(SecurityAction.Demand,角色=‘MyRole’)]”,以测试用户是否具有一定的作用,并且该值从取存储在当前线程中的信息。 – domderen 2012-02-05 10:35:49

+0

隔离框架鼹鼠可能会在这里帮助:http://research.microsoft.com/en-us/projects/moles/ – Javi 2012-02-05 18:52:47