本文整理汇总了C#中Mock.Verify方法的典型用法代码示例。如果您正苦于以下问题:C# Mock.Verify方法的具体用法?C# Mock.Verify怎么用?C# Mock.Verify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mock
的用法示例。
在下文中一共展示了Mock.Verify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EmitSummary_Logs_Expected_Messages_With_Valid_Results_That_Has_A_Warning_But_No_Errors
public void EmitSummary_Logs_Expected_Messages_With_Valid_Results_That_Has_A_Warning_But_No_Errors()
{
// Arrange
var loggerMock = new Mock<ILog>();
ConsoleEmitter.SetLogger(loggerMock.Object);
var expectedCompiledCode = "CompiledCode" + Guid.NewGuid();
var compilerResults = new CompilerResults
{
OutputFilePath = string.Empty,
Errors = null,
Warnings = new List<CompilerError>
{
new CompilerError
{
Lineno = 0,
Type = string.Empty,
Error = string.Empty,
Line = string.Empty,
}
},
CompiledCode = expectedCompiledCode,
};
var emitter = new ConsoleEmitter();
// Act
emitter.EmitSummary(compilerResults);
// Assert
loggerMock.Verify(m => m.Info(It.Is<string>(s => s == "----------------------------")), Times.Exactly(2));
loggerMock.Verify(m => m.Info(It.Is<string>(s => s == "Code Emitted:")), Times.Once);
loggerMock.Verify(m => m.Info(It.Is<string>(s => s == expectedCompiledCode)), Times.Once);
loggerMock.Verify(m => m.Info(It.Is<string>(s => s.Contains("1 Warnings"))), Times.Once);
}
示例2: CallTest
public void CallTest()
{
//Arrange
var domainStatProjectState1 = new DomainStatProjectState() { Producer = ProductName.TaggerIPhone, IsSuccessfulUpload = true };
var domainStatProjectState2 = new DomainStatProjectState() { Producer = ProductName.TaggerIPhone, IsSuccessfulUpload = false };
var domainStatProjectState3 = new DomainStatProjectState() { Producer = "ProductName", IsSuccessfulUpload = true };
var domainReport = new DomainReport();
var statProjectDeletionFilter = new Mock<IStatProjectDeletionFilter>();
var taggerIPhoneDeletionsFilter = new TaggerIPhoneDeletionsFilter();
taggerIPhoneDeletionsFilter.Set(statProjectDeletionFilter.Object);
//Act
taggerIPhoneDeletionsFilter.Call(domainStatProjectState1, domainReport);
taggerIPhoneDeletionsFilter.Call(domainStatProjectState2, domainReport);
taggerIPhoneDeletionsFilter.Call(domainStatProjectState3, domainReport);
//Assert
Assert.AreEqual(1, domainReport.TaggerIPhoneDeletions);
statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState1, domainReport), Times.Once());
statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState2, domainReport), Times.Once());
statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState3, domainReport), Times.Once());
}
示例3: ExecuteAsync_calls_Commit_if_no_transaction
public async Task ExecuteAsync_calls_Commit_if_no_transaction()
{
var mockModificationCommandBatch = new Mock<ModificationCommandBatch>();
mockModificationCommandBatch.Setup(m => m.ModificationCommands.Count).Returns(1);
var mockRelationalConnection = new Mock<IRelationalConnection>();
var transactionMock = new Mock<IDbContextTransaction>();
IDbContextTransaction currentTransaction = null;
mockRelationalConnection.Setup(m => m.BeginTransaction()).Returns(() => currentTransaction = transactionMock.Object);
mockRelationalConnection.Setup(m => m.CurrentTransaction).Returns(() => currentTransaction);
var cancellationToken = new CancellationTokenSource().Token;
var batchExecutor = new BatchExecutor();
await batchExecutor.ExecuteAsync(new[] { mockModificationCommandBatch.Object }, mockRelationalConnection.Object, cancellationToken);
mockRelationalConnection.Verify(rc => rc.OpenAsync(cancellationToken));
mockRelationalConnection.Verify(rc => rc.Close());
transactionMock.Verify(t => t.Commit());
mockModificationCommandBatch.Verify(mcb => mcb.ExecuteAsync(
It.IsAny<IRelationalConnection>(),
cancellationToken));
}
示例4: TestBenchmarkClass1
public void RunBenchmarks_Should_LogExceptionsButNotResults_When_ClassAndMethodNameSpecifiedAndExceptionsAreThrown()
{
var assemblyInterrogator = new Mock<AssemblyInterrogator>();
assemblyInterrogator.Setup(p => p.AssemblyName).Returns("TestBenchmark.dll");
var items = new List<Object>();
var testObject = new TestBenchmarkClass1();
testObject.TestBenchy2ThrowException = true;
items.Add(testObject);
string errors;
assemblyInterrogator.Setup(p => p.PopulateItemsToBench(out errors)).Returns(true);
assemblyInterrogator.Setup(p => p.ItemsToBench).Returns(items);
var outputWriter = new Mock<OutputWriter>();
var processStarter = new Mock<ProcessStarterFactory>();
var target =
new BenchmarkExecuter(
new Settings
{BuildLabel = "Build1", BenchmarkClass = "TestBenchmarkClass1", BenchmarkMethod = "TestBenchy2"},
assemblyInterrogator.Object, outputWriter.Object, processStarter.Object);
bool result = target.RunBenchmarks(out errors);
Assert.IsFalse(result);
Assert.IsTrue(testObject.SetUpCalled);
Assert.IsTrue(testObject.TearDownCalled);
Assert.IsFalse(testObject.TestBenchy1Called);
Assert.IsTrue(testObject.TestBenchy2Called);
outputWriter.Verify(o => o.WriteResults("TestBenchy2", "Build1", It.IsAny<long>()), Times.Never());
outputWriter.Verify(o => o.WriteError(It.IsAny<string>(), "TestBenchy2", "Build1"), Times.Once());
}
示例5: ExecuteAsync_does_not_call_Commit_if_existing_transaction
public async Task ExecuteAsync_does_not_call_Commit_if_existing_transaction()
{
var sqlGenerator = new Mock<IUpdateSqlGenerator>().Object;
var mockModificationCommandBatch = new Mock<ModificationCommandBatch>(sqlGenerator);
mockModificationCommandBatch.Setup(m => m.ModificationCommands.Count).Returns(1);
var mockRelationalConnection = new Mock<IRelationalConnection>();
var transactionMock = new Mock<IRelationalTransaction>();
mockRelationalConnection.Setup(m => m.Transaction).Returns(transactionMock.Object);
var cancellationToken = new CancellationTokenSource().Token;
var relationalTypeMapper = new ConcreteTypeMapper();
var batchExecutor = new BatchExecutorForTest(relationalTypeMapper);
await batchExecutor.ExecuteAsync(new[] { mockModificationCommandBatch.Object }, mockRelationalConnection.Object, cancellationToken);
mockRelationalConnection.Verify(rc => rc.OpenAsync(cancellationToken));
mockRelationalConnection.Verify(rc => rc.Close());
mockRelationalConnection.Verify(rc => rc.BeginTransaction(), Times.Never);
transactionMock.Verify(t => t.Commit(), Times.Never);
mockModificationCommandBatch.Verify(mcb => mcb.ExecuteAsync(
It.IsAny<IRelationalTransaction>(),
relationalTypeMapper,
It.IsAny<DbContext>(),
null,
cancellationToken));
}
示例6: Test_PatternCreator_GetEmbroidery
public void Test_PatternCreator_GetEmbroidery()
{
var mockCanvasConverter = new Mock<ICanvasConverter>();
var mockPatternMapGenerator = new Mock<IPatternMapGenerator>();
var mockDecoratorCompositions = new Mock<IDecoratorsComposition>();
mockPatternMapGenerator.Setup(map => map.Generate(It.IsAny<Canvas>(), It.IsAny<Settings>())).Returns(new Canvas(3, 3));
mockCanvasConverter.Setup(conv => conv.ConvertBitmapToCanvas(It.IsAny<Bitmap>())).Returns(new Canvas(4, 3));
mockDecoratorCompositions.Setup(decor => decor.Decorate(It.IsAny<Canvas>(), It.IsAny<Canvas>(), It.IsAny<Settings>()));
Settings settings = new Settings();
settings.CellsCount = 3;
settings.Coefficient = 2;
settings.Palette = new Palette(new Color[]{Color.Red, Color.Blue});
settings.DecoratorsComposition = mockDecoratorCompositions.Object;
EmbroideryCreator creator = new EmbroideryCreator();
creator.CanvasConverter = mockCanvasConverter.Object;
creator.PatternMapGenerator = mockPatternMapGenerator.Object;
Bitmap image = new Bitmap(4, 3);
creator.GetEmbroidery(image, settings);
mockCanvasConverter.Verify(conv => conv.ConvertBitmapToCanvas(image));
mockPatternMapGenerator.Verify(pat => pat.Generate(It.IsAny<Canvas>(), settings));
mockDecoratorCompositions.Verify(decor => decor.Decorate(It.IsAny<Canvas>(), It.IsAny<Canvas>(), settings));
mockCanvasConverter.Verify(conv => conv.ConvertCanvasToBitmap(It.IsAny<Canvas>()));
}
示例7: InitializationOfAmqpStuff
public void InitializationOfAmqpStuff()
{
const String queueName = "queue_name";
const String exchangeName = "exchange_name";
const String routingKey = "routing_key";
var configuration = new EnvironmentConfiguration();
configuration.Endpoint(new Uri("amqp://localhost:5672"));
configuration.GeneratesMessageIdBy(new Mock<INewId>().Object);
configuration.ResolveMessageTypeBy(new Mock<IMessageTypeResolver>().Object);
var model = new Mock<IModel>();
var connectionBuilder = StubConnectionBuilder(model);
var broker = new BrokerWrapper(connectionBuilder.Object, model.Object, configuration);
var consumer = new FakeConsumer(_ => Task.Factory.StartNew(() => { }));
var queue = broker.DeclareQueue(queueName);
var exchange = broker.DeclareDirectExchange(exchangeName);
broker.DeclareExchangeBinding(exchange, queue, routingKey);
broker.SubscribeByAtLeastOnce(queue, _ => { _.Consumes(consumer); });
broker.Connect();
model.Verify(_ => _.QueueDeclare(queueName,
false,
false,
false,
It.IsAny<IDictionary<String, Object>>()));
model.Verify(_ => _.ExchangeDeclare(exchangeName,
"direct",
false,
false,
It.IsAny<IDictionary<String, Object>>()));
model.Verify(_ => _.QueueBind(queueName,
exchangeName,
routingKey,
It.IsAny<IDictionary<String, Object>>()));
}
示例8: GetIpAddress_DnsEntry_NoDeadlock
public void GetIpAddress_DnsEntry_NoDeadlock()
{
// Using an asynchronous view query within an MVC Web API action causes
// a deadlock if you wait for the result synchronously.
var context = new Mock<SynchronizationContext>
{
CallBase = true
};
SynchronizationContext.SetSynchronizationContext(context.Object);
try
{
var uri = new Uri("http://localhost/");
uri.GetIpAddress(false);
// If view queries are incorrectly awaiting on the current SynchronizationContext
// We will see calls to Post or Send on the mock
context.Verify(m => m.Post(It.IsAny<SendOrPostCallback>(), It.IsAny<object>()), Times.Never);
context.Verify(m => m.Send(It.IsAny<SendOrPostCallback>(), It.IsAny<object>()), Times.Never);
}
finally
{
SynchronizationContext.SetSynchronizationContext(null);
}
}
示例9: TestWithChannelListener
public void TestWithChannelListener()
{
var mockConnectionFactory = new Mock<ConnectionFactory>();
var mockConnection = new Mock<IConnection>();
var mockChannel = new Mock<IModel>();
mockConnectionFactory.Setup(factory => factory.CreateConnection()).Returns(mockConnection.Object);
mockConnection.Setup(c => c.IsOpen).Returns(true);
mockConnection.Setup(connection => connection.CreateModel()).Returns(mockChannel.Object);
var called = new AtomicInteger(0);
var connectionFactory = this.CreateConnectionFactory(mockConnectionFactory.Object);
var channelListeners = new List<IChannelListener>();
var mockChannelListener = new Mock<IChannelListener>();
mockChannelListener.Setup(listener => listener.OnCreate(It.IsAny<IModel>(), It.IsAny<bool>())).Callback(() => called.IncrementValueAndReturn());
channelListeners.Add(mockChannelListener.Object);
connectionFactory.ChannelListeners = channelListeners;
var con = connectionFactory.CreateConnection();
var channel = con.CreateChannel(false);
Assert.AreEqual(1, called.Value);
channel.Close();
con.Close();
mockConnection.Verify(c => c.Close(), Times.Never());
connectionFactory.CreateConnection();
con.CreateChannel(false);
Assert.AreEqual(2, called.Value);
connectionFactory.Dispose();
mockConnection.Verify(c => c.Close(), Times.AtLeastOnce());
mockConnectionFactory.Verify(c => c.CreateConnection());
}
示例10: ShouldCopyFilesInPathIfLastWriteTimeDiffersFromLastWriteTimeOfFileInBin
public void ShouldCopyFilesInPathIfLastWriteTimeDiffersFromLastWriteTimeOfFileInBin()
{
var args = new ScriptCsArgs { Restore = true, ScriptName = "" };
var fs = new Mock<IFileSystem>();
var resolver = new Mock<IPackageAssemblyResolver>();
var executor = new Mock<IScriptExecutor>();
var scriptpackResolver = new Mock<IScriptPackResolver>();
var packageInstaller = new Mock<IPackageInstaller>();
var root = new ScriptServiceRoot(fs.Object, resolver.Object, executor.Object, scriptpackResolver.Object, packageInstaller.Object);
const string CurrentDirectory = @"C:\";
var sourceFilePath = Path.Combine(CurrentDirectory, "fileName.cs");
var sourceWriteTime = new DateTime(2013, 3, 7);
var destFilePath = Path.Combine(CurrentDirectory, "bin", "fileName.cs");
var destWriteTime = new DateTime(2013, 2, 7);
fs.Setup(x => x.GetWorkingDirectory(It.IsAny<string>())).Returns(CurrentDirectory);
fs.Setup(x => x.GetLastWriteTime(sourceFilePath)).Returns(sourceWriteTime).Verifiable();
fs.Setup(x => x.GetLastWriteTime(destFilePath)).Returns(destWriteTime).Verifiable();
resolver.Setup(i => i.GetAssemblyNames(CurrentDirectory, It.IsAny<Action<string>>())).Returns(new[] { sourceFilePath });
var factory = new CommandFactory(root);
var result = factory.CreateCommand(args);
result.Execute();
fs.Verify(x => x.Copy(sourceFilePath, destFilePath, true), Times.Once());
fs.Verify(x => x.GetLastWriteTime(sourceFilePath), Times.Once());
fs.Verify(x => x.GetLastWriteTime(destFilePath), Times.Once());
}
示例11: TestCloseInvalidConnection
public void TestCloseInvalidConnection()
{
var mocker = new AutoMoqer();
var mockConnectionFactory = mocker.GetMock<RabbitMQ.Client.ConnectionFactory>();
var mockConnection1 = new Mock<RabbitMQ.Client.IConnection>();
var mockConnection2 = new Mock<RabbitMQ.Client.IConnection>();
mockConnectionFactory.Setup(c => c.CreateConnection()).ReturnsInOrder(mockConnection1.Object, mockConnection2.Object);
// simulate a dead connection
mockConnection1.Setup(c => c.IsOpen).Returns(false);
var connectionFactory = new SingleConnectionFactory(mockConnectionFactory.Object);
var connection = connectionFactory.CreateConnection();
// the dead connection should be discarded
connection.CreateChannel(false);
mockConnectionFactory.Verify(c => c.CreateConnection(), Times.Exactly(2));
mockConnection2.Verify(c => c.CreateModel(), Times.Exactly(1));
connectionFactory.Dispose();
mockConnection2.Verify(c => c.Close(), Times.Exactly(1));
}
示例12: Persister_Can_Successfully_Persist_New_Items_In_Memory
public void Persister_Can_Successfully_Persist_New_Items_In_Memory()
{
var items = this.BuildItems(numberOfFeeds: 10, numberOfTweets: 20);
var oldItem = this.BuildItem(DateTime.MinValue);
var savedItems = new List<Item>();
var fakeStreamAggregator = new Mock<IItemAggregator>();
fakeStreamAggregator.Setup(a => a.GetLatest(DateTime.MinValue)).Returns(items);
var fakeStreamProcessor = new Mock<IItemProcessor>(MockBehavior.Loose);
var fakeStreamStorage = new Mock<IStreamStorage>();
fakeStreamStorage.Setup(s => s.Top()).Returns(oldItem);
fakeStreamStorage.Setup(s => s.Save(It.IsAny<IEnumerable<Item>>())).Callback<IEnumerable<Item>>(savedItems.AddRange);
var streamPersister = new StreamPersister(fakeStreamAggregator.Object, fakeStreamProcessor.Object, fakeStreamStorage.Object);
streamPersister.PersistLatest();
CollectionAssert.AreEquivalent(items, savedItems);
fakeStreamAggregator.Verify(a => a.GetLatest(oldItem.Published), Times.Once());
fakeStreamProcessor.Verify(p => p.Process(It.IsAny<Item>()), Times.Exactly(items.Count));
fakeStreamStorage.Verify(s => s.Top(), Times.Once());
fakeStreamStorage.Verify(s => s.Save(It.IsAny<IEnumerable<Item>>()), Times.Once());
}
示例13: Only_Retrieve_Distributions_Once
public void Only_Retrieve_Distributions_Once()
{
var cloudfrontClient = new Mock<AmazonCloudFront>();
var distributionId = Guid.NewGuid().ToString();
var bucket = Guid.NewGuid().ToString();
var distribution = bucket + ".s3.amazonaws.com";
var key = Guid.NewGuid().ToString();
var listDistributionsResponse = new ListDistributionsResponse();
listDistributionsResponse.Distribution.Add(new CloudFrontDistribution
{
Id = distributionId,
DistributionConfig = new CloudFrontDistributionConfig
{
S3Origin = new S3Origin(distribution, null)
}
});
cloudfrontClient.Setup(cfc => cfc.ListDistributions())
.Returns(listDistributionsResponse);
var invalidator = new CloudFrontInvalidator(cloudfrontClient.Object);
invalidator.InvalidateObject(bucket, key);
invalidator.InvalidateObject(bucket, key);
cloudfrontClient.Verify(cfc => cfc.PostInvalidation(It.Is<PostInvalidationRequest>(pir => pir.DistributionId == distributionId
&& pir.InvalidationBatch.Paths.Count == 1
&& pir.InvalidationBatch.Paths.First() == key)), Times.Exactly(2));
cloudfrontClient.Verify(cfc => cfc.ListDistributions(), Times.Once());
}
示例14: TestILGenerator
public void TestILGenerator()
{
var generator = new ILGenProxyGenerator();
var proxyType = generator.CreateProxy<IAwesomeInterface>();
var instanceMock = new Mock<IAwesomeInterface>();
var proxyHandlerMock = new Mock<IProxyHandler<IAwesomeInterface>>();
var proxy = (IAwesomeInterface) Activator.CreateInstance(proxyType, instanceMock.Object, proxyHandlerMock.Object);
proxy.FaulyCachedMethod();
var proxyRequest1 = ProxyRequest<IAwesomeInterface>.FromExpression(a => a.FaulyCachedMethod());
instanceMock.Verify(a => a.FaulyCachedMethod(), Times.Never());
proxyHandlerMock.Verify(a => a.HandleRequest(proxyRequest1), Times.Once());
proxy.VoidMethod();
instanceMock.Verify(a => a.VoidMethod(), Times.Once());
proxy.ParameteredMethod("", 1);
var proxyRequest2 = ProxyRequest<IAwesomeInterface>.FromExpression(a => a.ParameteredMethod("", 1));
instanceMock.Verify(a => a.ParameteredMethod("", 1), Times.Never());
proxyHandlerMock.Verify(a => a.HandleRequest(proxyRequest2));
}
示例15: Add
public void Add()
{
var lockKey = new DatasetLockKey();
var datasetLock = new Mock<ITrackDatasetLocks>();
{
datasetLock.Setup(d => d.LockForWriting())
.Returns(lockKey)
.Verifiable();
datasetLock.Setup(d => d.RemoveWriteLock(It.IsAny<DatasetLockKey>()))
.Callback<DatasetLockKey>(key => Assert.AreSame(lockKey, key))
.Verifiable();
}
var originalId = new GroupCompositionId();
var originalDefinition = new GroupDefinition("a");
var storage = new Mock<IStoreGroupsAndConnections>();
{
storage.Setup(s => s.Add(It.IsAny<GroupCompositionId>(), It.IsAny<GroupDefinition>()))
.Callback<GroupCompositionId, GroupDefinition>(
(id, def) =>
{
Assert.AreSame(originalId, id);
Assert.AreSame(originalDefinition, def);
});
}
var commands = new CompositionCommands(datasetLock.Object, storage.Object);
var task = commands.Add(originalId, originalDefinition);
task.Wait();
datasetLock.Verify(d => d.LockForWriting(), Times.Once());
datasetLock.Verify(d => d.RemoveWriteLock(It.IsAny<DatasetLockKey>()), Times.Once());
}