1
我是在Visual Studio中編寫單元測試的新手。在我的Web應用程序中,我有以下內容。使用依賴注入的任務方法的單元測試
1>接口
public interface IGettProxy
{
Task<List<CityDetails>> getCity();
Task<List<CountryDetails>> getCountry(int cityId);
}
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>控制器
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; }
}
我對數據成員不同的類庫。
對於注入配置,我使用Unity方法。
因此,在這個觀點中,我已經下降,以約束城市,國家的價值觀。
對於這個下拉式綁定我想寫單元測試。請幫助我瞭解這個細節。提前致謝。
我的測試方法
[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();
}
你想要在你的代碼中進行單元測試?你不知道或者問題在哪裏?也可以按照PascalCase的.net命名約定獲取方法名稱。 –
嗨@SriramSakthivel,謝謝你在我的問題中的表情。我已經更新了我的測試功能。我非常震驚。我不知道我必須做些什麼來實現下拉式綁定。並在實施中使用任務。 –
MVC的想法是你不測試用戶界面。您測試控制器和您使用的其他服務中的業務邏輯。你的測試方法也缺乏斷言。斷言什麼是真/假。我不清楚你不知道什麼。對不起。 –