【发布时间】:2018-12-22 20:18:56
【问题描述】:
在下面的代码中,我有“howmanystringasync”方法,它正在调用另外两个方法。这两个是假的。 由于“.ToList()”,第二个假的返回不起作用。
我通常返回 IEnumerable,因为在某些情况下我想限制调用者的操作。有时,我会直接在输入中询问一个 List,这样一个方法就可以完成 List 所提供的功能。
我怎样才能使下面的测试有效?
var 结果 = 等待 f.AccessTheWebAsync2(web.ToList());
using FakeItEasy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace api.tests.unit
{
public class SpecialString
{
public int IntProperty { get; set; }
public string StringProperty { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as SpecialString);
}
public bool Equals(SpecialString other)
{
if (other == null) return false;
return (this.IntProperty == other.IntProperty) && (this.StringProperty == other.StringProperty);
}
}
public interface IFoo
{
Task<IEnumerable<SpecialString>> AccessTheWebAsync(int a, int b);
Task<int> AccessTheWebAsync2(List<SpecialString> integers);
}
public class Foo : IFoo
{
public async Task<IEnumerable<SpecialString>> AccessTheWebAsync(int a, int b)
{
HttpClient client = new HttpClient();
string result = await client.GetStringAsync("https://msdn.microsoft.com");
var results = new List<SpecialString> {
new SpecialString{
IntProperty = 1,
StringProperty = "stringprop1"
},
new SpecialString{
IntProperty =2,
StringProperty = "stringprop2"
}
};
return results;
}
public async Task<int> AccessTheWebAsync2(List<SpecialString> specialstrings)
{
HttpClient client = new HttpClient();
string result = await client.GetStringAsync("https://msdn.microsoft.com");
var results = new List<SpecialString> {
new SpecialString{
IntProperty = 1,
StringProperty = "stringprop1"
},
new SpecialString{
IntProperty =2,
StringProperty = "stringprop2"
}
};
return results.Count();
}
}
public class BiggerFoo
{
private readonly IFoo f;
public BiggerFoo(IFoo f)
{
this.f = f;
}
public async Task<int> howManyStringsAsync(int a, int b)
{
var web = await f.AccessTheWebAsync(a, b);
var result = await f.AccessTheWebAsync2(web.ToList());
return result;
}
}
public class FooTest
{
[Fact]
public void testasyncmethod()
{
var fakeFoo = A.Fake<IFoo>();
IEnumerable<SpecialString> result = new List<SpecialString> {
new SpecialString{
IntProperty = 1,
StringProperty = "fakestringprop1"
},
new SpecialString{
IntProperty =2,
StringProperty = "fakestringprop2"
}
};
A.CallTo(() => fakeFoo.AccessTheWebAsync(1, 2)).Returns<Task<IEnumerable<SpecialString>>>(Task.FromResult(result));
A.CallTo(() => fakeFoo.AccessTheWebAsync2(result.ToList())).Returns<Task<int>>(Task.FromResult(5));
var bFoo = new BiggerFoo(fakeFoo);
bFoo.howManyStringsAsync(1, 2);
}
}
}
【问题讨论】:
-
用
result.ToList()代替A<IEnumerable<SpecialString>>.Ignored不行吗? -
是的,但根据 API,它必须是
List,而不是IEnumerable。 -
正如@xofz 所说,接口契约需要得到尊重。
标签: c# fakeiteasy