我是单元测试的初学者。我正在尝试编写测试脚本,但是我被卡住了。我想了解自己在做错什么。
public ConvertExcelDocumentResponse ConvertExcelDocument(ConvertExcelDocumentRequest request)
{
var logger = Bootstrapper.Resolve<ILogger>();
ConvertExcelDocumentResponse response = new ConvertExcelDocumentResponse();
if (!string.IsNullOrEmpty(request.FileName) &&
System.IO.Path.GetExtension(request.FileName).ToLowerInvariant() == ".xls" &&
request.FileContent != null && request.FileContent.Length > 0)
{
response.FileContent = _httpClient.ConvertExcelDocument(request.FileContent, request.FileName);
response.FileName = System.IO.Path.GetFileNameWithoutExtension(request.FileName) + ".xlsx";
response.Success = true;
}
else
{
logger.LogError("Unable to convert Excel Document '" + request.FileName + "' only .xls files are allowed.");
response.FileContent = new byte[] { };
response.Success = false;
}
return response;
}
这是我的考试:
/// <summary>
/// Test to Convert XLS to XLSX
/// </summary>
[TestCategory("DocumentService")]
[TestMethod]
public void Test_ConvertExcelDocumentResponse()
{
byte[] filecontent = new byte[] { };
string filename = "file";
using (ShimsContext.Create())
{
ConvertExcelDocumentRequest excelDocumentRequest1 = new ConvertExcelDocumentRequest()
{
FileName = "filename",
FileContent = new byte[] {},
};
ConvertExcelDocumentRequest excelDocumentRequest2 = new ConvertExcelDocumentRequest()
{
FileName = "",
FileContent = new byte[] {},
};
ShimDocumentService.AllInstances.ConvertExcelDocumentConvertExcelDocumentRequest = ((@this, Success) =>
{
return new ConvertExcelDocumentResponse()
{
FileContent=filecontent,
Success = true,
FileName = filename,
};
});
ShimHttpClientBase.AllInstances.ConvertWordDocumentByteArrayString = ((@this, fileContent, fileName) =>
{
return fileContent;
});
//Act
ILogger logger = Bootstrapper.Resolve<ILogger>();
var docService = new DocumentService();
//IDocumentService DocumentService = Bootstrapper.Resolve<IDocumentService>();
var excelResponse1 = docService.ConvertExcelDocument(excelDocumentRequest1);
var excelResponse2 = docService.ConvertExcelDocument(excelDocumentRequest2);
//Assert
Assert.AreEqual(excelResponse1.FileContent, filecontent );
Assert.AreEqual(excelResponse1.FileName, filename);
Assert.IsTrue(excelResponse1.Success, "Expects true");
Assert.AreEqual(excelResponse2.FileContent, filecontent);
Assert.AreEqual(excelResponse2.FileName, filename);
Assert.IsTrue(excelResponse2.Success, "Expects true");
}
}
这通过了测试,但代码覆盖率为0%。我不知道我要去哪里错了。我尝试覆盖filename = null和其他一些条件。不知道为什么它没有覆盖我的代码
答案 0 :(得分:0)
您似乎还需要编写一个测试,其中文件名为null或为空。这样,您将覆盖else块中的代码。
增加代码覆盖率通常涉及使测试练习的代码片段不太可能被正常击中。