Search Results for

    Show / Hide Table of Contents

    Property Constraint

    PropertyConstraint tests the value of a named property on an object against a further constraint.

    Usage

    Has.Property(string propertyName).<constraint>
    Has.Length.<constraint>
    Has.Count.<constraint>
    Has.Message.<constraint>
    Has.InnerException.<constraint>
    

    Examples

    public class Person
    {
        public string Name { get; set; } = "";
        public int Age { get; set; }
    }
    
    [Test]
    public void PropertyConstraint_Examples()
    {
        // Test property values
        Assert.That("Hello", Has.Property("Length").EqualTo(5));
        Assert.That(new int[] { 1, 2, 3 }, Has.Property("Length").EqualTo(3));
    
        // Common properties have shortcuts
        Assert.That("Hello", Has.Length.EqualTo(5));
        Assert.That(new List<int> { 1, 2, 3 }, Has.Count.EqualTo(3));
    
        // Exception properties
        var ex = new InvalidOperationException("Test error", new ArgumentException());
        Assert.That(ex, Has.Message.EqualTo("Test error"));
        Assert.That(ex, Has.InnerException.InstanceOf<ArgumentException>());
    
        // Custom object properties
        var person = new Person { Name = "Alice", Age = 30 };
        Assert.That(person, Has.Property("Name").EqualTo("Alice"));
        Assert.That(person, Has.Property("Age").GreaterThan(18));
    }
    

    Built-in Property Shortcuts

    Has.Length       // Equivalent to Has.Property("Length")
    Has.Count        // Equivalent to Has.Property("Count")
    Has.Message      // Equivalent to Has.Property("Message")
    Has.InnerException // Equivalent to Has.Property("InnerException")
    

    Notes

    1. If no constraint follows Has.Property(), it becomes a PropertyExistsConstraint.
    2. The property must be public and readable.
    3. If the property doesn't exist, the constraint fails with a descriptive message.

    See Also

    • PropertyExists Constraint - Just test for property existence
    • ExactCount Constraint - Count items matching a constraint
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0