我如何从用 NSubstitute 模拟的对象中 return 一个对象(即 List<string>)?

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

我正在使用 NSubstitute 来模拟我的 classes/interfaces 之一。我的class实现的功能之一应该是return一个List类型的对象。

但是当我尝试使用 _mockedObject.MyFunction().Returns(myList) 时,它给我一个错误,提示我无法在我的列表和 Func 类型的对象之间进行转换。

我想我可以使用一些 ToString() 函数将我的列表作为字符串传递并将其转换回来?但这似乎不是特别干净,因为我希望从我的函数中返回一个列表。

我从有关使用依赖注入进行单元测试的视频中看到,您可以使用 Moq (https://www.youtube.com/watch?v=DwbYxP-etMY) 从模拟对象中 return 个对象。如果我无法使用 NSubstitute return 一个对象,我正在考虑切换到那个。

这里是如何从 NSubstitute 模拟的对象 return 一个 List<string> 的例子:

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());
    }
}

您描述的错误听起来涉及不同的类型。希望上面的示例将有助于显示问题的根源,但如果没有,请 post _mockedObject 接口示例和测试(如@jpgrassi 的评论中所建议)。