Assert (検証)メソッド サンプル集
Assert.That で期待する条件を書く
NUnit のアサーションは、実際の値が期待どおりかを調べます。Assert.That(実際値, 条件) と書くと、どの値に何を期待しているかを順番に読めます。テストコードでは using NUnit.Framework; を指定します。Unity 6.6 の公式資料では、Test Framework は NUnit 3.5 をベースにしたカスタム版を使用しています。
| 確かめたいこと | Assert.That の例 | 旧来の書き方 |
|---|---|---|
| 等しい | Assert.That(actual, Is.EqualTo(expected)); | Assert.AreEqual(expected, actual); |
| 等しくない | Assert.That(actual, Is.Not.EqualTo(expected)); | Assert.AreNotEqual(expected, actual); |
| 真 | Assert.That(condition, Is.True); | Assert.IsTrue(condition); |
| 偽 | Assert.That(condition, Is.False); | Assert.IsFalse(condition); |
| null | Assert.That(value, Is.Null); | Assert.IsNull(value); |
| null 以外 | Assert.That(value, Is.Not.Null); | Assert.IsNotNull(value); |
浮動小数点の近似値では、期待値からどこまでの差を許すか決めます。
using NUnit.Framework;
public class ApproximationTests
{
[Test]
public void PiApproximation_IsWithinTolerance()
{
float actual = 3.1415f;
Assert.That(actual, Is.EqualTo(3.14f).Within(0.01f));
}
}
この例では、3.14f との差が 0.01f 以内なら成功します。Unity の GameObject やコンポーネントが破棄済みかを確かめる場合は、Unity の == null を使うと、Unity が扱う生存状態を検証できます。たとえば Play Mode で Destroy を呼んで次フレームまで待ったあと、Assert.That(gameObject == null, Is.True); と書きます。
NUnit の制約モデル · NUnit の等値制約 · UnityEngine.Object の等価演算子 · Edit Mode での実行手順








ディスカッション
コメント一覧
まだ、コメントがありません