【发布时间】:2018-11-29 21:57:46
【问题描述】:
我正在使用flurl,我正在尝试对下面的代码进行单元测试:
public class MyRestClient
{
public async Task<T> Request<T>(IFlurlRequest flurlRequest)
{
try
{
return await flurlRequest
.WithOAuthBearerToken("my-hardcoded-token")
.GetAsync()
.ReceiveJson<T>();
}
catch(HttpFlurlException)
{
throw new MyCustomException();
}
}
}
我要测试的是,如果flurlRequest 抛出HttpFlurlException 类型的异常,那么它将抛出MyCustomException。我的想法是最小起订量 flurlrequest 并抛出异常。这就是我布置测试的方式:
var moq = Substitute.For<IFlurlRequest>();
// Problem is with line below:
moq.When(x => x.WithOAuthBearerToken("dummy")).Do(x => { throw new HttpFlurlException(); } );
var myClient = new MyRestClient();
Func<Task> call = async () => { await myClient.Request<object>(moq); };
// FluentAssertions
call.Should().Throw<MyCustomException>();
代码运行时返回 NullReferenceException:
Exception has occurred: CLR/System.NullReferenceException
An exception of type 'System.NullReferenceException' occurred in
Flurl.Http.dll but was not handled in user code: 'Object reference not
set to an instance of an object.'
at Flurl.Http.HeaderExtensions.WithHeader[T](T clientOrRequest, String name, Object value)
所以我看到它与标题有关......所以我也尝试通过添加来模拟它:
var moq = Substitute.For<IFlurlRequest>();
moq.Headers.Returns(new Dictionary<string, object> { {"dummy", new {} };
但我经常遇到同样的异常。我究竟做错了什么?
【问题讨论】:
标签: c# mocking xunit nsubstitute flurl