一个 nUnit / nMock / 单元测试新手问题的位:
我正在尝试对此类进行单元测试。
我创建了一个模拟,因为我想知道从“getCurrencyRates”返回的值,以便我可以基于该数据创建测试。
所以我创建了这个对象的模拟(只是为了能够知道返回的汇率)。
...但现在我也想调用这个类的一些其他方法。
我是不是该:
a) 以某种方式从模拟对象调用真实方法(甚至不确定这是否可能)b) 重构以便只有 Web 服务调用在它自己的对象中并创建一个模拟 c) 其他东西?
public class CurrencyConversion : ICurrencyConversion
{
public decimal convertCurrency(string fromCurrency, string toCurrency, decimal amount)
{
CurrencyRateResponse rates = getCurrencyRates();
var fromRate = getRate(rates, fromCurrency);
var toRate = getRate(rates, toCurrency);
decimal toCurrencyAmount = toRate / fromRate * amount;
return toCurrencyAmount;
}
public int addNumbers(int i, int j)
{
return i + j;
}
public decimal getRate(CurrencyRateResponse rates, string fromCurrency)
{
if (rates.rates.ContainsKey(fromCurrency))
{
return rates.rates[fromCurrency];
}
else
{
return 0;
}
}
public CurrencyRateResponse getCurrencyRates()
{
HttpWebRequest webRequest = GetWebRequest("http://openexchangeerates.org/latest.json");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
}
var serializer = new JavaScriptSerializer();
CurrencyRateResponse rateResponse = serializer.Deserialize<CurrencyRateResponse>(jsonResponse);
return rateResponse;
}
public HttpWebRequest GetWebRequest(string formattedUri)
{
// Create the request’s URI.
Uri serviceUri = new Uri(formattedUri, UriKind.Absolute);
// Return the HttpWebRequest.
return (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
}
}