How to create an empty or with one element IReadOnlyCollection for your unit-tests

When using the Moq framework for mocking your C# classes, you will have do define what dummy value or values a method of the mocked classes returns. For that we use the Setup method and in the Returns method we define the returned value. The question now is, which dummy value to return when your methods return a IReadOnlyCollection collection.

Return an empty array

fooServiceMock
    .Setup(_ => _.FooMethod(It.IsAny<string>()))
    .Returns(Array.Empty<FooModel>);

If the mocked method runs asynchronously, then we use the ReturnsAsync method.

Return an IReadOnlyCollection with one item

fooServiceMock
    .Setup(_ => _.FooMethodAsync(It.IsAny<string>()))
    .ReturnsAsync(new List<FooModel> 
    {
        new FooModel
        {
            fooProperty = "foo"
        }
    }.AsReadOnly());
comments powered by Disqus