0


I am very new to unit testing when it comes to databases and especially entity framework and I am now stuck. I am using NUnit to test and mock the entities used and am working using a generic repository. My entity framework has a full set of POCO classes and the bit I am currently testing looks like this:

    campaignRepoMock = new DynamicMock(typeof(IRepository<Campaign>));
    campaignRepoMock.ExpectAndReturn("First", testCampaign, new Func<Campaign, bool>(c => c.CampaignID == testCampaign.CampaignID));
    CampaignService campaignService = new CampaignService((IRepository<Campaign>)campaignRepoMock.MockInstance);
    Campaign campaign = campaignService.GetCampaign(testCampaign.Key, ProjectId);
    Assert.AreEqual(testCampaign, campaign);

testCampaign is a single POCO campaign test object. The method "First" in the IRepository looks like the following:

    public T First(Func<T, bool> predicate)
    {
        return _objectSet.FirstOrDefault<T>(predicate);
    }

The error I am getting from Nunit is

CampaignServiceTests.Campaign_Get_Campaign:   
  Expected: <System.Func`2[Campaign,System.Boolean]>  
  But was: <System.Func`2[Campaign,System.Boolean]>

So it is basically saying that it is getting what it is expecting, but its throwing an error? Maybe my understanding of this is all wrong, I just want to test the searching for a Campaign based on its key and the project it is linked to. The GetCampaigns method just search the repository sent to it for a campaign that has both of those items.

Can anyone point me to what I am doing wrong? Thanks in advance.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
Chiefy
  • 179
  • 2
  • 17

1 Answers1

1

If I understand your code, over here

campaignRepoMock.ExpectAndReturn("First", testCampaign, new Func<Campaign, bool>(c => c.CampaignID == testCampaign.CampaignID));

you are setting up your mock object to return a function that is not identical to your testCampaign.

Assert.AreEqual() tests for strict equality. testCampaign and campaign are of the same type and have the same content, but refer to different objects.

What mocking framework are you using? Looks pretty complicated and confusing to me. For starting I would recommend something like Moq

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
  • Hi thanks for your answer, I shall look into that and get back to you. I am using the NUnit.Mocks mocking framework. I looked at Moq but couldnt get my head around it as easily as this, maybe i should give it another go. – Chiefy Aug 19 '11 at 14:08
  • Once you get it, it's really easy. Have a look at this introduction to Moq: http://www.dimecasts.net/Casts/CastDetails/8 – Dennis Traub Aug 19 '11 at 14:21
  • Thanks Dennis, also found a good post on here http://stackoverflow.com/questions/5769414/cannot-seem-to-moq-ef-codefirst-4-1-help-anyone. Turns out searching for "EF" bring more results than "Entity Framework". Will use Moq instead. – Chiefy Aug 19 '11 at 14:28