C# debugging and testing | Assert (assertion)

insert image description here

Assert (assertion)

foreword

Today I want to talk to you about an artifact in C# debugging and testing - assertion (Assert). If you don't know what an assertion is, or how to use assertions to debug your C# program, please listen to me slowly.


What is Assert

What is Assert?
Assertions are a tool for checking whether conditions are met while a program is running. If the condition is not met, the assertion will throw an exception, which helps us quickly locate and debug the problem.
In C#, you can use the Debug.Assert method to implement an assertion. This method accepts a Boolean expression as a parameter. If the expression evaluates to false, an AssertionFailedException will be thrown.


Applicable scene

When should assertions be used?

Normally, we should add assertions in the program to check whether the conditions we assume are true. For example, we can add an assertion to the method to check whether the incoming parameter is empty, or add an assertion to the loop to check whether the loop variable is within the specified range, and so on.
If the assertion fails, our assumption is wrong and the code needs to be modified.


Example of use

Check if the passed parameter is empty

public void Test(string name)
{
    
    
    Debug.Assert(!string.IsNullOrEmpty(name), "参数name不可为空。");
    // 你的代码...
}

If the name passed in is empty, an AssertionFailedException will be thrown.

Checks if loop variable is within specified range

for (int i = 0; i < 10; i++)
{
    
    
    Debug.Assert(i >= 0 && i < 5, "i的取值范围是[0,5)");
    // 你的代码...
}

If the value of the loop variable i is outside the specified range, an AssertionFailedException will be thrown.

Check if the method return value is null

public string GetName()
{
    
    
    string name = null;
    
    // 你的代码...
    
    Debug.Assert(name != null, "返回值name不可为空。");
    return name;
}

If the name returned by the method is null, an AssertionFailedException will be thrown.


conclusion

Assertion is a very useful debugging tool that can help us quickly locate and solve problems in the program.
However, assertions are not a panacea. If assertions are abused, the code may become confusing.

If you think this article is helpful to you, please like and follow me, I will continue to bring more interesting and practical technical articles.

Guess you like

Origin blog.csdn.net/lgj123xj/article/details/130143925