C# 模拟库方法
我最近开始了tdd,但我的模拟知识还不完整。我知道基本知识,但是,一些方法的测试是在没有考虑tdd的情况下编写的,这让我很困惑 这就是我要测试的C# 模拟库方法,c#,unit-testing,mocking,moq,C#,Unit Testing,Mocking,Moq,我最近开始了tdd,但我的模拟知识还不完整。我知道基本知识,但是,一些方法的测试是在没有考虑tdd的情况下编写的,这让我很困惑 这就是我要测试的 public int GetThirdPartyUserId(int serviceTypeId, string accessToken) { ThirdPartyRequestDetail requestDetail = GetThirdPartyRequestDetails(serviceType, accessToken);
public int GetThirdPartyUserId(int serviceTypeId, string accessToken)
{
ThirdPartyRequestDetail requestDetail = GetThirdPartyRequestDetails(serviceType, accessToken);
IHttwrapConfiguration configuration = new HttwrapConfiguration(requestDetail.BaseUrl);
IHttwrapClient httwrap = new HttwrapClient(configuration);
Task<IHttwrapResponse<OpenAuthUserResponse>> response = httwrap.GetAsync<OpenAuthUserResponse>(requestDetail.PathAndQuery);
try
{
if (response.Result.Data != null && response.Status != TaskStatus.Faulted)
{
//Do something
}
else
{
//WANT TO TEST HERE
}
}
}
当httpwrap给我一个错误的请求-响应代码时,我如何测试我的类行为?在它的当前形式中,您不能使用传统的模拟框架来帮助您进行测试。为了使模拟能够工作,您必须
设置生产代码中使用的相同模拟。当前,您在测试中创建的模拟与您的测试方法所依赖的IHttpwrapClient
之间没有任何连接
您需要执行的第一步是将HttpwrapClient
的创建移到要测试的方法之外。然后,您需要通过它的接口将其提供给代码,以便稍后从测试中提供
提供接口有三种常见方式
- 将其注入类的构造函数中
- 通过类上的属性注入它
- 将其作为参数传递给函数
通常,构造函数注入优于属性注入,但主要取决于哪种方法最有效(它们各有优点和缺点),以及什么对注入的数据最有意义
然后,您将创建接口的模拟,并根据需要将其注入到代码中
就生产代码而言,仍然需要创建具体类的实例。您可以在调用类时直接执行此操作,也可以通过工厂之类的方式,或者使用IoC容器,如Castle Winsor或Ninject(还有其他几种)。正如您所说,我将IHttpWrapClient移到了类外,然后我开始模拟该类,一切都很好,谢谢
private Mock<IHttwrapClient> _httpwrap;
public void httprwapTest()
{
string accessToken = "invalid";
int thirdPartySiteId = (int)ThirdPartyServiceType.GooglePlus;
string requestPath = _fixture.Create<string>();
_httpwrap.Setup(item => item.GetAsync(requestPath)).Returns(Task.FromResult(new HttwrapResponse(HttpStatusCode.BadRequest, "body")));
OpenAuthUserResponse response = _oauthAuthenticator.GetThirdPartyUser(thirdPartySiteId, accessToken);
Assert.AreEqual(response.Error, OauthAuthenticatorErrorType.RequestFaulted);
}
_httpwrap.Setup(item => item.GetAsync(requestPath)).Returns(Task.FromResult(new HttwrapResponse(HttpStatusCode.BadRequest, "body")));