[英]How can I mock a DbContext to use within unit tests of a repository?
[英]How can I mock data for unit tests?
我正在嘗試創建一種優雅的方式來為我的測試編寫虛擬數據而無需復制粘貼。
public void AssetIndexPortfolioCompositionMappingTest()
{
var AssetIndexDTO = new AssetIndexSummaryDto()
{
PortfolioComposition = new PortfolioCompositionDto()
{
FaceValue = decimal.Zero,
InsolvencyCasesPercentage = 1,
LegalCasesPercentage = 2,
NumberOfAccounts = 3,
NumberOfCustomers = 4,
NumberOfTotalPayments = 5,
Principal = 6.7m
}
};
var AssetIndexEntity = new AssetIndexEntity();
_mapper.Map(AssetIndexDTO, AssetIndexEntity);
// Assert
AssetIndexDTO.PortfolioComposition.FaceValue.Should().Be(AssetIndexEntity.FaceValue);
AssetIndexDTO.PortfolioComposition.LegalCasesPercentage.Should().Be(AssetIndexEntity.LegalCasesPercentage);
AssetIndexDTO.PortfolioComposition.NumberOfAccounts.Should().Be(AssetIndexEntity.NumberOfAccounts);
AssetIndexDTO.PortfolioComposition.NumberOfCustomers.Should().Be(AssetIndexEntity.NumberOfCustomers);
AssetIndexDTO.PortfolioComposition.NumberOfTotalPayments.Should().Be(AssetIndexEntity.NumberOfTotalPayments);
AssetIndexDTO.PortfolioComposition.Principal.Should().Be(AssetIndexEntity.Principal);
}
這是我的測試和初始化 AssetIndexDTO 的新 object 的部分,我想模擬它以便我可以在所有測試中重新使用它而無需每次都復制粘貼
我嘗試的是使用最小起訂量
var mock = new Mock<AssetIndexSummaryDto>();
mock.SetupAllProperties();
然后在斷言中我試圖將它與映射值進行比較
mock.Object.PortfolioComposition.FaceValue.Should().Be(AssetIndexEntity.FaceValue);
但它不工作並引發System.NullReferenceException: 'Object reference not set to an instance of an object.'
提前致謝!
您通常不會模擬數據,而是模擬與測試無關/不需要的功能。
只需將生成虛擬數據的代碼移動到一個方法並調用所有測試:
public void AssetIndexPortfolioCompositionMappingTest()
{
var AssetIndexDTO = GetTestAssetIndexSummaryDto();
var AssetIndexEntity = new AssetIndexEntity();
_mapper.Map(AssetIndexDTO, AssetIndexEntity);
// Assert
AssetIndexDTO.PortfolioComposition.FaceValue.Should().Be(AssetIndexEntity.FaceValue);
AssetIndexDTO.PortfolioComposition.LegalCasesPercentage.Should().Be(AssetIndexEntity.LegalCasesPercentage);
AssetIndexDTO.PortfolioComposition.NumberOfAccounts.Should().Be(AssetIndexEntity.NumberOfAccounts);
AssetIndexDTO.PortfolioComposition.NumberOfCustomers.Should().Be(AssetIndexEntity.NumberOfCustomers);
AssetIndexDTO.PortfolioComposition.NumberOfTotalPayments.Should().Be(AssetIndexEntity.NumberOfTotalPayments);
AssetIndexDTO.PortfolioComposition.Principal.Should().Be(AssetIndexEntity.Principal);
}
private AssetIndexSummaryDto GetTestAssetIndexSummaryDto()
{
return new AssetIndexSummaryDto()
{
PortfolioComposition = new PortfolioCompositionDto()
{
FaceValue = decimal.Zero,
InsolvencyCasesPercentage = 1,
LegalCasesPercentage = 2,
NumberOfAccounts = 3,
NumberOfCustomers = 4,
NumberOfTotalPayments = 5,
Principal = 6.7m
}
};
}
如果你想避免復制粘貼,我建議你實現一些創建 object 的方法。並在你的測試中重用該方法。 我在這里看不到 mocking 的需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.