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

Entity Framework Cache Busting

The DbContext in Entity Framework 6 automatically caches data that it retrieves from your database. This is useful, but sometimes data changes outside your context (perhaps by another user) and you end up with stale data. How can you force Entity Framework to reload the updated data from the database, and when should you do this?

There are several ways to manage this, depending on which version of Entity Framework you are using and what type of application you are writing.

  1. Disable Tracking using AsNoTracking()
  2. Throw away the DbContext and create a new one
  3. Use an ObjectQuery instead of a DBQuery and set MergeOptions
  4. Refresh the Entities
  5. Detatch the Entities
  6. Call GetDatabaseValues to get the updated values for a single Entity
  7. Use the stale data

Code related to this post can be found at https://github.com/codethug/EFCaching

Read More

A Simple interface for fluently mocking a DbSet

You are testing, right? Have you ever used a mock in your test? When testing a class, a mock allows you to create an object that looks just like an object that your class depends on, but acts in a very specific way that you specify for your test, so that you can test your class completely isolated from the rest of your code. If you’re not familiar with mocks, visit Moq’s quickstart guide to get started.

Now that you know about mocks, let’s look at mocking something a little more complicated. If you’ve ever wanted to unit test a method that uses a DbSet<T> to retrieve data, it can be challenging to figure out how to properly mock the DbSet<T>.

Read More

Web API Deep Dive - Testing with EF Rollbacks across HTTP (part 6 of 6)

Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.

Overview

A few weeks ago I wrote an article called Cleaning Up EF 6 Tests With Transactions Rollbacks, where I showed how to create integration tests that set up some data in a database, run a test against the data, and then roll back all changes to the data. The rollback was possible because all of the changes to the data were wrapped up inside a transaction.

This posts extends that idea, but instead of a test calling methods on a repository or service layer, this test makes an HTTP call against a Web API endpoint, while preserving the ability to revert all changes to the database as part of a transaction rollback.

The interesting part here is that we will create a database context, start a transaction against that context, create some test data, and then spin up a Web API server that uses that same context. When we’re done with our tests, we’ll roll back the transaction so that the database changes are all reverted.

2016-01-27 Update - clarified when Configuration is available in an API Controller

Read More

Web API Deep Dive - DTO Transformations and Automapper (Part 5 of 6)

Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.

Data Transfer Objects

First, off what is this DTO thing? A Data Transfer Object is an object structure that you use to transfer data across the wire. Sometimes it will look exactly like your entity framework entities. Sometimes it will be different.

For example, suppose you have a database with Customers and Invoices, and your tables look like this:

1
2
3
4
5
6
7
8
9
10
11
12
Customer Table
--------------
CustomerId
Name
City
Telephone

Invoice Table
-------------
InvoiceId
CustomerId
Amount

These are also what your Entity models look like, because entity models reflect the database structure.

Now suppose that you want to provide an API endpoint that returns a list of customers in a particular city with the number of invoices for each customer.

Read More