Example #1
0
   public void RequiresSort_SorterType_ReturnsTrue()
   {
      NodeSorter sorter = new Mock<NodeSorter>().Object;
      
      Boolean result = NodeSorter.RequiresSort(sorter, sorter.GetType());

      Assert.IsTrue(result);
   }
Example #2
0
        public void TestCreateWarrior_ShouldCreatCompleteObject()
        {
            Mock moq = new Mock<IAttack>();
            Console.WriteLine(moq.GetType());

            var mock = new Mock<IList<int>>();
            var mockedObject = mock.Object;
        }
        public void ItShouldBehaviorForNonDecoratedTypesOrMethod()
        {
            var repository = new Mock<MockeableRepository>().Object;
            var method = repository.GetType().GetMethod("GetAll");
            var behavior = repository.GetBehavior(method);

            Assert.IsNotNull(behavior);
            Assert.IsFalse(behavior.HandlesEverything);
        }
        public void GetSpatialDataReader_throws_on_non_SqlDataReader()
        {
            var executionStrategyMock = new Mock<IDbExecutionStrategy>();
            executionStrategyMock.Setup(m => m.Execute(It.IsAny<Action>())).Callback<Action>(a => a());

            var connection = new SqlConnection(SimpleConnectionString(("master")));
            var mockReader = new Mock<DbDataReader>().Object;
            Assert.Throws<ProviderIncompatibleException>(
                () => DbProviderServices.GetProviderServices(connection).GetSpatialDataReader(
                    mockReader, "2008")).ValidateMessage(EntityFrameworkSqlServerAssembly,
                        "SqlProvider_NeedSqlDataReader", "System.Data.Entity.SqlServer.Properties.Resources.SqlServer", mockReader.GetType());
        }
        public void Generate_throws_when_operation_unknown()
        {
            var migrationSqlGenerator = new SqlCeMigrationSqlGenerator();
            var unknownOperation = new Mock<MigrationOperation>(null).Object;

            var ex = Assert.Throws<InvalidOperationException>(
                () => migrationSqlGenerator.Generate(new[] { unknownOperation }, "4.0"));

            Assert.Equal(
                Strings.SqlServerMigrationSqlGenerator_UnknownOperation(typeof(SqlCeMigrationSqlGenerator).Name, unknownOperation.GetType().FullName),
                ex.Message);
        }
        public void ShouldUseCustomFactoryWhenSet()
        {
            ResetViewModelLocationProvider();

            Mock view = new Mock();
            Assert.IsNull(view.DataContext);

            string viewModel = "Test String";
            ViewModelLocationProvider.Register(view.GetType().ToString(), () => viewModel);
            
            ViewModelLocator.SetAutoWireViewModel(view, true);
            Assert.IsNotNull(view.DataContext);
            ReferenceEquals(view.DataContext, viewModel);
        }
Example #7
0
        public void ExecuteBootstrapperTasks_should_execute_bootstrapper_tasks()
        {
            var task = new Mock<BootstrapperTask>();
            task.Setup(t => t.Execute()).Verifiable();

            var config = new KeyValuePair<Type, Action<object>>(task.GetType(), null);

            bootstrapperTasksRegistry.Setup(r => r.TaskConfigurations).Returns(new[] { config });
            adapter.Setup(a => a.GetService(It.IsAny<Type>())).Returns(task.Object).Verifiable();

            bootstrapper.ExecuteBootstrapperTasks();

            task.VerifyAll();
            adapter.VerifyAll();
        }
