Có hai cách verify exception trong unit testing:
- Dùng
Assert.ThrowsException - Dùng attribute
ExpectedException
Ví dụ method cần test
using System;
namespace DemoApplication
{
public class Program
{
static void Main(string[] args) { }
public string StringAppend(string firstName, string lastName)
{
throw new Exception("Test Exception");
}
}
}
Cách 1: Assert.ThrowsException
using System;
using DemoApplication;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DemoUnitTest
{
[TestClass]
public class DemoUnitTest
{
[TestMethod]
public void DemoMethod()
{
Program program = new Program();
var ex = Assert.ThrowsException(() => program.StringAppend("Michael", "Jackson"));
Assert.AreSame(ex.Message, "Test Exception");
}
}
}
Gọi StringAppend qua Assert.ThrowsException, validate exception type và message. Test case pass.
Cách 2: ExpectedException Attribute
using System;
using DemoApplication;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DemoUnitTest
{
[TestClass]
public class DemoUnitTest
{
[TestMethod]
[ExpectedException(typeof(Exception), "Test Exception")]
public void DemoMethod()
{
Program program = new Program();
program.StringAppend("Michael", "Jackson");
}
}
}
Dùng ExpectedException attribute chỉ định type của expected exception. Vì StringAppend ném cùng loại exception trong attribute, test case pass.