views:

1082

answers:

3

My understanding is that you have to write unit tests that isolate functionality. So given a repository class that has this method:

Entity GetById(Guid id)

and a fake implementation (using a Dictionary for storage), how would you write a test without first adding an entity? Is it ok to use a known set of guids for testing? Then in the fake repository constructor I could fill the dictionary with a couple of entities where the guids follow a pattern, so that I can test the GetById() method with a guid that I know will return an entity.

Thanks for reading!

PS. This is my first time writing unit tests.

+3  A: 

Yes, you could use known test ids in your test - that is what I would do. Although I have become a fan of Rhino Mocks which lets you put more directly in the test about what you'd expect to the mock object to do.

For example just before your call to the repository, you would do this:

Expect.Call(repository.GetById("someObject")).Return(new RepositoryThing());

It appeals to me anyway :)

Chris Kimpton
You'd probably do new RepositoryThing { Id = 1, Name = "TestOne, ... }
tvanfosson
But then I'm no longer testing the fake repository?
michielvoo
+1  A: 

There is an interesting article here.

DeletedAccount
+1  A: 

Yes, using a fake implementation of an object/interface with a fixed list of items that can be queried from the fake instance is a valid practice.

Obviously, without adding an entry first, one can only test what's returned when the Guid can't be found in the repository.

In C# allows it, one also can have the fake implementation of the repository have a method to add items to the repository.

philippe