[Unit Test]Assert Exception with MSTest

  • 5038
  • 0

[Unit Test]Assert Exception with MSTest

前言

沒寫過 Unit Test 的朋友對於驗證某些 scenario 應拋出某些特定種類的 exception,往往寫法都會使用 production code 的角度來作。這邊要介紹的是,使用 MSTest 時,請使用 ExpectedException 這個 attribute 來驗證是否攔截到特定種類的 exception

 

一般寫法

舉例來說,我們有個 Calculator 類別,呼叫 Divide 方法時,若除數為 0 ,預期會 throw System.DivideByZeroException 這個 exception 。一般常見的測試程式寫法,如下圖所示:

image

然而,這樣的寫法並不直覺,也無法一眼看出來我們預期的行為,也就是需求。

 

透過 ExpectedException 來驗證

在 Microsoft.VisualStudio.TestTools.UnitTesting 這個 namespace 中有提供一個 attribute : ExpectedException ,其實就是用來作這一件事。使用方式如下圖所示:

image

簡單的說,就像使用 attribute 來進行 AOP 的設計一般,把 try/catch 驗證是否有引發特定 exception 的行為,封裝到 attribute 中。

跟上圖比較一下,我們需要寫的測試程式更少了,既不含邏輯,又能很清楚的表達:這個 TestMethod 應該要 throw DivideByZeroException ,否則應該為 test failed。

 

結論

雖然蠻多人認為 xUnit 家族驗證 exception 的方式寫的更美妙,如下圖為 NUnit 的驗證方式:

image
xUnit 則長這樣:

image

不過我覺得這三種方式其實沒差多少,如果只是要驗證有 throw 特定 exception ,只要不是自己用 try/catch 去攔 exception 作驗證,都能挺明確的表達出測試案例的意圖, production code 的需求,那就夠了。


blog 與課程更新內容,請前往新站位置:http://tdd.best/