- Assert.AreEqual と Assert.AreNotEqual
- Assert.AreAboutEqual と Assert.AreNotAboutEqual
- Assert.IsTrue と Assert.IsFalse
- Assert.IsNull と Assert.IsNotNull
指定された平等または不平等原則の違反を検出する
public void TestAssertEqual()
{
Assert.AreEqual("123", "456", "断言检测违背相等原则");
Assert.AreNotEqual("123", "123", "断言检测违背不相等原则");
}
ほぼ等しいか等しくないかをテストします
public void TestAreApproximatelyEqual()
{
// 默认允许误差小于 0.00001f,这里我们制定误差为 0.01f
Assert.AreApproximatelyEqual(0.9f, 0.91f, 0.01f, "断言检测 约等于 不成立");
Assert.AreNotApproximatelyEqual(0.9f, 0.9000001f, 0.01f, "断言检测 不约等于 不成立");
}
値が True か False かを確認します
public void TestIsTrue()
{
Assert.IsTrue(1 > 2, "违背结果为真的原则");
Assert.IsTrue(Testbool());
Assert.IsFalse(1 < 2, "违背结果为假的原则");
}
public bool Testbool()
{
return false;
}
Null かどうかを確認する
public void TestIsNull()
{
Student student1 = new Student();
Assert.IsNull(student1,"检测结果值不为null");
student1 = null;
Assert.IsNotNull<Student>(student1,"检测结果为null");
}
アサーションの比較ルールをカスタマイズすることもできます。コードは次のとおりです。
public class Student
{
public string name;
public int number;
public int age;
}
public void TestCustomEqualityComparer()
{
Student S1 = new Student() { age = 1 };
Student S2 = new Student() { age = 2 };
Assert.AreEqual(S1, S2, "自定义比较结果为不相等", new CustomEqualityComparer<Student>((s1, s2) => { return s1.age == s2.age; }));
}
比較部分は IEqualityComparer を継承して、比較したいルールを再実装することです
アサーションのもう 1 つの機能は、トリガー条件の後にコード ブロックの実行を防止するかどうかです.使用される API は Assert.raiseExceptions で、デフォルト値は false です
効果は次のとおりです。
Assert.raiseExceptions = false;
public void TestRaiseExceptions()
{
Assert.raiseExceptions = false;
Assert.IsTrue(1 > 2);
Assert.IsTrue(1 > 2, "自定义输出");
Debug.LogError(new string('*', 20));
Debug.Log("执行");
}
Assert.raiseExceptions = true;
public void TestRaiseExceptions()
{
Assert.raiseExceptions = true;
Assert.IsTrue(1 > 2);
Assert.IsTrue(1 > 2, "自定义输出");
Debug.LogError(new string('*', 20));
Debug.Log("执行");
}