What is the way to go to fake my database layer in a unit test?

Posted by Michel on Stack Overflow See other posts from Stack Overflow or by Michel
Published on 2010-04-22T07:08:15Z Indexed on 2010/04/22 7:13 UTC
Read the original article Hit count: 296

Filed under:
|
|
|

Hi,

i have a question about unit testing.

say i have a controller with one create method which puts a new customer in the database:

//code a bit shortened
public actionresult Create(Formcollection formcollection){
    client c = nwe client();
    c.Name = formcollection["name"];
    ClientService.Save(c);
{

Clientservice would call a datalayer object and save it in the database. What i do now is create a database testscript and set my database in a know condition before testing. So when i test this method in the unit test, i know that there must be one more client in the database, and what it's name is.

In short:
ClientController cc = new ClientController();
cc.Create(new FormCollection (){name="John"});
//i know i had 10 clients before
assert.areEqual(11, ClientService.GetNumberOfClients());
//the last inserted one is John
assert.areEqual("John", ClientService.GetAllClients()[10].Name);

So i've read that unit testing should not be hitting the database, i've setup an IOC for the database classes, but then what? I can create a fake database class, and make it do nothing.

But then ofcourse my assertions will not work because if i say GetNumberOfClients() it will alwasy return X because it has no interaction with the fake database class used in the Create Method.

I can also create a List of Clients in the fake database class, but as there will be two different instance created (one in the controller action and one in the unit test), they will have no interaction.

What is the way to make this unit test work without a database?

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about .NET