.Netcore很快到2了,各种周边的配套也不断的完善,为了跨平台,微软也是相当的有诚意,很多功能不在需要绑定宇宙第一编辑器了。本文以单元测试为例,讲述利用dotnet命令行创建单元测试的全过程。
安装环境
因为不想使用VS这个庞然大物,安装的时候,选择单独安装包,Windows下直接下载安装文件,安装就好啦。打开命令行输入dotnet --version,就会看到刚刚安装的版本号,安装完毕。
创建项目
个人喜好,为了代码整洁,会单独建一个测试项目,因此这里需要至少两个项目 首先创建一个项目根文件夹:
mkdir ut
进入根文件夹,创建库类型的项目:
dotnet new classlib -n PrimeService
再创建测试项目:
dotnet new mstest -n PrimeService.MSTests
目前命令行支持创建xunit和MSTest两种类型的测试项目,这里选择MSTest类型的测试
在PrimeService.MSTests项目下PrimeService.MSTest.csproj的文件里增加对PrimeService项目的依赖
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="MSTest.TestAdapter" Version="1.1.11" />
<PackageReference Include="MSTest.TestFramework" Version="1.1.11" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.3.0" />
<ProjectReference Include="..\PrimeService\PrimeService.csproj" />
</ItemGroup>
编写功能
按照测试驱动开发的一般流程,进入PrimeService项目,把Class1.cs文件改成Prime.cs,代码如下:
using System;
namespace PrimeService
{
public class Prime
{
public bool IsPrime(int candidate)
{
throw new NotImplementedException("Please create a test first");
}
}
}
先不用实现IsPrime方法,写对应的测试代码,进入PrimeService.MSTests项目,修改UnitTest1.cs文件的代码如下:
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PrimeService.MSTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var _prime = new PrimeService.Prime();
int value = 2;
var result = _prime.IsPrime(value);
Assert.IsTrue(result);
}
}
}
在PrimeService.MSTest根目录下,运行:
dotnet restore
dotnet test
正常情况下,不出意外会输出如下测试结果:
System.NotImplementedException: Please create a test first
堆栈跟踪:
测试运行失败。
at PrimeService.Prime.IsPrime(Int32 candidate) in C:\devs\dot\ut\PrimeService\Pri
me.cs:line 10
at PrimeService.MSTest.UnitTest1.TestMethod1() in C:\devs\dot\ut\PrimeService.MSTe
st\UnitTest1.cs:line 13
总测试: 1。已通过: 0。失败: 1。已跳过: 0。
测试执行时间: 1.0572 秒
如果发现控制台输出中文乱码,那是因为codepage不对,默认的codepage是65001,而中文版Windows的默认codepage是936,为此,可以暂时把命令行的codepage切换成65001, 命令如下:
chcp 65001
实现功能
修改IsPrime函数,实现完整的功能:
public bool IsPrime(int candidate)
{
if (candidate < 2)
{
return false;
}
for (var divisor = 2; divisor <= Math.Sqrt(candidate); divisor++)
{
if (candidate % divisor == 0)
{
return false;
}
}
return true;
}
再次在测试项目下运行dotnet test,测试通过。