• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Mock类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Mock的典型用法代码示例。如果您正苦于以下问题:C# Mock类的具体用法?C# Mock怎么用?C# Mock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Mock类属于命名空间,在下文中一共展示了Mock类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
        }
开发者ID:ucdavis,项目名称:JabbR,代码行数:30,代码来源:ChatFacts.cs


示例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);
        }
开发者ID:harumburum,项目名称:todolist-mvc5,代码行数:26,代码来源:TodoRepositoryTests.cs


示例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());
        }
开发者ID:GusLab,项目名称:video-portal,代码行数:25,代码来源:TaggerIPhoneDeletionsFilterTest.cs


示例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
 }
开发者ID:danludwig,项目名称:UCosmic,代码行数:25,代码来源:CreatePersonValidatorFacts.cs


示例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);
        }
开发者ID:Condeti,项目名称:spark,代码行数:30,代码来源:IndexServiceTests.cs


示例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);
 }
开发者ID:DavidMoore,项目名称:Foundation,代码行数:7,代码来源:HibernateDataProviderTests.cs


示例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);
        }
开发者ID:cberberian,项目名称:GameSim,代码行数:30,代码来源:CityStorageCalculatorTests.cs


示例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"));
        }
开发者ID:nbucket,项目名称:bounce,代码行数:7,代码来源:LogFactoryRegistryTest.cs


示例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));
        }
开发者ID:nbucket,项目名称:bounce,代码行数:7,代码来源:LogFactoryRegistryTest.cs


示例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();
        }
开发者ID:Berzeger,项目名称:NuGet,代码行数:35,代码来源:PackageWalkerTest.cs


示例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);
        }
开发者ID:joomnet,项目名称:SkillSignal,代码行数:33,代码来源:ApplicationViewModelTests.cs


示例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));
            }
        }
开发者ID:konstantin-matsebora,项目名称:HealthCheck,代码行数:30,代码来源:HealthCheckTests.cs


示例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);
 }
开发者ID:Robin--,项目名称:Warewolf,代码行数:30,代码来源:ConnectControlViewModelTests.cs


示例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();
        }
开发者ID:delfinof,项目名称:ssh.net,代码行数:29,代码来源:SubsystemSession_OnChannelDataReceived_Connected.cs


示例16: GetAnonymousCompetitions

        public void GetAnonymousCompetitions()
        {
            var repository = new RepositoryForTests<Competition>();
            repository.TheContent.Add(new Competition
            {
                CompetitionType = CompetitionType.Field,
                Id = Guid.NewGuid(),
                IsPublic = true,
                Name = "Public1",
                StartDate = DateTime.Now,
                UseNorwegianCount = false
            });
            repository.TheContent.Add(new Competition
            {
                CompetitionType = CompetitionType.Field,
                Id = Guid.NewGuid(),
                IsPublic = false,
                Name = "Private1",
                StartDate = DateTime.Now,
                UseNorwegianCount = false
            });

            var rightsHelperMock = new Mock<IRightsHelper>();

            var userRolesInfoMock = new Mock<IRepository<UserRolesInfo>>();

            var competitions = new CompetitionsLogic(repository, userRolesInfoMock.Object, rightsHelperMock.Object);

            var result = competitions.GetCompetitions();
            Assert.AreEqual(1, result.Count());
        }
开发者ID:WinShooter,项目名称:WinShooter-Web,代码行数:31,代码来源:CompetitionsLogicTests.cs


示例17: GetTestableChat

        public static TestableChat GetTestableChat(string clientId, TrackingDictionary clientState, ChatUser user, NameValueCollection 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>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            // setup client agent
            chat.Agent = new ClientAgent(mockedConnectionObject, "Chat");

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);

            // setup signal agent
            var prinicipal = new Mock<IPrincipal>();
            chat.Caller = new SignalAgent(mockedConnectionObject, clientId, "Chat", clientState);

            // setup context
            chat.Context = new HubContext(new HostContext(request.Object, null, prinicipal.Object), clientId);

            return chat;
        }
开发者ID:skoon,项目名称:JabbR,代码行数:30,代码来源:ChatFacts.cs


示例18: MessagePassedToConstructorIsReturned

 public void MessagePassedToConstructorIsReturned()
 {
     const string Msg = "msg";
     var innerRule = new Mock<IRule<string>>();
     var rule = new NotRule<string>(innerRule.Object, Msg);
     Assert.AreEqual(Msg, rule.Message);
 }
开发者ID:kevinwiegand,项目名称:EnergyTrading-Core,代码行数:7,代码来源:NotRuleFixture.cs


示例19: GetCurrentSession_delegates_to_session_factory

 public void GetCurrentSession_delegates_to_session_factory()
 {
     var factory = new Mock<ISessionFactory>();
     var provider = new HibernateDataServicesProvider(factory.Object);
     provider.GetCurrentSession();
     factory.Verify(sessionFactory => sessionFactory.GetCurrentSession());
 }
开发者ID:DavidMoore,项目名称:Foundation,代码行数:7,代码来源:HibernateDataProviderTests.cs


示例20: Should_Return_Page_Html_Content

        public void Should_Return_Page_Html_Content()
        {
            // Create html content
            var htmlContent = TestDataProvider.CreateNewHtmlContent();
            var pageContent = TestDataProvider.CreateNewPageContent(htmlContent);
            htmlContent.Status = ContentStatus.Published;

            // Create command
            var command = new GetPageHtmlContentCommand();
            command.UnitOfWork = new Mock<IUnitOfWork>().Object;
            command.Repository = new Mock<IRepository>().Object;

            // Mock content service
            var serviceMock = new Mock<IContentService>();
            serviceMock
                .Setup(f => f.GetPageContentForEdit(pageContent.Id))
                .Returns(new Tuple<PageContent, Content>(pageContent, htmlContent));
            command.ContentService = serviceMock.Object;

            // Execute command
            var result = command.Execute(pageContent.Id);

            Assert.IsNotNull(result);
            Assert.AreEqual(result.Id, pageContent.Id);
            Assert.AreEqual(result.ContentId, htmlContent.Id);
            Assert.AreEqual(result.ContentName, htmlContent.Name);
            Assert.AreEqual(result.ContentVersion, htmlContent.Version);
            Assert.AreEqual(result.CurrentStatus, htmlContent.Status);
            Assert.AreEqual(result.PageId, pageContent.Page.Id);
            Assert.AreEqual(result.RegionId, pageContent.Region.Id);
            Assert.AreEqual(result.LiveFrom, htmlContent.ActivationDate);
            Assert.AreEqual(result.LiveTo, htmlContent.ExpirationDate);
        }
开发者ID:tkirda,项目名称:BetterCMS,代码行数:33,代码来源:GetPageHtmlContentCommandTest.cs



注:本文中的Mock类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# MockClients类代码示例发布时间:2022-05-24
下一篇:
C# MobileServiceCollection类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap