我有一个具体的课程CalculatorService
我要测试CalculateBuyOrder()
方法。 CalculatorService
有几个依赖项通过构造函数参数注入,CalculateBuyOrder()
调用同一服务上的另一个方法。
我需要一个
类的模拟这似乎是一个显而易见的基本用例,但我似乎既不会弄清楚自己,也不会找到解释它的文档。我得到的最远的是使用AutoMocker来达到1.但是2.让我难过。
public class CalculatorService
: ICalculatorService
{
private readonly IMainDbContext _db;
private readonly TradeConfig _tradeConfig;
private readonly MainConfig _config;
private readonly StateConfig _state;
private readonly ICurrencyService _currencyService;
private readonly IExchangeClientService _client;
// Parameters need to be mocked
public CalculatorService(MainDbContext db, TradeConfig tradeConfig, MainConfig config, StateConfig state, ICurrencyService currencyService, IExchangeClientService client)
{
this._db = db;
this._tradeConfig = tradeConfig;
this._config = config;
this._state = state;
this._currencyService = currencyService;
this._client = client;
}
// This needs to be tested
public async Task<OrderDto> CalculateBuyOrder(
String coin,
CoinPriceDto currentPrice,
Decimal owned,
IDictionary<TradeDirection, OrderDto> lastOrders,
OrderDto existingOrder = null,
TradeConfig.TradeCurrencyConfig tradingTarget = null,
Decimal? invested = null)
{
// ...
this.GetInvested();
// ...
}
// This needs to be mocked
public virtual IDictionary<String, Decimal> GetInvested()
{
// ...
}
}
}
答案 0 :(得分:1)
正如一些评论所说,你应该在构造函数中放置接口,例如伪代码:
GoogleApiClient
注意构造函数中的所有参数都是接口。 然后你的测试方法看起来有点像这样
public class Foo : IFoo
{
IBoo boo;
IGoo goo;
public Foo(IBoo boo, IGoo goo)
{
this.boo = boo;
this.goo = goo;
}
public int MethodToTest(int num1,int num2)
{
//some code
/*..*/ = boo.Method(num1,num2);
//more code and return
}
}
有关详细信息,请转到此链接Moq Github。
现在问题的第二部分,在同一个类中模拟一个方法。这挫败了嘲弄的目的,因为嘲弄&#34;假的&#34;依赖。因此,要么重新构建代码,以便您可以正确地模拟它,要么确保它调用的任何方法都以他们提供可用的可靠输出的方式进行模拟。