Visual Studio 2017 NUnit Usage

NUnit 是 .NET 的 unit test framework

建立專案

  1. 新增「Visual Studio C# 類別庫 (.Net Framework)」專案
  2. 在 solution 裡加入 unit test 新專案,一樣是 Visual Studio C# 類別庫 (.Net Framework)

unit test project 可命名為 [Project].UnitTests

安裝 NUnit 套件

在 unit test project 右鍵 → 管理 NuGet 套件 → 搜尋 → 安裝。

安裝 NUnitNUnit3TestAdapter 套件,NUnit 裝完可以在參考看到 nunit.framework

安裝的 NUnit 版本是 3.11.0。

寫 & 跑測試

在 unit test project 加入要測試的 project 的參考。

在 class 前標註 [TestFixture] 表示 NUnit 測試的類別,在 function 前標註 [Test] 表示測試。

選單→測試→執行→所有測試,就會出現「測試總管」顯示測試結果啦~

SetUp & TearDown

執行每個測試 function 前會執行標上 [SetUp] attribute 的 function,通常用來準備物件、進行測試需要的設定等等。

每個測試 function 執行後會執行標上 [TearDown] 的 function。

標上 [OneTimeSetUp][OneTimeTearDown] 則是在所有測試 function 執行前與執行後會跑一次的 function。

這幾個 attribute 在一個 test fixture 裡都可以標多個 function,不過一般來說一個 test fixture 只會標一個,在繼承的情況下才會多個 function 使用相同 attribute。

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using NUnit.Framework;

namespace LogAn.UnitTests
{
[TestFixture]
public class LogAnalyzerTests
{
private LogAnalyzer analyzer = null;

[SetUp]
public void Setup()
{
analyzer = new LogAnalyzer();
}

[TearDown]
public void TearDown()
{
// Just a sample
}

[Test]
public void IsValidFileName_BadExtension_ReturnsFalse()
{
bool result = analyzer.IsValidLogFileName("testing.foo");
Assert.False(result);
}
}
}

Ref