Mocking Extension Methods

Mocking

Mocking is a technique where a dependency to a class is swapped out (mocked) with an alternate/fake equivalent to the functionality so that the class can be tested in isolation from it’s dependencies. For these examples, I’ll be using the mocking framework Moq.

Suppose we have a method that we wanted to mock:

1
2
3
4
5
6
7
8
9
10
11
public interface IPunctuation
{
string AddExclamationPoint(string s);
}

public class Punctuation : IPunctuation
{
public string AddExclamationPoint(string s) {
return s + "!";
}
}

We use the method like this:

1
2
3
var punctuation = new Punctuation();
var s = punctuation.AddExclamationPoint("Hello");
// Result: "Hello!"

Mocking this is fairly straighforward using Moq:

1
2
3
4
5
var punctuationMock = new Mock<IPunctuation>();
punctuationMock
.Setup(p => p.AddExclamationPoint(It.IsAny<string>()))
.Returns("HardcodedResult");
var punctuation = punctuationMock.Object;

Once mocked, we use it in the exact same way as we use the real Punctuation class, but with the mocked result:

1
2
var s = punctuation.AddExclamationPoint("Hello");
// Result: "HardcodedResult"

That’s mocking. For more on mocking, see Moq’s documentation.

Extension Methods

Extension methods in C# are static methods that provide some helpful syntax to make code that consumes them a little more readable (and chainable).

We can change the method above to an extension method by making the class and method static and by adding the this keyword:

1
2
3
4
5
6
public static class PunctuationExtensions
{
public static string AddExclamationPoint(this string s) {
return s + "!";
}
}

And the usage of the extension method is a little cleaner:

1
2
var s = "Hello".AddExclamationPoint();
// Result: "Hello!";

Mocking Extension Methods

I love to mock things when testing, and I love using extension methods, because I find both to be very helpful in writing clean, maintainable code. But how can we mock an extension method?

In the example above, how would I mock out the AddExclamationPoint() method from the PunctuationExtensions class?

Well, you can’t.

Read More

Chrome 58 and Self Signed Certificates in IIS

When working in development, sometimes you need to use an SSL certificate. There is no need to pay a provider to sign one for you, because you can create a ‘self signed’ certificate. IIS can do this out of the box for localhost - for more Information, see Scott Guthrie’s walkthrough on creating a self signed certificate in IIS.

That worked great, for a while. But with Chrome 58, which was released in May 2017, a new security feature was introduced which prevents Chrome from trusting a self-signed certificate generated by IIS. The problem is that IIS generates a self signed SSL certificate that doesn’t include a SubjectAlternativeName (SAN), and starting with Chrome 58, certificates without a SAN are seen as insecure.

Read More