Test Explorer中单元测试显示‘未运行’且仅出警告的原因排查
.NET单元测试未运行及警告的原因分析
作为.NET新手,我编写了Person类及对应的单元测试代码,但在Visual Studio的Test Explorer里只显示“1个未运行的测试”,执行dotnet test命令也只有警告、无错误输出,请问问题出在哪?
Person类代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonCreator { public class Person { public string Name { get; set; } = ""; public DateTime BirthDate { get; set; } = new DateTime(1900, 1, 1); public double Height { get; set; } = 0.0; public Boolean IsMarried { get; set; } = false; public int NoOfChildren { get; set; } = 0; public Person(string name, DateTime birthdate, double height, Boolean isMarried, int noOfChildren) { this.Name = name; this.BirthDate = birthdate; this.Height = height; this.IsMarried = isMarried; this.NoOfChildren = noOfChildren; } public string MakeTitle() { string title = ($"{Name};{BirthDate};{Height};{IsMarried};{NoOfChildren}"); return title; } } }
单元测试代码
using PersonCreator; [TestClass] public class UnitTest1 { [TestMethod] public void CheckPersonConstructor() { // #### ARRANGE #### Person person = new Person("John Doe", new DateTime(1975, 8, 24), 175.9, true, 3); // #### ACT #### string title = person.MakeTitle(); // #### ASSERT #### Assert.AreEqual("John Doe;24-08-1975 00:00:00;175,9;True;3", title); } }
测试未运行的核心原因
- 缺少测试框架依赖:测试类中使用的
[TestClass]、[TestMethod]属于MS Test框架,但测试项目大概率没安装对应的NuGet包(Microsoft.NET.Test.Sdk、MSTest.TestAdapter、MSTest.TestFramework)。没有这些依赖,测试运行器无法识别测试方法,自然不会执行。 - 项目类型错误:如果测试项目不是用“单元测试项目(.NET)”模板创建的普通类库,测试运行器也无法识别其中的测试代码。
警告及后续断言失败的潜在原因
即使解决了测试运行的问题,你的代码还会因为格式匹配问题导致断言失败,这也是dotnet test出现警告的可能来源:
- DateTime格式依赖系统文化:
BirthDate直接ToString()的输出格式随系统区域设置变化,默认不会是24-08-1975 00:00:00这种格式。 - 数字小数点符号差异:
Height的输出中,小数点符号受系统文化影响,你断言用的是逗号175,9,但多数英文环境下会输出点175.9,导致不匹配。
解决步骤
- 补全测试框架依赖:在测试项目的NuGet包管理器中安装以下包:
Microsoft.NET.Test.SdkMSTest.TestAdapterMSTest.TestFramework
- 统一输出格式避免文化差异:修改
MakeTitle方法,显式指定格式:public string MakeTitle() { var invariantCulture = System.Globalization.CultureInfo.InvariantCulture; string title = $"{Name};{BirthDate:dd-MM-yyyy HH:mm:ss};{Height.ToString(invariantCulture)};{IsMarried};{NoOfChildren}"; return title; } - 确认测试项目配置:右键测试项目→属性,确保输出类型为“类库”,且目标框架与Person类所在项目一致。
内容的提问来源于stack exchange,提问作者Aleksandar
相关产品推荐
相关产品推荐

