【发布时间】:2012-09-04 21:40:48
【问题描述】:
我正在尝试验证特定的 CancellationTokenSource 是否用作方法调用中的实际参数。
public void DataVerification(Object sender, EventArgs e)
{
_entity.PopulateEntityDataVerificationStage(_view.DataTypeInputs, _view.ColumnNameInputs, _view.InitialRow, _view.FinalRow, _view.CurrencyPair, _view.CsvFilePath, _view.ErrorLogFilePath);
//...
CancellationTokenSource tempCsvFileVerificationCancellation = new CancellationTokenSource();
_source.Source = tempCsvFileVerificationCancellation;
//Want to verify that TempCsvFileVerificationCancellation.Token is passed into the following method.
_verify.SetupCsvFileVerification(_entity, tempCsvFileVerificationCancellation.Token);
//...
}
以下是我的测试:
[Test]
public void DataVerification_SetupCsvFileVerification_CorrectInputs()
{
Mock<IMainForm> view = new Mock<IMainForm>();
Mock<IUserInputEntity> entity = new Mock<IUserInputEntity>();
Mock<ICsvFileVerification> verify = new Mock<ICsvFileVerification>();
verify.Setup(x => x.SetupCsvFileVerification(It.IsAny<UserInputEntity>(), It.IsAny<CancellationToken>()));
CancellationTokenSource cts = new CancellationTokenSource();
Mock<ICancellationTokenSource> source = new Mock<ICancellationTokenSource>();
source.SetupSet(x => x.Source = It.IsAny<CancellationTokenSource>()).Callback<CancellationTokenSource>(value => cts = value);
source.SetupGet(x => x.Source).Returns(cts);
source.SetupGet(x => x.Token).Returns(cts.Token);
MainPresenter presenter = new MainPresenter(view.Object, entity.Object, verify.Object, source.Object);
presenter.DataVerification(new object(), new EventArgs());
verify.Verify(x => x.SetupCsvFileVerification(entity.Object, source.Object.Token));
}
报错信息如下:
预期至少对模拟调用一次,但从未执行过:x => x.SetupCsvFileVerification(.entity.Object, (Object).source.Object.Token) 未配置任何设置。
source代表的类如下:
public interface ICancellationTokenSource
{
void Cancel();
CancellationTokenSource Source { get; set; }
CancellationToken Token { get; }
}
public class CancellationTokenSourceWrapper : ICancellationTokenSource
{
private CancellationTokenSource _source;
public CancellationTokenSourceWrapper(CancellationTokenSource source)
{
_source = source;
}
public CancellationTokenSource Source
{
get
{
return _source;
}
set
{
_source = value;
}
}
public CancellationToken Token
{
get
{
return Source.Token;
}
}
public void Cancel()
{
_source.Cancel();
}
}
当我逐步完成单元测试时,cts 确实被分配了 TempCsvFileVerificationCancellation 的值。 source 中的 Token 属性,返回 Source.Token。我不知道我做错了什么。
任何指针/帮助将不胜感激。
谢谢
编辑
【问题讨论】:
-
您似乎没有使用 DataVerification 方法向您的类提供验证对象,并且在测试中不清楚您如何创建调用验证的验证模拟,以及哪个然后抛出异常。
-
嗨,大卫,你绝对正确,我曾尝试将其剪裁一点以使其更易于理解,但意外删除了验证,对此感到抱歉。我已经编辑了代码,现在应该可以了。
标签: c# c#-4.0 moq cancellationtokensource