I was wondering what I should test and how I should test an IRepository.
At the moment I created a MemoryRepository in my domain and I am testing that with fake data. I am not sure if this is correct though. Feels a little weird to first create some data and then test to see if the repository returns it correctly.
This is what my MemoryRepository looks like:
public class MemoryRepositoryUser : IRepositoryUser
{
List<User> fakeUsers;
public MemoryRepositoryUser(List<User> fakeUsers)
{
this.fakeUsers = fakeUsers;
}
public IEnumerable<User> GetAll()
{
return fakeUsers;
}
public User GetById(string id)
{
return GetAll().Where(u => u.Username == id).Single();
}
}
These are some tests I wrote:
[TestFixture]
class TestMemoryRepositoryUser
{
private MemoryRepositoryUser repository;
public TestMemoryRepositoryUser(){
repository = new MemoryRepositoryUser(FakeData.GetFakeUsers());
}
[Test]
public void Get_All_Users()
{
var Users = repository.GetAll();
Assert.IsNotNull(Users);
Assert.IsInstanceOf(typeof(IEnumerable<User>), Users);
Assert.AreEqual(3, Users.Count());
}
[Test]
public void Get_User_By_ID()
{
var Username = "Bob";
var User = repository.GetById(Username);
Assert.IsNotNull(User);
Assert.AreEqual(Username, User.Username);
}
}
I am pretty new to testing code and I mostly have problems with what I should test. I guess testing a MemoryRepository helps me to create all the features I need in the interface without having to talk to a database?
Typically repository tests are integration tests and they do talk to the database. As you've noticed, there's little point to testing a repository with fake data.
It's usually the repository that's mocked to test other classes. By mocking every dependency except the class under test, you can isolate the functions that you are testing. The benefit of declaring interfaces for repositories is that it allows them to be easily mocked and used in unit tests of other code.