단위 테스트에서 예외를 확인할 수 있는 두 가지 방법이 있습니다.
- Assert.ThrowsException 사용
- ExpectedException 속성 사용.
예
예외를 throw하는 StringAppend 메서드를 테스트해야 한다고 가정해 보겠습니다.
using System;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
}
public string StringAppend(string firstName, string lastName) {
throw new Exception("Test Exception");
}
}
} 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<Exception>(() => program.StringAppend("Michael","Jackson"));
Assert.AreSame(ex.Message, "Test Exception");
}
}
} 예를 들어 Assert.ThrowsException을 사용하여 StringAppend 메서드를 호출하고 예외 유형과 메시지의 유효성을 검사합니다. 따라서 테스트 케이스는 통과할 것입니다.
ExpectedException 속성 사용
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");
}
}
} 예를 들어, ExpectedException 속성을 사용하고 예상되는 예외 유형을 지정합니다. StringAppend 메서드는 [ExpectedException(typeof(Exception), "Test Exception")]에 언급된 것과 동일한 유형의 예외를 throw하므로 테스트 케이스가 통과합니다.