我有一個服務調用包裝函數,它除了在調用中將參數轉發給服務外,什麼也不做。包裝的原因是我們可以使用一個DI容器來包裝注入,因此被模擬進行單元測試。如何在單元測試簡單方法時引發異常
這裏是包裝的樣子
public class WeatherChannelWrapper : IWeatherServiceWrapper
{
public GetLocalWeather(string zipcode)
{
TWCProxy.GetCurrentCondition(zipcode, DateTime.Now.ToString("MM/dd/yyyy hh:mm"));
}
}
一切正常,現在我有一個要求,吞下對TWCProxy的崩潰例外。所以現在我的包裝看起來像這樣。
public class WeatherChannelWrapper : IWeatherServiceWrapper
{
private readonly IExceptionLogger exceptionLogger;
public WeatherChannelWrapper(IExceptionLogger logger)
{
this.exceptionLogger = logger;
}
public GetLocalWeather(string zipcode)
{
try
{
TWCProxy.GetCurrentCondition(zipcode, DateTime.Now.ToString("MM/dd/yyyy hh:mm"));
}
catch (Exception e)
{
exceptionLogger.Log(e);
}
}
}
我必須寫下面的單元測試
- GetLocalWeather()時,內部發生異常
- GetLocalWeather(不崩潰的應用程序)記錄異常
我們測試兩種情況,我需要以某種方式誘發崩潰;我該如何使用NUnit和Automoq/Moq?
好像你要測試通過傳遞一個無效的郵政編碼或任何會導致'TWCProxy.GetCurrentCondition'拋出一個n例外。 – juharr
https://www.bing.com/search?q=c%23%20moq%20throw ...或者你需要澄清你在找什麼。 –
@juharr是的,但這不會是拋出異常的可靠方法。這樣你就可以預測/依賴第三方API的行爲。 – fahadash