本文整理汇总了C#中Mock类的典型用法代码示例。如果您正苦于以下问题:C# Mock类的具体用法?C# Mock怎么用?C# Mock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Mock类属于命名空间,在下文中一共展示了Mock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetTestableChat
public static TestableChat GetTestableChat(string connectionId, StateChangeTracker clientState, ChatUser user, IDictionary<string, Cookie> cookies)
{
// setup things needed for chat
var repository = new InMemoryRepository();
var resourceProcessor = new Mock<IResourceProcessor>();
var chatService = new Mock<IChatService>();
var connection = new Mock<IConnection>();
var settings = new Mock<IApplicationSettings>();
var mockPipeline = new Mock<IHubPipelineInvoker>();
// add user to repository
repository.Add(user);
// create testable chat
var chat = new TestableChat(settings, resourceProcessor, chatService, repository, connection);
var mockedConnectionObject = chat.MockedConnection.Object;
chat.Clients = new HubConnectionContext(mockPipeline.Object, mockedConnectionObject, "Chat", connectionId, clientState);
var prinicipal = new Mock<IPrincipal>();
var request = new Mock<IRequest>();
request.Setup(m => m.Cookies).Returns(cookies);
request.Setup(m => m.User).Returns(prinicipal.Object);
// setup context
chat.Context = new HubCallerContext(request.Object, connectionId);
return chat;
}
示例2: SetupSubject
protected void SetupSubject()
{
MockUpdatableAuth = new Mock<IUpdatable<UserAuthentication>>();
_passwords = new Passwords();
_translateUserUserAuth = new DataUserToAccountUserTranslator();
_userAuthProvider = new UserAuthenticationProvider(
_translateUserUserAuth
, MockRetrievableUserByEmail.Object
, MockRetrievableAuthyId.Object
, MockUpdatableAuth.Object
, MockCreatableAuth.Object
, _passwords
, MockDeletableAuth.Object);
Subject = new UserAccountProvider(
_userAuthProvider
, MockCreateableUser.Object
, MockRetrievableUserById.Object
, MockRetrievableUserByEmail.Object
, MockDeletableUser.Object
, MockUpdateableUser.Object
, _translateUserUserAuth
, MockSystemTime.Object);
}
开发者ID:ServiceManagementGroup,项目名称:IntegrationTestTraining,代码行数:26,代码来源:Advanced_UserAccountProvider_tests.cs
示例3: GetAllShouldReturnTodos
public void GetAllShouldReturnTodos()
{
var data = new List<Todo>
{
new Todo {Id = 1},
new Todo {Id = 2},
new Todo {Id = 3},
}.AsQueryable();
var mockSet = new Mock<DbSet<Todo>>();
mockSet.As<IQueryable<Todo>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Todo>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Todo>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Todo>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var mockContext = new Mock<ApplicationDbContext>();
mockContext.Setup(c => c.Todos).Returns(mockSet.Object);
var service = new TodoRepository(mockContext.Object);
var todos = service.GetAll().ToList();
Assert.AreEqual(3, todos.Count);
Assert.AreEqual(1, todos[0].Id);
Assert.AreEqual(2, todos[1].Id);
Assert.AreEqual(3, todos[2].Id);
}
示例4: 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());
}
示例5: IsInvalidWhen_UserName_MatchesExistingUser
public void IsInvalidWhen_UserName_MatchesExistingUser()
{
const string userName = "[email protected]";
const string userDisplayName = "Bruce Wayne";
const string personDisplayName = "Adam West";
var command = new CreatePersonCommand
{
DisplayName = personDisplayName,
UserName = userName,
};
var queryProcessor = new Mock<IProcessQueries>(MockBehavior.Strict);
queryProcessor.Setup(m => m.Execute(It.Is<GetUserByNameQuery>(q => q.Name == command.UserName)))
.Returns(new User { Person = new Person { DisplayName = userDisplayName, } });
var validator = new CreatePersonValidator(queryProcessor.Object);
var results = validator.Validate(command);
results.IsValid.ShouldBeFalse();
results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
var error = results.Errors.SingleOrDefault(e => e.PropertyName == "UserName");
error.ShouldNotBeNull();
// ReSharper disable PossibleNullReferenceException
error.ErrorMessage.ShouldEqual(string.Format(
ValidateUser.FailedBecauseNameMatchedEntity,
userName));
// ReSharper restore PossibleNullReferenceException
}
示例6: TestInitialize
public void TestInitialize()
{
IFhirModel _fhirModel;
FhirPropertyIndex _propIndex;
ResourceVisitor _resourceVisitor;
ElementIndexer _elementIndexer;
var _indexStoreMock = new Mock<IIndexStore>();
var spPatientName = new SearchParamDefinition() { Resource = "Patient", Name = "name", Description = @"A portion of either family or given name of the patient", Type = SearchParamType.String, Path = new string[] { "Patient.name", } };
var searchParameters = new List<SearchParamDefinition> { spPatientName };
var resources = new Dictionary<Type, string> { { typeof(Patient), "Patient" }, { typeof(HumanName), "HumanName" } };
var enums = new List<Type>();
//CK: I use real objects: saves me a lot of mocking and provides for a bit of integration testing.
_fhirModel = new FhirModel(resources, searchParameters, enums);
_propIndex = new FhirPropertyIndex(_fhirModel, new List<Type> { typeof(Patient), typeof(HumanName) });
_resourceVisitor = new ResourceVisitor(_propIndex);
_elementIndexer = new ElementIndexer(_fhirModel);
//_indexStoreMock.Setup(ixs => ixs.Save(It.IsAny<IndexValue>))
sutLimited = new IndexService(_fhirModel, _propIndex, _resourceVisitor, _elementIndexer, _indexStoreMock.Object);
_fhirModel = new FhirModel(); //For this test I want all available types and searchparameters.
_propIndex = new FhirPropertyIndex(_fhirModel);
_resourceVisitor = new ResourceVisitor(_propIndex);
_elementIndexer = new ElementIndexer(_fhirModel);
sutFull = new IndexService(_fhirModel, _propIndex, _resourceVisitor, _elementIndexer, _indexStoreMock.Object);
}
示例7: GetUnitOfWorkFactory_uses_same_session_factory_as_provider
public void GetUnitOfWorkFactory_uses_same_session_factory_as_provider()
{
var factory = new Mock<ISessionFactory>();
var provider = new HibernateDataServicesProvider(factory.Object);
var unitOfWorkFactory = (HibernateUnitOfWorkFactory)provider.GetUnitOfWorkFactory();
Assert.AreEqual(factory.Object, unitOfWorkFactory.SessionFactory);
}
示例8: scenario_10
public void scenario_10()
{
var propertyUpgradeUoW = new Mock<IPropertyUpgradeUoW>();
propertyUpgradeUoW.Setup(x => x.ProductTypeRepository.Get())
.Returns(GetDomainProductTypes());
var calculator = new CityStorageCalculator(propertyUpgradeUoW.Object);
var cityStorage = GetCityStorage();
cityStorage.CurrentInventory.First(x => x.ProductTypeId == 1).Quantity = 8;
cityStorage.CurrentInventory.First(x => x.ProductTypeId == 2).Quantity = 8;
cityStorage.CurrentInventory.First(x => x.ProductTypeId == 3).Quantity = 8;
cityStorage.CurrentInventory.First(x => x.ProductTypeId == 4).Quantity = 8;
var request = new CalculateStorageRequest
{
CityStorage = cityStorage,
NewProductQuantities = new[]
{
new SimGame.Handler.Entities.Product
{
ProductTypeId = 3,
Quantity = 2
},
}
};
var ret = calculator.CalculateNewStorageAmounts(request);
ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 4).Quantity.ShouldEqual(6);
ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 3).Quantity.ShouldEqual(10);
ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 2).Quantity.ShouldEqual(8);
ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 1).Quantity.ShouldEqual(8);
}
示例9: ShouldReturnNameOfLogFactory
public void ShouldReturnNameOfLogFactory() {
var logFactoryRegistry = new LogFactoryRegistry();
var mylogger = new Mock<ITaskLogFactory>().Object;
logFactoryRegistry.RegisterLogFactory("mylogger", mylogger);
Assert.That(logFactoryRegistry.FindNameForLogFactory(mylogger), Is.EqualTo("mylogger"));
}
示例10: ShouldReturnLogFactoryByName
public void ShouldReturnLogFactoryByName() {
var logFactoryRegistry = new LogFactoryRegistry();
var mylogger = new Mock<ITaskLogFactory>().Object;
logFactoryRegistry.RegisterLogFactory("mylogger", mylogger);
Assert.That(logFactoryRegistry.GetLogFactoryByName("mylogger"), Is.SameAs(mylogger));
}
示例11: ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider
public void ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider()
{
// Arrange
IPackage packageA = PackageUtility.CreatePackage("A",
"1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B");
var repository = new Mock<PackageRepositoryBase>();
repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable());
var dependencyProvider = repository.As<IDependencyResolver>();
dependencyProvider.Setup(c => c.ResolveDependency(It.Is<PackageDependency>(p => p.Id == "B"), It.IsAny<IPackageConstraintProvider>(), false, true, DependencyVersion.Lowest))
.Returns(packageB).Verifiable();
var localRepository = new MockPackageRepository();
IPackageOperationResolver resolver = new InstallWalker(localRepository,
repository.Object,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
// Assert
Assert.Equal(2, operations.Count);
Assert.Equal(PackageAction.Install, operations.First().Action);
Assert.Equal(packageB, operations.First().Package);
Assert.Equal(PackageAction.Install, operations.Last().Action);
Assert.Equal(packageA, operations.Last().Package);
dependencyProvider.Verify();
}
示例12: When_a_navigation_button_is_clicked_the_associated_page_should_be_displayed
public void When_a_navigation_button_is_clicked_the_associated_page_should_be_displayed()
{
this.testContainer = new UnityContainer();
this.autoMocker = new AutoMoq.AutoMoqer(this.testContainer);
var mockPageViewModel = new Mock<IPageViewModel>();
mockPageViewModel.SetupGet(page => page.Title).Returns("Page1");
IPageViewModel pageViewModel = mockPageViewModel.Object;
var viewModelFactoryMock = new Mock<IViewModelFactory>();
viewModelFactoryMock.Setup(f => f.Get<StartPageViewModel>()).Returns(() => new StartPageViewModel(new Mock<INavigationService>().Object));
this.autoMocker.SetInstance(viewModelFactoryMock.Object);
var navigationServiceMock = this.navigationServiceMock;
navigationServiceMock.Setup(vm => vm.GetDefaultPagesByNames())
.Returns(
new Dictionary<string, Func<IPageViewModel>>
{
{ "page1", () => pageViewModel },
{ "page2", () => null },
{ "page3", () => null },
{ "page4", () => null },
});
INavigationService navigationService = navigationServiceMock.Object;
this.autoMocker.SetInstance(navigationService);
var applicationViewModel = this.autoMocker.Resolve<ApplicationViewModel>();
applicationViewModel.LeftNavigationButtonCollection.Single(btn => btn.DisplayText == "page1").ExecuteAsync(null);
navigationServiceMock.VerifySet(ns => ns.CurrentPage = pageViewModel);
}
示例13: Run_WhenCheckerThrows_FailureResult
public async Task Run_WhenCheckerThrows_FailureResult()
{
// Arrange
var checkerMocks = Enumerable
.Range(1, 3)
.Select(x =>
{
var mock = new Mock<IChecker>();
mock.SetupGet(y => y.Name).Returns(x.ToString());
mock.Setup(y => y.Check()).ThrowsAsync(new Exception("error " + mock.Object.Name));
return mock;
})
.ToArray();
var healthCheck = new HealthCheck(checkerMocks.Select(x => x.Object));
// Act
var result = await healthCheck.Run();
// Assert
Assert.That(result.Passed, Is.False);
Assert.That(result.Status, Is.EqualTo("failure"));
Assert.That(result.Results.Length, Is.EqualTo(checkerMocks.Length));
foreach (var checkerMock in checkerMocks)
{
var checkResult = result.Results.Single(x => x.Checker == checkerMock.Object.Name);
Assert.That(checkResult.Checker, Is.EqualTo(checkerMock.Object.Name));
Assert.That(checkResult.Passed, Is.False);
Assert.That(checkResult.Output, Is.EqualTo("error " + checkerMock.Object.Name));
}
}
示例14: ConnectControlViewModel_AddNewServer_ResourceRepositoryReturnExistingServers_False
public void ConnectControlViewModel_AddNewServer_ResourceRepositoryReturnExistingServers_False()
{
//------------Setup for test--------------------------
var mainViewModel = new Mock<IMainViewModel>();
var connectControlSingleton = new Mock<IConnectControlSingleton>();
var env1 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false);
var env2 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false);
var connectControlEnvironments = new ObservableCollection<IConnectControlEnvironment>();
var controEnv1 = new Mock<IConnectControlEnvironment>();
var controEnv2 = new Mock<IConnectControlEnvironment>();
controEnv1.Setup(c => c.EnvironmentModel).Returns(env1);
controEnv2.Setup(c => c.EnvironmentModel).Returns(env2);
controEnv1.Setup(c => c.IsConnected).Returns(true);
connectControlEnvironments.Add(controEnv2.Object);
connectControlEnvironments.Add(controEnv1.Object);
connectControlSingleton.Setup(c => c.Servers).Returns(connectControlEnvironments);
var environmentRepository = new Mock<IEnvironmentRepository>();
ICollection<IEnvironmentModel> environments = new Collection<IEnvironmentModel>
{
env1
};
environmentRepository.Setup(e => e.All()).Returns(environments);
var viewModel = new ConnectControlViewModel(mainViewModel.Object, environmentRepository.Object, e => { }, connectControlSingleton.Object, "TEST : ", false);
//------------Execution-------------------------------
int serverIndex;
var didAddNew = viewModel.AddNewServer(out serverIndex, i => { });
//------------Assert----------------------------------
Assert.IsNotNull(viewModel);
Assert.IsFalse(didAddNew);
}
示例15: Arrange
protected void Arrange()
{
var random = new Random();
_subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
_operationTimeout = TimeSpan.FromSeconds(30);
_encoding = Encoding.UTF8;
_disconnectedRegister = new List<EventArgs>();
_errorOccurredRegister = new List<ExceptionEventArgs>();
_channelDataEventArgs = new ChannelDataEventArgs(
(uint)random.Next(0, int.MaxValue),
new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });
_sessionMock = new Mock<ISession>(MockBehavior.Strict);
_channelMock = new Mock<IChannelSession>(MockBehavior.Strict);
_sequence = new MockSequence();
_sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
_channelMock.InSequence(_sequence).Setup(p => p.Open());
_channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);
_subsystemSession = new SubsystemSessionStub(
_sessionMock.Object,
_subsystemName,
_operationTimeout,
_encoding);
_subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
_subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
_subsystemSession.Connect();
}