我有一个Microsoft.Net.Http用于检索一些Json数据的服务.大!
当然,我不希望我的单元测试击中实际的服务器(否则,这是一个集成测试).
这是我的服务ctor(使用依赖注入......)
public Foo(string name, HttpClient httpClient = null)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我不知道我怎么可以......比如嘲笑这个.. Moq或FakeItEasy.
我想确保当我的服务电话GetAsync或PostAsync..然后我可以伪造这些电话.
有什么建议我怎么做?
我希望 - 我不需要制作我自己的Wrapper ..因为这是废话:(微软不能对此进行疏忽,对吧?
(是的,它很容易制作包装..我之前已经完成了它们......但这是重点!)
我在我的代码中遇到WebApi抛出异常的问题:
public class WebApiAuthenticationHandler : DelegatingHandler
{
private const string AuthToken = "AUTH-TOKEN";
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var requestAuthTokenList = GetRequestAuthTokens(request);
if (ValidAuthorization(requestAuthTokenList))
{
// EXCEPTION is occuring here!....
return base.SendAsync(request, cancellationToken);
}
/*
** This will make the whole API protected by the API token.
** To only protect parts of the API then mark controllers/methods
** with the Authorize attribute and always return this:
**
** return base.SendAsync(request, cancellationToken);
*/
return Task<HttpResponseMessage>.Factory.StartNew(
() …Run Code Online (Sandbox Code Playgroud) 我创建了2个项目:
我做的是我添加了我的自定义消息处理程序,派生自DelegatingHandler它们.这里是:
public class MyHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken);
}
}
Run Code Online (Sandbox Code Playgroud)
我global.asax在两者中注册了它:
GlobalConfiguration.Configuration.MessageHandlers.Add(new MyHandler());
Run Code Online (Sandbox Code Playgroud)
我把断点放进去了
return base.SendAsync(request, cancellationToken);
Run Code Online (Sandbox Code Playgroud)
ASP.NET MVC和ASP.NET WebAPI之间的区别在于,当我调用ASP.NET MVC application(http://localhost:4189/Something)时,不会触发断点.当我调用Web API(http://localhost:7120/api/values)时,会触发断点.
这是为什么?这些应用程序类型执行流程是否有任何差异?
另外,当我尝试请求正常Controller而不是ApiControllerWebAPI应用程序时,不会触发http://localhost:7120/Home断点.