简体   繁体   English

NUnit:在断言中使用对象之前,我是否应该检查对象是否不是 null?

[英]NUnit: Should I check that objects are not null before using them in asserts?

I'm writing a test that calls a method that may potentially return null.我正在编写一个调用可能返回 null 的方法的测试。 In this specific test, the returned object must not be null and some property on it must match a specific value.在这个特定的测试中,返回的 object不能是 null 并且它的某些属性必须匹配特定的值。 Example:例子:

var obj = thing.GetObject();
Assert.That(obj, Is.Not.Null);
Assert.That(obj.Name, Is.EqualTo("Name"));

This is a habit of mine from C++, where you'd normally have an assertion prior to using a pointer since accessing null can crash the unit test (and you'd want to avoid doing that).这是我在 C++ 中的一个习惯,在使用指针之前通常会先进行断言,因为访问 null 可能会使单元测试崩溃(并且您希望避免这样做)。 In C#, however, accessing null objects is a normal exception.然而,在 C# 中,访问 null 对象是一个正常的异常。 Is it a good practice to do what I've done above, or just go ahead and access the object and rely on the exception to fail the test case if the object is null? Is it a good practice to do what I've done above, or just go ahead and access the object and rely on the exception to fail the test case if the object is null? As in:如:

var obj = thing.GetObject();
Assert.That(obj.Name, Is.EqualTo("Name")); // Throws if `obj` is null

I'm no authority on the matter but I think you'll get more meaningful and consistent test result messages if you assert that it's not null instead of letting it throw an exception.我对此事没有权威,但我认为如果你断言它不是 null 而不是让它抛出异常,你会得到更有意义和一致的测试结果消息。 I do it in my own unit tests, for what it's worth.我在自己的单元测试中这样做,这是值得的。

A NullReferenceException is a sign that you missed something. NullReferenceException表示您错过了某些内容。 Asserting that the result is not null before testing the property is not missing that something.在测试属性之前断言结果不是 null 并没有遗漏一些东西。

It depends, I'm afraid.这取决于,我害怕。

In the example you give, there is no initial setup, yet you state that the method called may sometimes return null.在您给出的示例中,没有初始设置,但是您 state 调用的方法有时可能会返回 null。 Without that setup, you can't test for null or non-null, because (as stated) either is possible.如果没有该设置,您将无法测试 null 或非空值,因为(如前所述)两者都是可能的。 Such a test is not useful.这样的测试是没有用的。

OTOH in the real test, you will have done setup and should actually know what result you expect. OTOH 在实际测试中,您将完成设置并且应该知道您期望的结果。 In that case, test for it, just as you have done.在这种情况下,请像您所做的那样对其进行测试。

You should also have a test where the object is set up to return null and test for that situation.您还应该进行测试,其中 object 设置为返回 null 并针对这种情况进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM