Simple Entity Framework testing with Typemock Isolator

One of my favorite things about TypeMock is how easy you can isolate out entity framework and the database from your production code, without having to write loads of extra mocking code. To show that I’ve got a really short piece of production code.

Here’s a method that uses my Entity Framework context:

public int GetUserAccountWithToken(string token) { if (string.IsNullOrEmpty(token)) throw new ArgumentException("Token cannot be empty", "token"); var user = _context.useraccounts.Single(t => t.appToken == token); if (user == null) return 0;
return user.id; }

So, a simple method that retrieve a single record based an a string token using our app . If it doesn’t find a record (user == null) then it returns a zero.

What I want to test is that you get an user id back if the datacontext returns a user object. Here’s my test method:

(TestMethod) (Isolated) public void GetUserAccountWithToken_CorrectToken_ReturnUserId() { var repository = new UserAccountRepository();
DbSet fakeUserAccountEntityDbSet = Isolate.Fake.Instance>();
string aToken = Guid.NewGuid().ToString(); int fakeUserId = -1; var user = new useraccount() {id = fakeUserId , appToken = aToken };
Isolate.WhenCalled( () => fakeUserAccountEntityDbSet.Single(null)) .WillReturn(user);
Assert.AreEqual(-1, repository.GetUserAccountWithToken(correctToken)); }

repository holds the GetUserAccountWithToken method, It’s the class we are testing in and GetUserAccountWithToken is the test method, and we are working with the entity DbSet of type useraccount. aToken is a dummy text we need to complete the test, fakeUserId is nothing more than that, we just need a number that could have come from the database. The user object is the fake response object from the database(context).

The magic starts with WhenCalled… When our production code hits a request to the object of type DbSet and asks for a “Single” record – Instead of going to the database, it returns our fake user object (WillReturn). Everything else in the production code runs as written and intended, it’s just the _context part that is replaced or intercepted.

This example just takes out one DbSet from the context, next I’ll show how to fake the whole context.

Setup and teardown of test objects for tests is usually placed inside global and local setup/teardown methods and not declared and initialized in the local test (more on how and what that is later)

Use Facebook to Comment on this Post


  • Love
  • Save
    Add a blog to Bloglovin’
    Enter the full blog address (e.g. https://www.fashionsquad.com)
    We're working on your request. This will take just a minute...