Example #8
0
            public void ReaderExecuted_logs()
            {
                var dataReader = new Mock<DbDataReader>().Object;
                var interceptionContext = new DbCommandInterceptionContext<DbDataReader>();

                interceptionContext.Result = dataReader;
                var writer = new StringWriter();
                new DbCommandLogger(writer.Write).ReaderExecuted(CreateCommand(""), interceptionContext);

                Assert.Equal(Strings.CommandLogComplete(0, dataReader.GetType().Name, ""), GetSingleLine(writer));
            }
            public void EnsureLoadedForContext_throws_if_configuration_was_set_but_is_not_found_in_context_assembly()
            {
                var configuration = new Mock<DbConfiguration>().Object;
                var mockFinder = new Mock<DbConfigurationFinder>();
                var manager = CreateManager(null, mockFinder);

                manager.SetConfiguration(configuration);

                Assert.Equal(
                    Strings.SetConfigurationNotDiscovered(configuration.GetType().Name, typeof(FakeContext).Name),
                    Assert.Throws<InvalidOperationException>(
                        () => manager.EnsureLoadedForContext(typeof(FakeContext))).Message);
            }
            public void EnsureLoadedForContext_throws_if_configuration_is_found_but_default_was_previously_used()
            {
                var configuration = new Mock<DbConfiguration>().Object;
                var mockFinder = new Mock<DbConfigurationFinder>();
                mockFinder.Setup(m => m.TryFindConfigurationType(It.IsAny<IEnumerable<Type>>())).Returns(configuration.GetType());
                var manager = CreateManager(null, mockFinder);

                manager.GetConfiguration();

                Assert.Equal(
                    Strings.ConfigurationNotDiscovered(configuration.GetType().Name),
                    Assert.Throws<InvalidOperationException>(
                        () => manager.EnsureLoadedForContext(typeof(FakeContext))).Message);
            }
 public void ShouldLogAsDebugWhenPluginSourceIsRemoved()
 {
     PluginRepository tested = new PluginRepository();
       MockLog log = new MockLog(tested);
       var pluginSource = new Mock<IPluginSource>().Object;
       tested.AddPluginSource(pluginSource);
       tested.RemovePluginSource(pluginSource);
       Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Debug && x.Message.Contains("removed") && x.Message.Contains(pluginSource.GetType().FullName)));
 }
      public void Contains_Type_ReturnsFiltersOfType()
      {
         FilterCollection<int> filters = new FilterCollection<int>();
         Filter<int> filterInt = new Mock<Filter<int>>().Object;
         Filter<double> filterDouble = new Mock<Filter<double>>().Object;
         filters.Add(filterInt);

         Assert.IsTrue(filters.Contains(filterInt.GetType()));
         Assert.IsFalse(filters.Contains(filterDouble.GetType()));
      }
      public void Remove_ByType()
      {
         FilterCollection<int> filters = new FilterCollection<int>();
         Filter<int> filter = new Mock<Filter<int>>().Object;
         filters.Add(filter);

         filters.Remove(filter.GetType());

         Assert.IsFalse(filters.Contains(filter));
      }
        public void ShouldUseCustomFactoryWhenSet()
        {
            ResetViewModelLocationProvider();

            var view = new Mock();

            string viewModel = "Test String";
            ViewModelLocationProvider.Register(view.GetType().ToString(), () => viewModel);

            ViewModelLocationProvider.AutoWireViewModelChanged(view, (v, vm) =>
                {
                    Assert.IsNotNull(v);
                    Assert.IsNotNull(vm);
                    Assert.AreEqual(viewModel, vm);
                });
        }
        public void ContainerControllerFactory_GetTypesFor_ReturnsAllControllerTypesInContainer()
        {
            Func<IEnumerable<Type>, string> typeToString = _types => _types.OrderBy(x => x.Name).Select(x => x.Name).ConcatAll(",");

            var container = new Container();
            var mockController = new Mock<IController>().Object;
            container.Inject<IController>(new ProperController());
            container.Inject<IController>(mockController);

            var types = ContainerControllerFactory.GetControllersFor(container);

            Assert.Equal(typeToString(new[] { typeof(ProperController), mockController.GetType() }),
                         typeToString(types));
        }
        public void ShouldUseCustomTypeWhenSet()
        {
            ResetViewModelLocationProvider();

            var view = new Mock();

            ViewModelLocationProvider.Register(view.GetType().ToString(), typeof(ViewModelLocationProviderFixture));

            ViewModelLocationProvider.AutoWireViewModelChanged(view, (v, vm) =>
            {
                Assert.NotNull(v);
                Assert.NotNull(vm);
                Assert.IsType<ViewModelLocationProviderFixture>(vm);
            });
        }
Example #17
0
        public void Should_register_bootstrapper_tasks_as_singleton()
        {
            var task = new Mock<BootstrapperTask>().Object;

            buildManager.Setup(bm => bm.ConcreteTypes).Returns(new[] { task.GetType() });

            adapter.Setup(a => a.RegisterType(task.GetType(), task.GetType(), LifetimeType.Singleton)).Returns(adapter.Object).Verifiable();

            Assert.NotNull(bootstrapper.Adapter);

            adapter.Verify();
        }
