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 RequiresSort_SorterType_ReturnsTrue() { NodeSorter sorter = new Mock<NodeSorter>().Object; Boolean result = NodeSorter.RequiresSort(sorter, sorter.GetType()); Assert.IsTrue(result); }
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); }
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(); }
public void SetConfiguration_throws_if_an_attempt_is_made_to_set_a_different_configuration_type() { var manager = CreateManager(); var configuration1 = new FakeConfiguration(); var mockInternalConfiguration1 = CreateMockInternalConfiguration(configuration1); var configuration2 = new Mock <DbConfiguration>().Object; var mockInternalConfiguration2 = CreateMockInternalConfiguration(configuration2); manager.SetConfiguration(mockInternalConfiguration1.Object); Assert.Equal( Strings.ConfigurationSetTwice(configuration2.GetType().Name, configuration1.GetType().Name), Assert.Throws <InvalidOperationException>(() => manager.SetConfiguration(mockInternalConfiguration2.Object)).Message); }
public void ShouldUseCustomFactoryWhenSet() { ResetViewModelLocationProvider(); Mock view = new Mock(); Assert.Null(view.DataContext); string viewModel = "Test String"; ViewModelLocationProvider.Register(view.GetType().ToString(), () => viewModel); ViewModelLocator.SetAutoWireViewModel(view, true); Assert.NotNull(view.DataContext); ReferenceEquals(view.DataContext, viewModel); }
public void Generate_throws_when_operation_unknown() { if (LocalizationTestHelpers.IsEnglishLocale()) { 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); } }
private static void MockProperty <T>(Mock <T> pageMock, PropertyInfo property) where T : Page, new() { By finder = CreateFinder(property.GetCustomAttribute <FindsByAttribute>()); var finderFunc = GetFinderMethod(property.PropertyType, pageMock.Object, finder); LambdaExpression propertyExpression = GetPropertyExpression <T>(property.Name); var propertyType = typeof(T).GetProperty(property.Name).PropertyType; var setupMethod = pageMock.GetType().GetMethods().Single(d => d.Name.Equals("Setup") && d.IsGenericMethod); MethodInfo generic = setupMethod.MakeGenericMethod(propertyType); var setup = generic.Invoke(pageMock, new[] { propertyExpression }); var methods = setup.GetType().GetMethods().Where(m => m.Name.Equals("Returns") && !m.IsGenericMethod); methods.First().Invoke(setup, new[] { finderFunc }); }
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(); }
public void ShouldUseCustomFactoryWhenSet() { ResetViewModelLocationProvider(); var view = new Mock(); string viewModel = "Test String"; ViewModelLocationProvider.Register(view.GetType().ToString(), () => viewModel); ViewModelLocationProvider.AutoWireViewModelChanged(view, (v, vm) => { Assert.NotNull(v); Assert.NotNull(vm); Assert.Equal(viewModel, vm); }); }
private async Task 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), (await Assert.ThrowsAsync <InvalidOperationException>( () => executeAsync(mockExecutionStrategy))).Message); } }
public void Test() { Dictionary <Type, object> data = new Dictionary <Type, object> { { typeof(IQueryable <Cycle>), new List <Cycle> { new Cycle { Name = "Test" } }.AsQueryable() }, { typeof(IQueryable <Rider>), new List <Rider> { new Rider { Name = "1" }, new Rider { Name = "2" } }.AsQueryable() } }; var mock = new Mock <IDataContext>(); var setup = mock.GetType().GetMethods().Single(d => d.Name == "Setup" && d.ContainsGenericParameters); var param = Expression.Parameter(typeof(IDataContext), "i"); foreach (var property in typeof(IDataContext).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { // Build lambda var ex = Expression.Lambda(Expression.MakeMemberAccess(param, property), param); // Get generic version of the Setup method var typedSetup = setup.MakeGenericMethod(property.PropertyType); // Run the Setup method var returnedSetup = typedSetup.Invoke(mock, new[] { ex }); // Get generic version of IReturns interface var iReturns = typedSetup.ReturnType.GetInterfaces().Single(d => d.Name.StartsWith("IReturns`")); // Get the generic Returns method var returns = iReturns.GetMethod("Returns", new Type[] { property.PropertyType }); // Run the returns method passing in our data returns.Invoke(returnedSetup, new[] { data[property.PropertyType] }); } Assert.Equal(1, mock.Object.Cycles.Count()); }
public void CreatingHotkeyReturnsCorrectResult() { var mockCommand = new Mock <CommandBase>(null).Object; var factory = new HotkeyFactory(new[] { mockCommand }); var setting = new HotkeySetting { CommandTypeName = mockCommand.GetType().Name, Key1 = "X", HasCtrlModifier = true }; var hotkey = factory.Create(setting, IntPtr.Zero); Assert.Multiple(() => { Assert.AreEqual(mockCommand, hotkey.Command); Assert.AreEqual(setting.ToString(), hotkey.Key); }); }
/// <summary> /// Ensure <see cref="PipelineComponent"/>-derived class does not break the implementation of the <see /// cref="Microsoft.BizTalk.Component.Interop.IComponent.Execute"/> method from its base class. /// </summary> protected void VerifyExecuteCoreIsSkippedWhenPipelineComponentIsNotEnabled() { var sut = new Mock <T> { CallBase = true }; sut.Object.Enabled = false; var resultMessage = sut.Object.Execute(PipelineContextMock.Object, MessageMock.Object); if (!ReferenceEquals(resultMessage, MessageMock.Object)) { throw new NotSupportedException( $"{nameof(PipelineComponent)} {sut.GetType().Name} did not return the same message it was given although the pipeline component was not enabled."); } sut.Verify(pc => pc.ExecuteCore(It.IsAny <IPipelineContext>(), It.IsAny <IBaseMessage>()), Times.Never()); }
public static void SetupRepositoryMock <T>(this Mock <Repository <T> > repositoryMock, Action <IRepository <T> > options) where T : BaseEntity { var context = new AppDashTestContext(); context.Database.EnsureDeleted(); var constructorArguments = repositoryMock.GetType().GetField("constructorArguments", BindingFlags.NonPublic | BindingFlags.Instance); constructorArguments?.SetValue(repositoryMock, new object[] { context }); repositoryMock.Protected().SetupGet <DbSet <T> >("Entities").Returns(context.Set <T>()); repositoryMock.Setup(repository => repository.Table).Returns(context.Set <T>()); repositoryMock.Setup(repository => repository.TableNoTracking).Returns(context.Set <T>().AsNoTracking); options.Invoke(repositoryMock.Object); context.SaveChanges(); }
private static void ProxyProperty <T>(object subject, Type targetType, Mock <T> proxy, Type subjectType, ParameterExpression targetExpression, PropertyInfo propertyInfo) where T : class { if (subjectType.GetProperty(propertyInfo.Name) == null) { throw new InvalidCastException(string.Format("Property '{0}' not found on subject of the cast.", propertyInfo.Name)); } var property = Expression.Property(targetExpression, propertyInfo.Name); var funcType = typeof(Func <,>).MakeGenericType(targetType, propertyInfo.PropertyType); var lambda = Expression.Lambda(funcType, property, targetExpression); var setupMethodInfo = proxy.GetType().GetMethod("SetupGet"); var genericMethod = setupMethodInfo.MakeGenericMethod(propertyInfo.PropertyType); var getter = genericMethod.Invoke(proxy, new object[] { lambda }); var returnsMethodInfo = getter.GetType().GetMethod("Returns", new Type[] { propertyInfo.PropertyType }); returnsMethodInfo.Invoke(getter, new object[] { subjectType.GetProperty(propertyInfo.Name).GetValue(subject) }); }
public void ShouldCommitChangesOfContext() { // Arrange IUnitOfWork unitOfWork = new UnitOfWork(); var contextMock = new Mock <IContext>(); var changeSet = new ChangeSet(contextMock.GetType(), new List <IChange> { Change.CreateAddedChange(new object()) }); contextMock.Setup(c => c.SaveChanges()).Returns(changeSet); unitOfWork.RegisterContext(contextMock.Object); // Act var numberOfChanges = unitOfWork.Commit(); // Assert numberOfChanges.Should().HaveCount(1); }
/// <summary> /// Specifies a setup on the mocked type for a call to a void method. /// All parameters are filled with <see cref ="It.IsAny" /> according to the parameter's type. /// </summary> /// <remarks> /// This may only be used on methods that are not overloaded. /// </remarks> /// <typeparam name="T">Type of the mock</typeparam> /// <param name="mock">The mock</param> /// <param name="methodName">The name of the expected method invocation.</param> /// <exception cref="ArgumentNullException">When mock or methodName is null.</exception> /// <exception cref="MissingMethodException">Thrown when no method with methodName is found.</exception> /// <exception cref="AmbiguousMatchException">Thrown when more that one method matches the passed method name.</exception> /// <returns></returns> public static ISetup <T> SetupWithAny <T>(this Mock <T> mock, string methodName) where T : class { if (mock is null) { throw new ArgumentNullException(nameof(mock)); } if (methodName is null) { throw new ArgumentNullException(nameof(methodName)); } LambdaExpression lambdaExpression = GetExpression <T>(methodName); MethodInfo setupMethod = mock.GetType().GetMethods() .Single(x => x.Name == nameof(Mock <object> .Setup) && x.ReturnType.GetGenericArguments().Length == 1); return((ISetup <T>)setupMethod.Invoke(mock, new object[] { lambdaExpression }) !); }
/// <summary> /// Specifies a setup on the mocked type for a call to a non-void (value-returning) method. /// All parameters are filled with <see cref ="It.IsAny" /> according to the parameter's type. /// </summary> /// <remarks> /// This may only be used on methods that are not overloaded. /// </remarks> /// <typeparam name="T">Type of the mock</typeparam> /// <typeparam name="TResult">The return type of the method</typeparam> /// <param name="mock">The mock</param> /// <param name="methodName">The name of the expected method invocation.</param> /// <exception cref="ArgumentNullException">When mock or methodName is null.</exception> /// <exception cref="MissingMethodException">Thrown when no method with methodName is found.</exception> /// <exception cref="AmbiguousMatchException">Thrown when more that one method matches the passed method name.</exception> /// <returns></returns> public static ISetup <T, TResult> SetupWithAny <T, TResult>(this Mock <T> mock, string methodName) where T : class { if (mock is null) { throw new ArgumentNullException(nameof(mock)); } if (methodName is null) { throw new ArgumentNullException(nameof(methodName)); } LambdaExpression lambdaExpression = GetExpression <T>(methodName); //Invoke the setup method MethodInfo setupMethod = mock.GetType().GetMethods() .Single(x => x.Name == nameof(Mock <object> .Setup) && x.ReturnType.GetGenericArguments().Length == 2); var ret = setupMethod.MakeGenericMethod(typeof(TResult)).Invoke(mock, new object[] { lambdaExpression }); return((ISetup <T, TResult>)ret !); }
public void SaveCustomerRatingControllerTest_query(long CId, string ExpectedValue, string BId) { // make a fake return data from sql var data = new List <CustomerInfomation> { new CustomerInfomation { BusinessID = "111111", CustomerID = 606060, BusinessName = "merchant2", CustomerComment = "bad comment b", CustomerStarRating = 1 }, new CustomerInfomation { BusinessID = "111111", CustomerID = 616060, BusinessName = "merchant2", CustomerComment = "bad comment", CustomerStarRating = 1 } }.AsQueryable(); var mockSet = new Mock <DbSet <CustomerInfomation> >(); mockSet.As <IQueryable <CustomerInfomation> >().Setup(s => s.Provider) .Returns(data.Provider); mockSet.As <IQueryable <CustomerInfomation> >().Setup(s => s.Expression) .Returns(data.Expression); mockSet.As <IQueryable <CustomerInfomation> >().Setup(s => s.ElementType) .Returns(data.ElementType); mockSet.As <IQueryable <CustomerInfomation> >().Setup(s => s.GetEnumerator()) .Returns(data.GetEnumerator()); Debug.Write("THE TYPE OF MOCK: " + mockSet.GetType().ToString()); var mo = new Mock <Entities>(); mo.Setup(s => s.CustomerInfomations).Returns(mockSet.Object); mo.Setup(s => s.SaveChanges()).Returns(1); //test if customer exist - should return save success var fakeSRC = new SaveCustomerRatingController(mo.Object); var json = fakeSRC.Index(5, "Very good", CId, BId); Assert.Equal(ExpectedValue, json.Data.ToString()); }
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); }); }
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 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))); }
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 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 is_api_neutral_should_return_false_for_undecorated_action_descriptor() { // arrange var controller = new Mock <IHttpController>().Object; var controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "Tests", controller.GetType()); var actionDescriptor = new Mock <HttpActionDescriptor>(controllerDescriptor) { CallBase = true }.Object; // act var versionNeutral = actionDescriptor.IsApiVersionNeutral(); // assert versionNeutral.Should().BeFalse(); }
public void get_api_version_info_should_add_and_return_new_instance_for_action_descriptor() { // arrange var controller = new Mock <IHttpController>().Object; var controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "Tests", controller.GetType()); var actionDescriptor = new Mock <HttpActionDescriptor>(controllerDescriptor) { CallBase = true }.Object; actionDescriptor.Properties.Clear(); // act var versionInfo = actionDescriptor.GetApiVersionModel(); // assert versionInfo.Should().NotBeNull(); actionDescriptor.Properties.ContainsKey("MS_ApiVersionInfo").Should().BeTrue(); }
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 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 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")); }
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); }
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 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 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 Add <TValue>(string key, Mock <TValue> mock) where TValue : class { Guard.ThrowIfNullOrEmpty("key", key); _values.Add(key, new Tuple <Type, object>(mock.GetType().GenericTypeArguments.First(), mock)); }
public void get_api_version_info_should_return_exising_instance_for_controller_descriptor() { // arrange var controller = new Mock <IHttpController>().Object; var controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "Tests", controller.GetType()); var assignedVersionInfo = ApiVersionModel.Default; controllerDescriptor.Properties[typeof(ApiVersionModel)] = assignedVersionInfo; // act var versionInfo = controllerDescriptor.GetApiVersionModel(); // assert versionInfo.Should().Be(assignedVersionInfo); }
public void GetSpatialDataReader_throws_on_non_SqlDataReader() { var executionStrategyMock = new Mock <IExecutionStrategy>(); 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 get_api_version_info_should_returne_exising_instance_for_action_descriptor() { // arrange var controller = new Mock <IHttpController>().Object; var controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "Tests", controller.GetType()); var actionDescriptor = new Mock <HttpActionDescriptor>(controllerDescriptor) { CallBase = true }.Object; var assignedVersionInfo = ApiVersionModel.Default; actionDescriptor.Properties["MS_ApiVersionInfo"] = assignedVersionInfo; // act var versionInfo = actionDescriptor.GetApiVersionModel(); // assert versionInfo.Should().Be(assignedVersionInfo); }
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 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 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 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 get_api_version_info_should_add_and_return_new_instance_for_controller_descriptor() { // arrange var controller = new Mock <IHttpController>().Object; var controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "Tests", controller.GetType()); controllerDescriptor.Properties.Clear(); // act var versionInfo = controllerDescriptor.GetApiVersionModel(); // assert versionInfo.Should().NotBeNull(); }
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 get_api_version_model_should_return_existing_instance_for_action_descriptor() { // arrange var controller = new Mock <IHttpController>().Object; var controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "Tests", controller.GetType()); var actionDescriptor = new Mock <HttpActionDescriptor>(controllerDescriptor) { CallBase = true }.Object; var assignedModel = ApiVersionModel.Default; actionDescriptor.Properties[typeof(ApiVersionModel)] = assignedModel; // act var model = actionDescriptor.GetApiVersionModel(); // assert model.Should().Be(assignedModel); }
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()); }
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(); }