我有一个下面的方法可以生成pdf,并且单元测试通过最小起订量。
public Task<Document> GenerateDocumentAsync(IData data)
{
var template = GetTemplateForTheme(data.Theme);
VerifyTemplateExists(template);
var relevantData = (RelevantData)data;
var voucherViewModel = _mapper.Map<VoucherViewModel>(relevantData);
var html = _htmlGenerator.Generate(template, voucherViewModel);
var bytes = _pdfRenderer.Render(html);
var document = new Document
{
Name = "Voucher.pdf",
MimeType = "application/pdf",
Data = bytes
};
return Task.FromResult(document);
}
并且单元测试正在通过最小起订量。
[TestInitialize]
public void Initialize()
{
_mockPdfRenderer = new Mock<IPdfRenderer>();
_mockPdfRenderer.Setup(x => x.Render(It.IsAny<string>())).Returns(AnyBytes());
_mockTemplateLocationResolver = new Mock<ITemplateLocationResolver>();
_mockTemplateLocationResolver.Setup(x => x.Resolve(It.IsAny<string>(), It.IsAny<string>()))
.Returns("template-name.cshtml");
_mockHtmlGenerator = new Mock<IHtmlGenerator>();
_mockMapper = new Mock<IMapper>();
_mockFileSystemWrapper = new Mock<IFileSystemWrapper>();
_mockFileSystemWrapper.Setup(x => x.Exists(It.IsAny<string>())).Returns(true);
_mockChannelContext = new Mock<IChannelContext>();
_mockChannelContext.SetupGet(x => x.ChannelId).Returns(default(int));
}
[TestMethod]
public async Task GenerateDocumentAsync_Called_ExpectReturnsDocumentOfCorrectMimeType()
{
var target = DefaultSubjectUnderTest();
var data = AnyRelevantData();
var actual = await target.GenerateDocumentAsync(data);
actual.MimeType.Should().Be("application/pdf");
}
private VoucherGenerator DefaultSubjectUnderTest()
{
return new VoucherGenerator(
_mockPdfRenderer.Object,
_mockTemplateLocationResolver.Object,
_mockHtmlGenerator.Object,
_mockMapper.Object,
_mockFileSystemWrapper.Object,
_mockChannelContext.Object);
}
private static VoucherData AnyRelevantData()
{
return new VoucherData();
}
public interface IChannelContext
{
int ChannelId { get; }
string ChannelName { get; }
}
当我使用附加属性更改方法时,上述测试失败,因为_mapper.Map返回null,并且无法将值分配给IsTradeExist,从而抛出未设置为实例的错误对象。 如何在代码中进行以下更改使上述测试通过?如何编写针对新代码行的单元测试?
public Task<Document> GenerateDocumentAsync(IData data)
{
var template = GetTemplateForTheme(data.Theme);
VerifyTemplateExists(template);
var relevantData = (RelevantData)data;
var voucherViewModel = _mapper.Map<VoucherViewModel>(relevantData);
voucherViewModel.IsTradeExist = _channelContext.ChannelId == (int)ChannelEnum.TradeSite; //new line of code added
var html = _htmlGenerator.Generate(template, voucherViewModel);
var bytes = _pdfRenderer.Render(html);
var document = new Document
{
Name = "Voucher.pdf",
MimeType = "application/pdf",
Data = bytes
};
return Task.FromResult(document);
}