Example #18
0
            public void LogResult_handles_completed_commands_with_DbDataReader_results()
            {
                var dataReader = new Mock<DbDataReader>().Object;
                var writer = new StringWriter();
                new DbCommandLogger(writer.Write).LogResult(
                    new Mock<DbCommand>().Object, dataReader, new DbCommandInterceptionContext<int>());

                Assert.Equal(Strings.CommandLogComplete(0, dataReader.GetType().Name, ""), GetSingleLine(writer));
            }
        public void RegisterValidatableObjectAdapter()
        {
            // Arrange
            var provider = new DataAnnotationsModelValidatorProvider();
            provider.ValidatableFactories = new Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory>();
            IValidatableObject validatable = new Mock<IValidatableObject>().Object;

            // Act
            provider.RegisterValidatableObjectAdapter(validatable.GetType(), typeof(MyValidatableAdapter));

            // Assert
            var type = provider.ValidatableFactories.Keys.Single();
            Assert.Equal(validatable.GetType(), type);

            var factory = provider.ValidatableFactories.Values.Single();
            var metadata = _metadataProvider.GetMetadataForType(() => null, typeof(object));
            var validator = factory(_noValidatorProviders);
            Assert.IsType<MyValidatableAdapter>(validator);
        }
            public void SetConfiguration_throws_if_an_attempt_is_made_to_set_a_different_configuration_type()
            {
                var manager = CreateManager();
                var configuration1 = new FakeConfiguration();
                var configuration2 = new Mock<DbConfiguration>().Object;

                manager.SetConfiguration(configuration1);

                Assert.Equal(
                    Strings.ConfigurationSetTwice(configuration2.GetType().Name, configuration1.GetType().Name),
                    Assert.Throws<InvalidOperationException>(() => manager.SetConfiguration(configuration2)).Message);
            }
      public void Get_ByType()
      {
         FilterCollection<int> filters = new FilterCollection<int>();
         Filter<int> filter = new Mock<Filter<int>>().Object;
         filters.Add(filter);

         Assert.AreEqual(filter, filters.Get(filter.GetType()));
      }
        public void ApiControllerCannotBeReused()
        {
            // Arrange
            var config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };
            var singletonController = new Mock<ApiController> { CallBase = true }.Object;
            var mockDescriptor = new Mock<HttpControllerDescriptor>(config, "MyMock", singletonController.GetType()) { CallBase = true };
            mockDescriptor.Setup(d => d.CreateController(It.IsAny<HttpRequestMessage>())).Returns(singletonController);
            var mockSelector = new Mock<DefaultHttpControllerSelector>(config) { CallBase = true };
            mockSelector.Setup(s => s.SelectController(It.IsAny<HttpRequestMessage>())).Returns(mockDescriptor.Object);
            config.Routes.MapHttpRoute("default", "", new { controller = "MyMock" });
            config.Services.Replace(typeof(IHttpControllerSelector), mockSelector.Object);
            var server = new HttpServer(config);
            var invoker = new HttpMessageInvoker(server);

            // Act
            HttpResponseMessage response1 = invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://localhost/"), CancellationToken.None).Result;
            HttpResponseMessage response2 = invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://localhost/"), CancellationToken.None).Result;

            // Assert
            Assert.NotEqual(HttpStatusCode.InternalServerError, response1.StatusCode);
            Assert.Equal(HttpStatusCode.InternalServerError, response2.StatusCode);
            Assert.Contains("Cannot reuse an 'ApiController' instance. 'ApiController' has to be constructed per incoming message.", response2.Content.ReadAsStringAsync().Result);
        }
            public void SetConfiguration_throws_if_an_attempt_is_made_to_set_a_configuration_after_the_default_has_already_been_used()
            {
                var manager = CreateManager();
                var configuration = new Mock<DbConfiguration>().Object;

                manager.GetConfiguration(); // Initialize default

                Assert.Equal(
                    Strings.DefaultConfigurationUsedBeforeSet(configuration.GetType().Name),
                    Assert.Throws<InvalidOperationException>(() => manager.SetConfiguration(configuration)).Message);
            }
Example #24
0
        public void throws_exception_if_required_argument_is_not_specified()
        {
            var stubCommand = new Mock<ICommand<IdArgument>>().Object;

            var engine = CleeEngine.Create(cfg =>
            {
                cfg.Factory(f => f.Use(new StubCommandFactory(stubCommand)));
                cfg.Registry(r => r.Register("foo", stubCommand.GetType()));
            });

            Assert.Throws<Exception>(() => engine.Execute("foo"));
        }
            private void ExecuteAsync_throws_for_an_existing_transaction(Func<DbExecutionStrategy, Task> executeAsync)
            {
                var mockExecutionStrategy =
                    new Mock<DbExecutionStrategy>
                        {
                            CallBase = true
                        }.Object;

                using (new TransactionScope())
                {
                    Assert.Equal(
                        Strings.ExecutionStrategy_ExistingTransaction(mockExecutionStrategy.GetType().Name),
                        Assert.Throws<InvalidOperationException>(
                            () =>
                            executeAsync(mockExecutionStrategy)).Message);
                }
            }
            public void EnsureLoadedForContext_does_not_throw_if_configuration_in_assembly_is_the_same_as_was_previously_used()
            {
                var configuration = new Mock<DbConfiguration>().Object;
                var mockFinder = new Mock<DbConfigurationFinder>();
                mockFinder.Setup(m => m.TryFindConfigurationType(It.IsAny<IEnumerable<Type>>())).Returns(configuration.GetType());
                var manager = CreateManager(null, mockFinder);

                manager.SetConfiguration(configuration);

                manager.EnsureLoadedForContext(typeof(FakeContext));

                mockFinder.Verify(m => m.TryFindConfigurationType(It.IsAny<IEnumerable<Type>>()));

                Assert.Same(configuration, manager.GetConfiguration());
            }