简体   繁体   中英

Unit Test for Task method with dependency injection

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

1> Interface

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

2> Contracts (Implementation of Interface)

  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.

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();
        }

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM