![](/img/trans.png)
[英]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.