我的测试用例没有执行,它开始执行,但什么都没有发生,并且显示未运行状态。当我点击运行测试时,excel文件不会打开,测试运行显示Not Run
。我不知道问题出在哪里,因为没有显示错误。请引导我。
应该是这样的:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Excel = Microsoft.Office.Interop.Excel;
using Xceed.Wpf.Toolkit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Test01.AppObj
{
[TestClass]
public class MainProjectFile
{
bool control = true;
private bool show_messages = true;
[TestMethod]
public void TestExcel_RunExceldownload_OK()
{
//Arrange
List<string> lst1 = new List<string>() { "Abc", "10t", "88990" };
show_messages = false;
//Act
bool returnValue = Exceldownload(lst1);
//Assert
Debug.Assert(returnValue==true);
}
private bool Exceldownload(List<string> lst)
{
string str;
int rw = 0;
int cl = 0;
bool returnValue = false;
Excel.Application xlApp = new Excel.Application();
{
xlApp.Visible = true;
xlApp.DisplayAlerts = false;
}
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"path", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "", false, false, 0, true, false, false);
xlApp.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMaximized;
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
rw = xlRange.Rows.Count;
cl = xlRange.Columns.Count;
for (int i = 1; i <= cl; i++)
{
str = Convert.ToString((xlRange.Cells[2, i] as Excel.Range).Value2);
if (!lst[i - 1].Equals(str))
{
if (show_messages)
MessageBox.Show($"Not match in column: {i}");
control = false;
returnValue = false;
}
}
if (control)
{
returnValue = true;
if (show_messages)
MessageBox.Show($"All match");
}
xlWorkbook.Close(0);
xlApp.Quit();
return returnValue;
}
private void Button1_Click(object sender, EventArgs e)
{
List<string> lst1 = new List<string>() { "Abc", "10t", "88990" };
Exceldownload(lst1);
}
}
}
我补充道:
private bool show_messages = true;
然后创建了新的测试方法:
[TestMethod]
public void TestExcel_RunExceldownload_OK()
的一些小变化
private bool Exceldownload(List<string> lst)
以在测试方法时不显示消息框。我把void改成了bool,以制作Assert。
通常,如果您希望测试工作,您必须编写一个公共测试方法并添加适当的属性:[TestMethod]。此外,为了编写好的测试,尝试使用Arrange-Act-Assert模式,请参见例如:https://github.com/testdouble/contributing-tests/wiki/Arrange-Act-Assert
这里有几件事。首先检查单元测试官方文件中的测试方法要求
测试方法必须满足以下要求:
列出项目
它是用[TestMethod]属性装饰的。
它返回无效。
它不能有参数。
这意味着你应该像@Marcin提到的那样更改代码。
[TestInitialize]
//[Ignore]
[Priority(1)]
[TestMethod]
public void ExceldownloadTest()
{
// Init list
this.Exceldownload(lst);
}
public void Exceldownload()
{
// Your code.
}
我能看到的第二件事是,你的代码坏了,这就是为什么你的参数超出了范围。你的问题就在这里:
for (int i = 1; i <= cl; i++)
{
str = Convert.ToString((xlRange.Cells[2, i] as Excel.Range).Value2);
if (!lst[i - 1].Equals(str)) // Problematic row
现在执行了测试,i比原来的长度3高得多。
尝试使用进行更改
if (lst.Count > i-2 && !lst[i - 1].Equals(str)) // Problematic row