简体   繁体   English

C#单元测试:是否可以使用条件访问代替Debug.Assert?

[英]C# unit tests: Is it OK to use conditional access instead of Debug.Assert?

So I have the following unit test for a controller action (MVC 5). 因此,我具有以下针对控制器动作的单元测试(MVC 5)。 The purpose of the test is to ensure that the Edit action of the controller returns a model of type Contact : 测试的目的是确保控制器的Edit操作返回类型为Contact的模型:

    [TestMethod]
    public void Edit_ValidContactIdPassed_ShouldReturnEditViewWithContact()
    {
        var result = _controller.Edit(1) as ViewResult;
        result?.ViewData.Model.Should().BeOfType<Contact>();
    }

As you can see I am using the conditional access(?) on the result object instead of: 如您所见,我在result对象上使用条件访问(?),而不是:

        Debug.Assert(result != null, "result != null");

I believe the conditional access is more readable but is there any issues with this within the context of a unit test? 我相信条件访问更具可读性,但是在单元测试的上下文中是否存在任何问题?

Well if you are testing the var result and test must be negative if it is == null in this case you will prevent the error from being fired as with the conditional access you prevent a potential NullPointerException 好吧,如果您正在测试var result并且如果它== null ,则test必须为 ,在这种情况下,您将避免触发错误,因为有条件访问会避免潜在的NullPointerException

Assert.IsNotNull(result);

It's not that bad after all :)! 毕竟还不算太糟:)!

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

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