使用dotnet命令行进行.netcore单元测试

.Netcore很快到2了,各类周边的配套也不断的完善,为了跨平台,微软也是至关的有诚意,不少功能不在须要绑定宇宙第一编辑器了。本文以单元测试为例,讲述利用dotnet命令行建立单元测试的全过程。windows

安装环境

由于不想使用VS这个庞然大物,安装的时候,选择单独安装包,Windows下直接下载安装文件,安装就好啦。打开命令行输入dotnet --version,就会看到刚刚安装的版本号,安装完毕。编辑器

建立项目

我的喜爱,为了代码整洁,会单独建一个测试项目,所以这里须要至少两个项目 首先建立一个项目根文件夹:函数

mkdir ut

进入根文件夹,建立库类型的项目:单元测试

dotnet new classlib -n PrimeService

再建立测试项目:测试

dotnet new mstest -n PrimeService.MSTests

目前命令行支持建立xunit和MSTest两种类型的测试项目,这里选择MSTest类型的测试spa

在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,代码以下:rest

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文件的代码以下:code

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根目录下,运行:ssl

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,测试经过。

相关文章
相关标签/搜索