Stevens Qiu
Stevens Qiu

Reputation: 138

How can I return an object (ie. List<string>) from an object mocked with NSubstitute?

I am using NSubstitute to mock one of my classes/interfaces. One of the functions implemented by my class should return an object of type List.

But when I try to use _mockedObject.MyFunction().Returns(myList), it gives me an error saying I cannot convert between my List and an object of type Func.

I figured I could pass my list as a string using some ToString() function and convert it back? But that doesn't seem particularly clean as I'm expecting a list to come back from my function.

I saw from a video on Unit Testing with Dependency Injection that you can return objects from mocked objects with Moq (https://www.youtube.com/watch?v=DwbYxP-etMY). I am considering switching to that if I can't manage to return an object with NSubstitute.

Upvotes: 3

Views: 2189

Answers (1)

David Tchepak
David Tchepak

Reputation: 10464

Here is an example of how to return a List<string> from an object mocked by NSubstitute:

using System.Collections.Generic;
using NSubstitute;
using Xunit;

public interface ISomeType {
    List<string> MyFunction();
}

public class SampleFixture {
    [Fact]
    public void ReturnList() {
        var _mockedObject = Substitute.For<ISomeType>();
        var myList = new List<string> { "hello", "world" };

        _mockedObject.MyFunction().Returns(myList);

        // Checking MyFunction() now stubbed correctly:
        Assert.Equal(new List<string> { "hello", "world" }, _mockedObject.MyFunction());
    }
}

The error you have described sounds like there are different types involved. Hopefully the above example will help show the source of the problem, but if not please post an example of the _mockedObject interface and the test (as suggested in @jpgrassi's comment).

Upvotes: 2

Related Questions