m.edmondson
m.edmondson

Reputation: 30882

Trying to create Moq object

I've got a method which takes a IList<Person> and returns an IEnumberable as so:

 internal static IEnumerable<Dictionary<string, string>> GetPersonsPerSite(IList<Person> Data)
    { 
         //Implementation ...
    }

and I'm trying to create a mock object of IList<Person> so I can test this method.

Using Moq I have written the following:

var mockObjects = new Mock<IList<Person>>();

mockObjects.Setup(x => x[0]).Returns(new Person()
                                                 {
                                                        SITE_ID = "test",
                                                        MPAN = "test",
                                                        ADDLINE1 = "test",
                                                        ADDLINE2 = "test",
                                                        ADDRESS_LINE_1 = "test",
                                                        ADDRESS_LINE_2 = "test"
                                                 });

However when I come to use the object the IEnumerable returned is aways throwing exception Object reference not set to an instance of an object.

I'm brand new to Moq, and I'm pretty sure I'm missing a fundamental concept here, however I've successfully being able to throw exceptions and modifiy outputs with other mock objects.

I'd appreciate if someone could point me in the right direction.

Upvotes: 0

Views: 2155

Answers (2)

Rob Levine
Rob Levine

Reputation: 41298

The code you have got there looks fine and does work for me. Can you expand with an example of where you actually consume the mockObjects.Object and find it null?

Also, do you really need to mock your IList<Person>? If you are just using it to supply test data to the method under test, just use a concrete list - there is nothing gained by using a mock for this.

Of course, you may be mocking it so you can verify certain actions are taken on it (methods called, properties accessed, etc) - in which case that is different.

Upvotes: 3

Richard Banks
Richard Banks

Reputation: 12546

Don't mock the IList. You don't need to, unless there's something specific your looking to check.

Instead just keep your test simple and do something like this:

var testData = new List<Person>(){new Person()
                                                 {
                                                        SITE_ID = "test",
                                                        MPAN = "test",
                                                        ADDLINE1 = "test",
                                                        ADDLINE2 = "test",
                                                        ADDRESS_LINE_1 = "test",
                                                        ADDRESS_LINE_2 = "test"
                                                 }};
var result = GetPersonsePerSite(testData);

Upvotes: 5

Related Questions