C#TDD,集成测试存储库,验证添加测试

时间:2017-02-27 09:23:13

标签: c# entity-framework unit-testing integration-testing

我对TDD比较陌生,我在存储库类中有一个带有EF的存储库模式的项目。 现在我想测试这些存储库,我已经成功地模拟了DbContext。 (使用Moq和nunit)

现在我想验证向我的模拟数据库添加一个对象。测试说,测试通过,但我很确定,我的测试不正确,因为我在Add方法之前查询数据库,返回5个对象,然后我调用Add方法再次查询数据库,仍然只有5个对象,但我希望现在有6个物体。我在这里错过了什么吗?

Model Address.cs

public class Address
{
    public int Id { get; set; }
    public string Person {get; set; }
    //some more properties
}

Repository.cs

public async Task<AdresseDto> AddAdresseAsync(AdresseDto adresseDto)
{
   try
   {
       ctx.Adresse.Add(adresse);
       await ctx.SaveChangesAsync();
       adresseDto.Id = adresse.Id;
   }
   catch (Exception e)
   {
       Console.WriteLine("ohoh");
       Console.WriteLine(e.ToString());
       Console.WriteLine("ohoh");
       return null;
   }

return adresseDto;

}

UnitTest.cs

public async Task Test_AddTestAddress_ReturnsAddressWithId()
{
     var dummyDataInDb = AddressHelper.GetAdressen(5);
     var dummyData4Db = AddressHelper.GetAdressen(1).FirstOrDefault();
//AddressHelper returns just some dummy objects

     InitializeMock<Adresse>.With(dummyDataInDb.AsQueryable(), out AdresseMock);
     XaDbMock = new Mock<xaModel>();
     XaDbMock
         .Setup(x => x.Adresse)
         .Returns(AdresseMock.Object);
     _repository = NewAddressRepository(XaDbMock.Object);

     //When
     var addressesInDb = await _repository.GetAllAdressenAsync();
     var result = await _repository.AddAdresseAsync(dummyData4Db);
     var addressesInDbAfter = await _repository.GetAllAdressenAsync();

     //Then
     Assert.IsNotNull(addressesInDb);
     Assert.AreEqual(5, addressesInDb.Count);
     Assert.IsNotNull(result);
     Assert.AreEqual(0, result.Id);
     Assert.IsNotNull(addressesInDbAfter);
     Assert.AreEqual(6, addressesInDbAfter.Count);
 }

InitializeMock.cs

public class InitializeMock<T> where T : class 
{
    public static void With(IQueryable<T> dummyData, out Mock<DbSet<T>> mock)
    {
        mock = new Mock<DbSet<T>>();
        //Required for async tasks
        mock.As<IDbAsyncEnumerable>()
            .Setup(x => x.GetAsyncEnumerator())
            .Returns(new TestDbAsyncEnumerator<T>(dummyData.GetEnumerator()));
        //Required for async tasks
        mock.As<IQueryable<T>>()
            .Setup(x => x.Provider)
            .Returns(new TestDbAsyncQueryProvider<T>(dummyData.Provider));

        mock.As<IQueryable<T>>()
            .Setup(x => x.Expression)
            .Returns(dummyData.Expression);
        mock.As<IQueryable<T>>()
            .Setup(x => x.ElementType)
            .Returns(dummyData.ElementType);
        mock.As<IQueryable<T>>()
            .Setup(x => x.GetEnumerator())
            .Returns(dummyData.GetEnumerator);
    }
}

如果遗漏了什么,请告诉我。我将提供您需要的任何必要信息。

提前致谢

0 个答案:

没有答案