I have an implementation of an authenticated HttpClient
generator class that resembles this:
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.
}
}
... how can I test that the GenerateClient()
method has successfully attached the client certificate to the HttpClient
class?
[TestMethod]
public void HttpClientCreationIncludesCertificate()
{
using (var auth = new X509Authentication(_certificate))
using (var client = auth.GenerateClient())
{
Assert...what? The certificate(s) are not visible here.
}
}
...or am I trying to test the wrong thing?
Chrome: Verifying that Your Client Certificate Is InstalledIn Chrome, go to Settings. On the Settings page, below Default browser, click Show advanced settings. Under HTTPS/SSL, click Manage certificates. In the Certificates window, on the Personal tab, you should see your Client Certificate.
HTTPS Client Authentication requires the client to possess a Public Key Certificate (PKC). If you specify client authentication, the web server will authenticate the client using the client's public key certificate.
The server authenticates the client by receiving the client's certificate during the SSL handshake and verifying the certificate is valid. Validation is done by the server the same way the client validates the server's certificate. The client sends a signed certificate to the server.
9 month old question but anyhow :)
What I would do. You are thinking correctly with the interface. Now that you have an interface you can mock away the "real" implementation of GenerateClient
since this method doesn't do anything else then using someone else's code (Code that that's not very test-friendly in the first place).
What I would test in this situation is that the method that should call IClientAuthenticator.GenerateClient
really calls it. An example ->
[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);
}
Now we can be safe knowing that the client certificate is added when it should be. Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With