Skip to content

kasthack-labs/kasthack.NotEmpty

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

kasthack.NotEmpty

NuGet GitHub release license .NET Status Patreon pledges Patreon patrons

What?

kasthack.Empty is a library for recursively checking objects for emptinness(being null, default value, an empty collection or a string). It saves you from writing boilerplate in tests for deserializers / parsers / API clients.

Why does this exist?

Manually checking properties for emptinness leaves an opportunity to miss something and makes the developer to write boilerplate.

Usage

  1. Install the appropriate package
  1. Check your objects / their properties for emptinness. Look at the tests for more details.
using kasthack.NotEmpty.Xunit;  // replace the namespace to match your test framework

public class MyAmazingTest
{
    [Fact]
    public void MyThingWorks()
    {
        var targetObject = MyClass.GetResult();

        targetObject.NotEmpty();

        //<actual asserts>
    }

    [Fact]
    public void TestOptions()
    {
        // won't throw
        new {
            PropertyThanLegitimatelyCanBeAnEmptyStringButNotNull = "",
        }.NotEmpty(new AssertOptions {
            AllowEmptyStrings = true,
        });

        //won't throw
        new {
            PropertyThanLegitimatelyCanBeAnEmptyCollectionButNotNull = new int[]{},
        }.NotEmpty(new AssertOptions {
            AllowEmptyCollections = true,
        });

        // won't throw
        new {
            FileContentThatObviouslyContainsSomeNullBytes = new byte[]{ 0 }
        }.NotEmpty(new AssertOptions {
            AllowZerosInNumberArrays = true
        });

        // won't throw BUT will stop at 200 iterations
        // default MaxDepth is 100
        new {
            DeeplyNestedObject = new InfiniteNestedStruct()
        }.NotEmpty(new AssertOptions {
            MaxDepth = 200
        });

        // won't throw
        new ComputedProperty().NotEmpty(new AssertOptions {
            IgnoreComputedProperties = true
        })
    }

    public struct InfiniteNestedStruct
    {
        public int Value { get; set; } = 1;

        public InfiniteNestedStruct Child => new InfiniteNestedStruct { Value = this.Value + 1 };
    }

    public class ComputedProperty
    {
        public int Value => 0;
    }
}