Assertによる検証
TEST_CLASS内に用意した各TEST_METHODでテストを行い、その結果を検証します。class Assertにはさまざまな検証関数が定義されています(各関数の引数の後ろにはデフォルト引数が続きますがここでは省略)。
| 検証関数 | 補足説明 |
| AreEqual<T>(const T& expected, const T& actual) | expected == actual |
| AreEqual(double expected, double actual, double tolerance) | |expected-actual| <= |tolerance| |
| AreEqual(float expected, float actual, float tolerance) | |
| AreEqual(const char* expected, const char* actual, bool ignoreCase =false) | 文字列として等値 |
| AreEqual(const wchar_t* expected, const wchar_t* actual, bool ignoreCase =false) | |
| AreSame<T>(const T& expected, const T& actual) | &expected == &actual |
| AreNotEqual<T>(const T& notExpected, const T& actual) | !(notExpected == actual) |
| AreNotEqual(double notExpected, double actual, double tolerance) | |notExpected-actual| > |tolerance| |
| AreNotEqual(float notExpected, float actual, float tolerance) | |
| AreNotEqual(const char* notExpected, const char* actual, bool ignoreCase =false) | 文字列として等値でない |
| AreNotEqual(const wchar_t* notExpected, const wchar_t* actual, bool ignoreCase =false) | |
| AreNotSame<T>(const T& notExpected, const T& actual) | !(¬Expected == &actual) |
| IsNull<T>(const T* actual) | actual == nullptr |
| IsNotNull<T>(const T* actual) | !(actual == nullptr) |
| IsTrue(bool condition) | condition == true |
| IsFalse(bool condition) | condition == false |
| Fail() | 常に失敗 |
| AreEqual<T>(T^ expected, T^ actual) | expected->Equals(actual) |
| AreEqual(string^ expected, string^ actual, bool ignoreCase =false) | 文字列として等値 |
| AreSame<T>(T% expected, T% actual) | %expected == %actual |
| AreNotEqual<T>(T^ notExpected, T^ actual) | !expected->Equals(actual) |
| AreNotEqual(string^ notExpected, string^ actual, bool ignoreCase =false) | 文字列として等値でない |
| AreNotSame<T>(T% notExpected, T% actual) | !(%notExpected == %actual) |
| IsNull<T>(T^ actual) | actual == nullptr |
| IsNotNull<T>(T^ actual) | !(actual == nullptr) |
| ExpectedException<Exception,Functor>(Functor functor) | functor() が Exception を throw する |
| ExpectedException<Exception,ReturnType>(ReturnType (*func)()) | func() が Exception を throw する |
最後の2つについては多少なりとも説明しておいた方がよさそうです。例えばこんな関数:
double square_root(double x) {
if ( x < 0.0 ) {
throw std::domain_error("argument should NOT be negative!");
}
return std::sqrt(x);
}
のテスト・ケースは2つ:
- x >= 0 なる x に対し xの平方根を返す
- x < 0 なる x に対し std::domain_error 例外がthrowされる
前者のテストは簡単です:
Assert::AreEqual(0.000, square_root(0.0), 0.01); Assert::AreEqual(1.414, square_root(2.0), 0.01);
後者についてはAssert::ExpectedExceptionを用いて:
TEST_CLASS(SquareRootTest) {
// lambda式でファンクタを与えて...
TEST_METHOD(bad_test1) {
Assert::ExpectedException<std::domain_error>([](){ square_root(-1.0); });
}
// あるいはstatic関数を用意し、
static void bad_root() {
square_root(-1.0);
}
// そのポインタを与えて...
TEST_METHOD(bad_test2) {
Assert::ExpectedException<std::domain_error>(&bad_root);
}
}
期待通りにstd::domain_errorがthrowされれば、なにごともなくテスト成功ですが、例外がthrowされない、あるいはthrowされてもstd::domain_errorではなかったときは失敗となります。
