如果直接引用Web Service写单元测试,运行以Windows集成方式认证并且不允许匿名访问的Web Service,那么运行的时候会报错,因为权限不够,可能是因为Visual Studio在运行的时候是以匿名用户的身份运行的,而非OS的用户身份,这样的情况需要写些代码来使用OS的用户身份:
        [TestInitialize]
        public void SetUp()
        {
            var basicHttpBinding = new BasicHttpBinding();

            basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;

            basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

            var endpoint = new EndpointAddress("http://localhost/IntegrationService/IntegrationService.asmx");

            _client = new IntegrationServiceSoapClient(basicHttpBinding, endpoint);
            _client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

            _client.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
        }
代码中的EndpointAddress和IntegrationServiceSoapClient要换成你自己的Web Service的对应内容。

更新:
如果按照 Windows平台应用的运行身份的更新中所说的指定用户,那么这里的单元测试就不需要这样麻烦了,直接new一个Client就可以了。

(Visited 162 times, 1 visits today)