我有一个经过身份验证的HttpClient
生成器类的实现,类似于:
public class X509Authentication : IClientAuthenticator
{
protected readonly X509Certificate2 Certificate;
public X509Authentication(X509Certificate2 certificate)
{
if (certificate == null) throw new ArgumentNullException("certificate");
Certificate = certificate;
}
public HttpClient GenerateClient()
{
var clientHandler = new WebRequestHandler();
clientHandler.ClientCertificates.Add(Certificate);
var request = new HttpClient(clientHandler);
return request;
}
public void Dispose()
{
//nothing to do here.
}
}
...如何测试GenerateClient()
方法是否已成功将客户端证书附加到HttpClient
类?
[TestMethod]
public void HttpClientCreationIncludesCertificate()
{
using (var auth = new X509Authentication(_certificate))
using (var client = auth.GenerateClient())
{
Assert...what? The certificate(s) are not visible here.
}
}
......或者我试图测试错误的东西?
答案 0 :(得分:1)
9个月大的问题,但无论如何:)
我会做什么。您正在考虑使用该界面。现在你有了一个界面,你可以嘲笑"真正的" GenerateClient
的实施,因为这种方法除了使用别人的代码之外没有做任何其他事情(代码首先不是非常适合测试的代码)。
在这种情况下我要测试的是应该调用IClientAuthenticator.GenerateClient
的方法真正调用它。一个例子 - >
[TestMethod]
Public void MyClass_MymethodthatcallsGenereateClient_DoesCallGenerateClient()
{
// Arrange
Mock<IClientAuthenticator> clientAuth = new Mock<IClientAuthenticator>();
MyClass myclass = new MyClass()
// Act
var result = MyClass.MymethodthatcallsGenereateClient();
// Assert (verify that we really added the client)
clientAuth.Verify(x => x.GenerateClient);
}
现在我们可以安全地知道客户端证书应该添加的时候。 希望这有帮助!