关于nUnit/nMock/单元测试方面的问题:
我正在尝试对这个类进行单元测试。
我创建了一个模拟对象,因为我想知道“getCurrencyRates”返回的值,以便可以基于这些数据创建测试。
所以我创建了一个对象的模拟(仅为了知道返回的汇率)。
...但是现在我还想调用该类的其他一些方法。
我应该:
a) 从模拟对象中以某种方式调用真实方法(不确定是否可能)
b) 重新设计,使只有网络服务调用自己的对象,并创建该对象的模拟
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);
}
}