具有依赖注入的Task方法的单元测试

时间:2022-08-28 11:21:20

I am new to writing Unit Test in visual studio. In my web application i have following contents.

我是视觉工作室中编写单元测试的新手。在我的Web应用程序中,我有以下内容。

1> Interface

public interface IGettProxy
{
    Task<List<CityDetails>> getCity();
    Task<List<CountryDetails>> getCountry(int cityId);
}

2> Contracts (Implementation of Interface)

2>合同(接口的实现)

  public async Task<List<CityDetails>> getCity()
    {
        try
        {

            _serviceUrl = String.Format("{0}/Search/getCityinfo", _serviceUrl);
            string requestUri = _serviceUrl;
            client = new HttpClient();
            var response = await client.GetAsync(requestUri);
            if (response.IsSuccessStatusCode)
            {
                string json = await response.Content.ReadAsStringAsync();
                var Result = new          JavaScriptSerializer().Deserialize<List<CityDetails>>(json);
                return Result;
            }
            else
            {
                throw new Exception("Errorhandling message");
            }
        }
        catch (Exception ex) { throw ex; }
    }


    public async Task<List<CountryDetails>> getCountry(int cityId)
    {
        try
        {
            _serviceUrl = String.Format("{0}/Search/getcountryinfo?cityId={1}", _serviceUrl, cityId);
            string requestUri = _serviceUrl;
            client = new HttpClient();
            var response = await client.GetAsync(requestUri);
            if (response.IsSuccessStatusCode)
            {
                string json = await response.Content.ReadAsStringAsync();
                var Result = new JavaScriptSerializer().Deserialize<List<CountryDetails>>(json);
                return Result;
            }
            else
            {
                throw new Exception("Errorhandling message");
            }
        }
        catch (Exception ex) { throw ex; }
    }

3> Controller

       private IGettProxy igettProxy;

    public GettController(IGettProxy gettProxy)
    {
        igettProxy = gettProxy;
    }

    /// <summary>
    /// Invoked on Page Load
    /// </summary>
    /// <returns></returns>
    public async Task<ActionResult> Getdet()
    { 
        try
        {
            List<CityDetails> cityDetails = await igettProxy.getCity();
            SearchModel viewModel = new SearchModel();
            viewModel.cityDetail = cityDetails;
            return View(viewModel);
        }
        catch (Exception ex) { throw ex; }
    }

    /// <summary>
    /// Get Country list based on city information
    /// </summary>
    /// <param name="cityId"></param>
    /// <returns></returns>
    public async Task<JsonResult> getCountry (int cityId)
    {
        try
        {
            List<CountryDetails> CountryDetails = await iSearchProxy.getCountry(cityId);
            return Json(CountryDetails,JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex) { throw ex; }
    }

I have different class libraries for data member.

我有不同的数据成员类库。

For injection configuration i am using Unity method.

对于注射配置,我使用的是Unity方法。

So in this view i have drop down to bind city, country values.

因此,在这个视图中,我已经下降到绑定城市,国家价值观。

For this drop down binding i want to write unit test. Please help me with this detail. Thanks in advance.

对于这个下拉绑定我想写单元测试。请帮我详细说明。提前致谢。

My Test method

我的测试方法

 [TestMethod]
        public void bookAppointment()
        {

             List<CityDetails> cityDetails = new List<CityDetails>();
             cityDetails.Add(new CityDetails {ID=1,CityName="Delhi"});
          //  var mockproxy = new StubISearchProxy();
            StubISearchProxy searchProxy = new StubISearchProxy();

            searchProxy.GetCity = () =>  cityDetails;

            SearchController searchController = new SearchController(searchProxy);
            var str = searchController.getCity();
        }

1 个解决方案

#1


In DI Unity will resolve this interface implementation for you. In order to test this you'll have to create a fake class that implements your interface, and inject (on the constructor). Something like:

在DI Unity将为您解决此接口实现。为了测试这个,你必须创建一个实现你的接口的假类,并注入(在构造函数上)。就像是:

public class FakeClass : IGettProxy {
public Task<List<CityDetails>> getCity(){
// here goes your fake implementation, to be injected on your controller.
}
// Remember to implement the other method 
}

Then when you instantiate your controller you're going to pass this fake implementation of the interface (that what the constructor requires).

然后,当你实例化你的控制器时,你将传递这个伪造的接口实现(构造函数需要的)。

And now you can test it.

现在你可以测试一下。

#1


In DI Unity will resolve this interface implementation for you. In order to test this you'll have to create a fake class that implements your interface, and inject (on the constructor). Something like:

在DI Unity将为您解决此接口实现。为了测试这个,你必须创建一个实现你的接口的假类,并注入(在构造函数上)。就像是:

public class FakeClass : IGettProxy {
public Task<List<CityDetails>> getCity(){
// here goes your fake implementation, to be injected on your controller.
}
// Remember to implement the other method 
}

Then when you instantiate your controller you're going to pass this fake implementation of the interface (that what the constructor requires).

然后,当你实例化你的控制器时,你将传递这个伪造的接口实现(构造函数需要的)。

And now you can test it.

现在你可以测试一下。