Bart Schelkens
Bart Schelkens

Reputation: 1293

Unittesting Repositories using mocks

I'm trying to write unittests. It is the first time I'm doing this using repositories and dependency injection.

My unittest looks as follows :

[TestClass()]
public class PersonRepositoryTests
{
    Mock<PersonRepository> persoonRepository;
    IEnumerable<Person> personen;

    [TestInitialize()]
    public void Initialize()
    {
        persoonRepository = new Moq.Mock<PersonRepository >();
        personen = new List<Person>() { new Person { ID = 1, Name = "Bart Schelkens", GewerkteDagen = 200, Leeftijd = 52, Type = "1" },
                                        new Person { ID = 2, Name = "Yoram Kerckhofs", GewerkteDagen = 190, Leeftijd = 52, Type = "1" }};

        persoonRepository.Setup(x => x.GetAll()).Returns(personen);

    }

    [TestMethod()]
    public void GetAll()
    {
        var result = persoonRepository.Object.GetAll();
    }
}

My repository :

 public class PersonRepository
{
    DatabaseContext DbContext { get; }

    public PersonRepository(DatabaseContext dbContext)
    {
        this.DbContext = dbContext;
    }

    public virtual IEnumerable<Person> GetAll()
    {
        return DbContext.Persons.ToList();
    }

}

Now when I run my test, I get the following error :

"Can not instantiate proxy of class: CoBen.Dossier.DataAccess.Repository.PersonRepository. Could not find a parameterless constructor."

So I am doing something wrong, but I'm not seeing it. Can anyone help me?

Upvotes: 0

Views: 137

Answers (3)

NikolaiDante
NikolaiDante

Reputation: 18639

You're mocking your system under test (sut), the PersonRepository, where as what you need to Mock is it's dependencies:

[TestMethod]
public void GetAll()
{
    // *Arrange*
    var mockSet = new Mock<DbSet<Person>>(); 

    var mockContext = new Mock<DatabaseContext>(); 
    mockContext.Setup(m => m.Person).Returns(mockSet.Object); 

    // Configure the context to return something meaningful

    var sut = new PersonRepository(mockContext.Object);

    // *Act*
    var result = sut.GetAll()

    // *Assert* that the result was as expected
}

It's a little bit "air code" as your question doesn't have much detail around how the DbContext bit is configured.

There is a worked example on MSDN.

Upvotes: 1

C Kingsley
C Kingsley

Reputation: 238

That error is occuring because in your unit test you are mock the repository but your repository class seems to have a dependency on the datacontext.

You need to add a default contructor in your repository that does not have the datacontext as a dependency as per below:

public PersonRepository()

or mock the datacontext. Hope that helps

Upvotes: 2

Mitklantekutli
Mitklantekutli

Reputation: 410

Try add a parameterless constructor :)

public PersonRepository(){}

Upvotes: 0

Related Questions