3
//class = Person
public string Name { get; internal set; }

I have an object with several different fields that are declared as shown above. I would like to use Moq so I can unit test the repository. The repository simply returns a list of names, so I would like to setup Moq to work with it like so:

var personRepositoryMock = new Mock<IPersonRepository>();

personRepositoryMock
        .Setup(p => p.GetNames())
        .Returns(new List<Person>
        {
            new Person{Name = "Hulk Hogan"}
        });

Being new to mocking and unit testing in general, I have a couple of questions:

  1. What are my options to stub out the Person class in my scenario?

  2. What is the benefit of mocking in this situation? I read and read and read, but I can't seem to get my head around why I see examples like this, testing a repository. Mocks make sense to me when I have to unit test business logic, but not so much in the data layer. Any words of wisdom to clear this up for me?

Thanks.

Mike
  • 2,912
  • 4
  • 31
  • 52

1 Answers1

4

1) You can use the "InternalsVisibleTo" attribute on the assembly (in AssemblyInfo.cs) that contains the repository class, to give the Moq assembly access to it.

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
[assembly: InternalsVisibleTo("YourTestClass")]

2) Mocking decouples your data layer from being a dependency requirement for unit tests.

Think of it this way: you won't be creating a Mock to test the repository itself. You're creating the mock for other classes to use as a fake data source, to test their functionality that requires input data from the repository in the real application.

If you can accurately predict the data cases that your repository will provide, then you can mock those cases as fake input, and not require that your unit tests actually connect to the database to get live data to use.

Your example won't actually unit test anything in the repository (other than the parameterless constructor!) so ... I don't know where you're seeing these examples, but I don't feel that the code above is providing anything useful "as is".

Community
  • 1
  • 1
womp
  • 115,835
  • 26
  • 236
  • 269