Asserts
The Assert
class is a part of the Cobra Logging package, designed to facilitate assertions within applications. It provides a range of methods for validating conditions, enhancing code robustness by identifying issues early in the development process.
Features
- Comprehensive Validation: Supports various assertions including null checks, collection emptiness, numeric comparisons, and more.
- Informative Logging: Logs detailed messages upon assertion failure, aiding in quick issue identification.
- Exception Control: Optionally throws exceptions on failed assertions to halt execution, signaling critical issues immediately.
Key Methods
- NotNull: Ensures a specified parameter is not null.
- NotEmpty: Verifies a collection is not empty.
- NotNullOrWhitespace: Confirms a string is neither null, empty, nor whitespace only.
- GreaterThan: Checks if a value is greater than a specified limit.
- LessThan: Verifies a value is less than a specified limit.
- InRange: Asserts a value falls within a specified range.
- NotNullOrEmpty: Ensures a collection is neither null nor empty.
- AreEqual: Verifies the value of a parameter matches an expected value.
- Contains: Asserts a collection contains an item that meets a specified condition.
- DoesNotContain: Ensures a collection does not contain any item that satisfies a provided condition.
- Implements: Checks if an object implements a specified interface.
Usage
Basic Assertions
Assert.NotNull(() => myObject, "MyObject must not be null.");
Assert.NotEmpty(() => myList, "The list cannot be empty.");
Assert.NotNullOrWhitespace(() => myString, "Input cannot be blank.");
Numeric Comparisons
Assert.GreaterThan(() => age, 18, "Age must be over 18.");
Assert.LessThan(() => temperature, 100, "Temperature must be below 100 degrees.");
Assert.InRange(() => score, 0, 100, "Score must be between 0 and 100.");
Collection Assertions
Assert.NotNullOrEmpty(() => myCollection, "The collection cannot be null or empty.");
Assert.Contains(() => myCollection, item => item.IsValid, "Collection must contain at least one valid item.");
Assert.DoesNotContain(() => myCollection, item => item.IsExpired, "Collection should not contain expired items.");
Type Assertions
Assert.Implements<IExpectedInterface>(() => myObject, "Object must implement IExpectedInterface.");
Advanced Features
- ParameterExpression: Utilizes lambda expressions for parameter checks, enabling precise identification of the assertion's context.
- Custom Messages: Allows specifying custom messages to enhance the information provided by logs on assertion failures.
- Control Over Exceptions: The throwException parameter dictates whether an exception is thrown, offering flexibility based on the criticality of the assertion.