我正在使用 NSubstitute 来模拟我的一个类/接口。我的类实现的函数之一应该返回一个 List 类型的对象。但是当我尝试使用 _mockedObject.MyFunction().Returns(myList) 时,它给我一个错误,说我无法在 List 和 Func 类型的对象之间进行转换。我想我可以使用一些 ToString() 函数将我的列表作为字符串传递并将其转换回来?但这似乎不是特别干净,因为我期望从我的函数中返回一个列表。我从有关使用依赖注入进行单元测试的视频中看到,您可以使用 Moq 从模拟对象返回对象,如果我无法使用 NSubstitute 返回对象,我正在考虑切换到该方法。
1 回答
慕容708150
TA贡献1831条经验 获得超4个赞
List<string>下面是如何从 NSubstitute 模拟的对象返回 a 的示例:
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());
}
}
您所描述的错误听起来像是涉及不同类型。
- 1 回答
- 0 关注
- 55 浏览
添加回答
举报
0/150
提交
取消