我正在尝试为“CheckSomething”方法编写单元测试的方法,但是我很难确定如何处理我在方法中实例化的RestClient对象。
我应该抽象出RestClient,并将Interface依赖项放在类级别并从inint中注入构造函数吗?如果我选择这条路线,这是否意味着我必须将所有依赖关系接口?
public class SomeRepository : IXRepository
{
public SomeRepository()
{
}
public bool CheckSomething()
{
var client = new RestClient("someurl");
var request = new RestRequest("resourceX/{name}", Method.GET);
request.AddUrlSegment("name", "ABC");
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.NotFound) return false;
if (response.StatusCode == HttpStatusCode.OK) return true;
throw new Exception("Something is messed up");
}
}
答案 0 :(得分:2)
如果您不想在SomeRepository中使用类级别的RestClient字段,则可以使用方法注入,并将RestClient参数添加到CheckSomething方法。然后,您可以模拟RestClient进行单元测试。
public bool CheckSomething(RestClient restClient)
{
var request = new RestRequest("resourceX/{name}", Method.GET);
request.AddUrlSegment("name", "ABC");
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.NotFound) return false;
if (response.StatusCode == HttpStatusCode.OK) return true;
throw new Exception("Something is messed up");
}
如果这是我的代码,我想测试以下内容:
如果这是您需要测试的全部内容,那么您需要模拟的唯一内容是RestClient,这意味着您可以轻松地使用方法注入,或构造函数或属性注入。