Chiefy
Chiefy

Reputation: 179

Entity Framework 4 Unit Testing and Mocking


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.

Upvotes: 0

Views: 716

Answers (1)

Dennis Traub
Dennis Traub

Reputation: 51634

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

Upvotes: 1

Related Questions