การพัฒนา Unit Testing โดย MSTest test library (.NET Core)
บทความนี้นำเสนอขั้นตอนการพัฒนา Unit Test อย่างง่ายโดยแสดงให่้เห็นการพัฒนาทีละขั้นตอน สำหรับระบบที่พัฒนาบน .NET Core โดยใช้ MSTest เพื่อทำความเข้าใจการพัฒนาแบบ test-driven development (TDD) ซึ่งในขั้นแรก เริ่มต้นด้วยการสร้าง source project ชื่อ “CalcTool” ใช้สำหรับการทดสอบ อยู่ภายใต้ folder “TestSample” ซึ่งขั้นตอนการสร้าง project สามารถดูได้จาก บทความ การพัฒนา Unit Testing โดย xUnit test library (.NET Core) ซึ่งจะได้ class “Calc” ซึ่งประกอบไปด้วย method “AbsAddByOne(int value)” ที่ยังไม่ได้เขียน code การทำงาน สร้าง test project ที่ใช้ MSTest library โดยเปิด command prompt เข้าไปที่ folder “TestSample” และสร้าง sub folder ชื่อ “CalcTool.MSTests” จากนั้นเข้าไปที่ folder “CalcTool.MSTests” ทำการสร้าง .NET Core project โดยใช้คำสั่ง dotnet new mstest โดยคำสั่งนี้จะทำการสร้าง test project ที่ใช้ MSTest test library และกำหนดค่า test runner <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″/> </ItemGroup> เพิ่ม reference ไปยัง project ที่ต้องการทดสอบซึ่งในที่นี้คือ CalcTool project โดยใช้คำสั่ง dotnet add reference ../CalcTool/CalcTool.csproj จากนั้นให้ execute คำสั่ง dotnet restore เพื่อ restore NuGet package ที่จำเป็นต้องใช้ในแต่ละ project เริ่มพัฒนา unit testing โดยลบ file “UnitTest1.cs” และสร้าง file ใหม่โดยใช้ชื่อว่า “CalcTest.cs” และเขียน code ดังนี้ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CalcTool.MSTest { [TestClass] public class CalcTest { [TestMethod] public void AbsAddByOneTest() { var c = new Calc(); var result = c.AbsAddByOne(5); Assert.AreEqual(result, 6); } } } *[TestClass] attribute ใช้เพื่อบอกว่ามี unit test อยู่ใน class นั้น *[TestMethod] attribute ใช้เพื่อกำหนดว่า method นั้นๆเป็นแบบ single test ทำการทดสอบโดยการ execute dotnet test ซึ่งจะทำการ build และ start MSTest test runner ซึ่งพบว่าผลการทดสอบ fail เนื่องจากยังไม่ได้ implement code ใน method “AbsAddByOne” ของ class “Calc” ดังนั้นกลับไปที่ method