任务中的单元测试异步调用.WhenAll返回null (System.NullReferenceException).&



我在一个方法中有一个任务,看起来像这样:

public async Task<List<SomeType>> GetAnotherThing()
{
var someTask = someList.Select(async anotherList => 
{
var someAsyncCall = await this.Provider.GetMeSomething()
// More code here that uses the result
}
await Task.WhenAll(someTask);
// more code here doing more stuff
}

然后我有一个测试方法

public async Task BusinessLogic_GetAnotherThing()
{
// bunch of code here
WhateverType someExpectedResult= new WhateverType
{
// more data here
};
IProvider provider = MockRepository.GenerateMock<IProvider>();
Provider
.Expect(x => x.GetMeSomething())
.Return(Task.FromResult(someExpectedResult));
}
SomeOtherType businessLogic = new SomeOtherType();
businessLogic.Provider = provider;
var actualGetAnotherThing = await businessLogic.GetAnotherThing();
// more code
}

当运行测试方法时,我得到经典的"system . nullreferenceexception"。它说var someAsyncCall = await this.Provider.GetMeSomething()返回null。

在我将这个调用封装在Task.WhenAll中等待它的Task中之前,在单元测试中一切正常。我不知道出了什么问题。

答案是添加"Repeat.Any()",

IProvider provider = MockRepository.GenerateMock<IProvider>();
Provider
.Expect(x => x.GetMeSomething())
.Return(Task.FromResult(someExpectedResult)).Repeat.Any();

相关内容

最新更新