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

1
2
3
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

1
2
3
4
5
6
7
8
9
fooServiceMock
    .Setup(_ => _.FooMethodAsync(It.IsAny<string>()))
    .ReturnsAsync(new List<FooModel> 
    {
        new FooModel
        {
            fooProperty = "foo"
        }
    }.AsReadOnly());
comments powered by Disqus