实体框架4单元测试和模拟

时间:2011-08-19 11:39:41

标签: unit-testing entity-framework-4 nunit repository-pattern


当谈到数据库,尤其是实体框架时,我对单元测试非常陌生,现在我陷入困境。我正在使用NUnit来测试和模拟使用的实体,并且正在使用通用存储库。我的实体框架有一整套POCO类,我目前测试的那个是这样的:

    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是一个POCO广告系列测试对象。 IRepository中的方法“First”如下所示:

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

我从Nunit得到的错误是

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

所以它基本上是说它正在得到它所期待的,但它抛出错误?也许我对此的理解是完全错误的,我只想根据其关键字及其链接的项目来测试搜索广告系列。 GetCampaigns方法只搜索发送给它的存储库,以查找包含这两个项目的广告系列。

有人能指出我做错了什么吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

如果我理解你的代码,请点击此处

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

您正在设置模拟对象以返回与testCampaign不同的函数。

Assert.AreEqual()测试严格的平等。 testCampaigncampaign属于同一类型且内容相同,但引用的是不同的对象。

你使用什么模拟框架?看起来很复杂,令我感到困惑。首先,我会推荐像Moq

这样的东西