public void PerformDbOperation_Raises_PreOperation_and_PostOperation_Events() { _nDbUnitTestStub.PreOperation += new PreOperationEvent(sqlCeTest_PreOperation); _nDbUnitTestStub.PostOperation += new PostOperationEvent(sqlCeTest_PostOperation); //expectations SetupResult.For(_mockConnection.State).Return(ConnectionState.Closed); _mockDbCommandBuilder.BuildCommands(_mockSchemaFileStream); DataSet dummyDS = new DataSet(); dummyDS.ReadXmlSchema(ReadOnlyStreamFromFilename(GetXmlSchemaFilename())); SetupResult.For(_mockDbCommandBuilder.GetSchema()).Return(dummyDS); SetupResult.For(_mockDbCommandBuilder.Connection).Return(_mockConnection); //_mockConnection.Open(); _mockConnection.Open(); SetupResult.For(_mockConnection.BeginTransaction()).Return(_mockTransaction); _mockDbOperation.Update(dummyDS, _mockDbCommandBuilder, _mockTransaction); LastCall.IgnoreArguments().Constraints(Is.TypeOf <DataSet>(), Is.Equal(_mockDbCommandBuilder), Is.Equal(_mockTransaction)); _mockTransaction.Commit(); _mockTransaction.Dispose(); _mockConnection.Close(); //end expectations _mocker.ReplayAll(); _nDbUnitTestStub.ReadXmlSchema(GetXmlSchemaFilename()); _nDbUnitTestStub.ReadXml(GetXmlFilename()); _nDbUnitTestStub.PerformDbOperation(DbOperationFlag.Update); Assert.IsTrue(_preOperationCalled, "PreOperation() callback was not fired."); Assert.IsTrue(_postOperationCalled, "PostOperation() callback was not fired."); }
public void OneLinerChild_RoutedCorrectly() { var mr = new MockRepository(); var sut = new SemContextStub(); var expectedChildContext = MockRepository.GenerateStub <IAttributeContext>(); sut.AttributeContextFactory = () => expectedChildContext; var sectionContext = mr.StrictMock <ISemanticContext>(); sectionContext.Expect(sc => sc.FinishItem()); var itemContext = mr.StrictMock <ISemanticContext>(); itemContext.Expect(i => i.OnFinished += null).IgnoreArguments(); sectionContext.Expect(sc => sc.PushLine(0, null, null, null)) .Constraints(Is.Equal(0), Is.Same(null), Is.Equal("mykey"), Is.Anything()) .Return(itemContext); sut.S1Func = _ => sectionContext; mr.ReplayAll(); var result = sut.PushLine(0, "!s1", "mykey", new AhlAttribute[0]); Assert.AreSame(itemContext, result); itemContext.GetEventRaiser(i => i.OnFinished += null).Raise(itemContext, EventArgs.Empty); mr.VerifyAll(); }
public async void ShouldGetAllUsers() { var users = this.CreateUsers(NumberOfUsersToCreate); var usersOutput = this.CreateUsersDto(NumberOfUsersToCreate); using (this.Repository.Record()) { Expect.Call(this.DbContextScopeFactory.CreateReadOnly()); Expect.Call(this.UserRepository.GetAllListAsync()).Return(Task.FromResult(users)); Expect.Call(this.Mapper.Map <List <UserDto> >(null)).Constraints(Is.Equal(users)).Return(usersOutput).Repeat.Once(); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Getting Users"))).Repeat.Once(); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Got Users"))).Repeat.Once(); } using (this.Repository.Playback()) { var userApplicationService = new UserApplicationService( this.UserRepository, this.DbContextScopeFactory, this.Mapper, this.Logger); var output = await userApplicationService.GetAllUsers(); Assert.IsTrue(output.Users.Any()); Assert.AreEqual(usersOutput.Count, output.Users.Count); } }
public void ShouldCreateToDoItemWithEmptyUser() { var createToDoItemInput = new CreateToDoItemInput { AssignedUserId = null, Description = Faker.Lorem.Sentence() }; using (this.Repository.Record()) { Expect.Call(this.DbContextScopeFactory.Create()); Expect.Call(this.UserRepository.Get(string.Empty)).Constraints(Is.Equal(null)).Repeat.Never(); Expect.Call(this.ToDoItemRepository.Add(null)).Constraints(Is.Anything()).Repeat.Once(); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Creating ToDoItem for input:"))).Repeat.Once(); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Created ToDoItem for input:"))).Repeat.Once(); } using (this.Repository.Playback()) { var toDoItemApplicationService = new ToDoItemApplicationService( this.ToDoItemRepository, this.UserRepository, this.DbContextScopeFactory, this.Mapper, this.Logger); toDoItemApplicationService.CreateToDoItem(createToDoItemInput); } }
public void When_adding_remote_notification_listener_new_notification_listener_is_added_to_the_server() { _remoteServer.AddNotificationListener("Tests:key=value", OnNotificaion, null, null); _server.AssertWasCalled(x => x.AddNotificationListener("Tests:key=value", OnNotificaion, null, null), x => x.IgnoreArguments().Constraints(Is.Equal(new ObjectName("Tests:key=value")), Is.Anything(), Is.Anything(), Is.Anything())); }
public void ShouldUpdateToDoItemWithoutState() { var updateToDoItemInput = new UpdateToDoItemInput { AssignedUserId = Guid.NewGuid().ToString(), State = null }; var updatedToDoItem = this.CreateToDoItem(); var assignedUser = this.CreateUser(); using (this.Repository.Record()) { Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Updating ToDoItem for input:"))); Expect.Call(this.DbContextScopeFactory.Create()); Expect.Call(this.ToDoItemRepository.Get(0)).Constraints(Is.Equal(updateToDoItemInput.ToDoItemId)).Return(updatedToDoItem); Expect.Call(this.UserRepository.Get(string.Empty)).Constraints(Is.Equal(updateToDoItemInput.AssignedUserId)).Return(assignedUser); Expect.Call(this.Mapper.Map <ToDoItemState>(null)).Constraints(Is.Anything()).Repeat.Never(); Expect.Call(this.ToDoItemRepository.Update(null)).Constraints(Is.Equal(updatedToDoItem)).Return(updatedToDoItem); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Updated ToDoItem for input:"))); } using (this.Repository.Playback()) { var toDoItemApplicationService = new ToDoItemApplicationService( this.ToDoItemRepository, this.UserRepository, this.DbContextScopeFactory, this.Mapper, this.Logger); toDoItemApplicationService.UpdateToDoItem(updateToDoItemInput); Assert.AreEqual(assignedUser, updatedToDoItem.AssignedUser); } }
public void ShouldUpdateToDoItemWithoutUser() { var updateToDoItemInput = new UpdateToDoItemInput { AssignedUserId = null, State = (Perfectial.Application.Model.ToDoItemState) this.enumGenerator.Next(0, Enum.GetValues(typeof(Perfectial.Application.Model.ToDoItemState)).Length) }; var updatedToDoItem = this.CreateToDoItem(); var state = (ToDoItemState)this.enumGenerator.Next(0, Enum.GetValues(typeof(ToDoItemState)).Length); using (this.Repository.Record()) { Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Updating ToDoItem for input:"))); Expect.Call(this.DbContextScopeFactory.Create()); Expect.Call(this.ToDoItemRepository.Get(0)).Constraints(Is.Equal(updateToDoItemInput.ToDoItemId)).Return(updatedToDoItem); Expect.Call(this.UserRepository.Get(string.Empty)).Constraints(Is.Anything()).Repeat.Never(); Expect.Call(this.Mapper.Map <ToDoItemState>(null)).Constraints(Is.Equal(updateToDoItemInput.State.Value)).Return(state); Expect.Call(this.ToDoItemRepository.Update(null)).Constraints(Is.Equal(updatedToDoItem)).Return(updatedToDoItem); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Updated ToDoItem for input:"))); } using (this.Repository.Playback()) { var toDoItemApplicationService = new ToDoItemApplicationService( this.ToDoItemRepository, this.UserRepository, this.DbContextScopeFactory, this.Mapper, this.Logger); toDoItemApplicationService.UpdateToDoItem(updateToDoItemInput); Assert.AreEqual(state, updatedToDoItem.State); } }
private void AddStepConstraints(IMethodOptions <RhinoMocksExtensions.VoidType> methodOptions, ScenarioStep step, Dictionary <string, string> paramSubst) { methodOptions .IgnoreArguments() .Constraints( Is.Equal(GetReplacedText(step.Text, paramSubst)), Is.Equal(GetReplacedText(step.MultiLineTextArgument, paramSubst)), step.TableArg == null ? Is.Equal(null) : Is.NotNull()); }
public void should_pass_default_output_path_to_writer_if_not_set() { var writer = MockRepository.GenerateMock <IBulkPageWriter>(); var generator = new DocumentationGenerator(StubAssemblyLoader, StubXmlLoader, StubParser, writer, StubResourceManager, StubEventAggregator); generator.SetAssemblies(new[] { "unimportant_file_path" }); generator.Generate(); writer.AssertWasCalled(x => x.CreatePagesFromDirectory(null, null, null), x => x.Constraints(Is.Anything(), Is.Equal("output"), Is.Anything())); }
public void Count() { var sut = MockRepository.GenerateStub <ISimpleModel>(); sut.Stub(x => x.Do(Arg <List <int> > .List.Count(RIS.Equal(0)))).Return(0); sut.Stub(x => x.Do(Arg <List <int> > .List.Count(RIS.Equal(1)))).Return(1); Assert.That(sut.Do(new List <int>()).Equals(0)); Assert.That(sut.Do(new List <int> { 1 }).Equals(1)); }
public void should_move_untransformable_resources_to_output_dir() { var resourceManager = MockRepository.GenerateMock <IUntransformableResourceManager>(); var generator = new DocumentationGenerator(StubAssemblyLoader, StubXmlLoader, StubParser, StubWriter, resourceManager, StubEventAggregator); generator.SetAssemblies(new[] { "unimportant_file_path" }); generator.SetOutputPath("output-dir"); generator.Generate(); resourceManager.AssertWasCalled(x => x.MoveResources(null, null), x => x.Constraints(Is.Anything(), Is.Equal("output-dir"))); }
public void ShouldGetToDoItemsWithoutUserAndWithState() { var getToDoItemInput = new GetToDoItemInput { AssignedUserId = null, State = (Perfectial.Application.Model.ToDoItemState) this.enumGenerator.Next(0, Enum.GetValues(typeof(Perfectial.Application.Model.ToDoItemState)).Length) }; Assert.IsNotNull(getToDoItemInput.State); var toDoItemState = (ToDoItemState)getToDoItemInput.State; var index = 0; var toDoItems = this.CreateToDoItems(NumberOfToDoItemsToCreate).AsQueryable(); toDoItems.ToList().ForEach( toDoItem => { toDoItem.AssignedUserId = Guid.NewGuid().ToString(); if (index++ % 2 == 1) { toDoItem.State = toDoItemState; } else { while (toDoItem.State == toDoItemState) { toDoItem.State = (ToDoItemState)this.enumGenerator.Next(0, Enum.GetValues(typeof(ToDoItemState)).Length); } } }); using (this.Repository.Record()) { Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Getting ToDoItems for input:"))); Expect.Call(this.DbContextScopeFactory.CreateReadOnly()); Expect.Call(this.ToDoItemRepository.GetAll()).Return(toDoItems); Expect.Call(this.Mapper.Map <ToDoItemState>(null)).Constraints(Is.Equal(getToDoItemInput.State)).Return(toDoItemState).Repeat.AtLeastOnce(); Expect.Call(this.Mapper.Map <List <ToDoItemDto> >(Arg <List <ToDoItem> > .List.Count(Is.Equal(toDoItems.Count() / 2)))); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Got ToDoItems output:"))); } using (this.Repository.Playback()) { var toDoItemApplicationService = new ToDoItemApplicationService( this.ToDoItemRepository, this.UserRepository, this.DbContextScopeFactory, this.Mapper, this.Logger); toDoItemApplicationService.GetToDoItems(getToDoItemInput); } }
/// <summary> /// Ensures, that all interface methods delegate to Write() with correct level + arguments /// and that arguments are still not evaluated up to this point (e.g. calling ToString()) /// </summary> private static void WriteIsCalledWithCorrectLogLevel(string levelName) { MockRepository mocks = new MockRepository(); AbstractTestLogger log = (AbstractTestLogger)mocks.PartialMock(typeof(AbstractTestLogger)); Exception ex = (Exception)mocks.StrictMock(typeof(Exception)); object messageObject = mocks.StrictMock(typeof(object)); object formatArg = mocks.StrictMock(typeof(object)); FormatMessageCallback failCallback = TestFormatMessageCallback.FailCallback(); MethodInfo[] logMethods = GetLogMethodSignatures(levelName); LogLevel logLevel = (LogLevel)Enum.Parse(typeof(LogLevel), levelName); using (mocks.Ordered()) { log.Log(logLevel, null, null); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Null()); log.Log(logLevel, null, ex); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Same(ex)); log.Log(logLevel, null, null); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Null()); log.Log(logLevel, null, ex); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Same(ex)); log.Log(logLevel, null, null); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Null()); log.Log(logLevel, null, ex); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Same(ex)); log.Log(logLevel, null, null); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Null()); log.Log(logLevel, null, ex); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Same(ex)); log.Log(logLevel, null, null); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Null()); log.Log(logLevel, null, ex); LastCall.Constraints(Is.Equal(logLevel), Is.Anything(), Is.Same(ex)); } mocks.ReplayAll(); Invoke(log, logMethods[0], messageObject); Invoke(log, logMethods[1], messageObject, ex); Invoke(log, logMethods[2], "format", new object[] { formatArg }); Invoke(log, logMethods[3], "format", ex, new object[] { formatArg }); Invoke(log, logMethods[4], CultureInfo.InvariantCulture, "format", new object[] { formatArg }); Invoke(log, logMethods[5], CultureInfo.InvariantCulture, "format", ex, new object[] { formatArg }); Invoke(log, logMethods[6], failCallback); Invoke(log, logMethods[7], failCallback, ex); Invoke(log, logMethods[8], CultureInfo.InvariantCulture, failCallback); Invoke(log, logMethods[9], CultureInfo.InvariantCulture, failCallback, ex); mocks.VerifyAll(); }
public void RefExample() { int refValue = 0; var sut = MockRepository.GenerateStub <ISimpleModel> (); sut.Stub(x => x.Do(Arg <int> .Is.Equal(1), ref Arg <int> .Ref(RIS.Equal(0), 10).Dummy)).Return(1); var value = sut.Do(1, ref refValue); Assert.That(value.Equals(1)); Assert.That(refValue.Equals(10)); }
public void When_removing_specific_remote_notification_listener_only_this_listener_is_removed_from_the_server() { _remoteServer.AddNotificationListener("Tests:key=value", OnNotificaion, null, 1); _remoteServer.AddNotificationListener("Tests:key=value", OnNotificaion, null, 2); _remoteServer.RemoveNotificationListener("Tests:key=value", OnNotificaion, null, 1); //Force wait for possibly asynchornous Remove to complete. _remoteServer.AddNotificationListener("Tests:key=value", OnNotificaion, null, null); _server.AssertWasCalled(x => x.RemoveNotificationListener("Tests:key=value", OnNotificaion, null, null), x => x.IgnoreArguments() .Constraints(Is.Equal(new ObjectName("Tests:key=value")), Is.Anything(), Is.Anything(), Is.Anything()) .Repeat.Once()); }
public void FizzBuzzGeneratorShouldPrintFizzBuzzForMultiplesOfThreeAndFive() { // Arrange _console = MockRepository.GenerateMock <IConsole>(); var generator = new FizzBuzzGenerator(_console); _console.Expect(x => x.Print(Arg <string> .Matches(Is.Equal("FizzBuzz")))).Repeat.AtLeastOnce(); // Act generator.Start(); // Assert _console.VerifyAllExpectations(); }
public void Derives_valid_filename_from_session_factory_ID_when_not_explicitly_specified() { var configurationPersister = MockRepository.GenerateMock <IConfigurationPersister>(); configurationPersister.Expect(x => x.IsNewConfigurationRequired(null, null)) .IgnoreArguments() .Constraints(Is.Equal("sessionFactory1.dat"), Is.Anything()) .Return(false); var builder = new PersistentConfigurationBuilder(configurationPersister); builder.GetConfiguration(facilityCfg); configurationPersister.VerifyAllExpectations(); }
private void ExpectLine(int lineNumber, int indent, string keyword, string key, params AhlAttribute[] ahlAttributes) { _parsingContext.Expect(c => c.PushLine(lineNumber, indent, keyword, key, ahlAttributes)) .IgnoreArguments() .Constraints( Is.Equal(lineNumber), Is.Equal(indent), Is.Equal(keyword), Is.Equal(key), Is.Matching <List <AhlAttribute> >(list => { CollectionAssert.AreEqual(ahlAttributes, list, new AhlAttributeComparer()); return(true); })); }
public void should_pass_document_model_to_writer() { var writer = MockRepository.GenerateMock <IBulkPageWriter>(); var generator = new DocumentationGenerator(StubAssemblyLoader, StubXmlLoader, StubParser, writer, StubResourceManager, StubEventAggregator); var documentModel = new List <Namespace>(); StubParser.Stub(x => x.CreateDocumentModel(null, null)) .IgnoreArguments() .Return(documentModel); generator.SetAssemblies(new [] { "unimportant_file_path" }); generator.Generate(); writer.AssertWasCalled(x => x.CreatePagesFromDirectory(null, null, null), x => x.Constraints(Is.Anything(), Is.Anything(), Is.Equal(documentModel))); }
public void TestIfNotInCacheCacheTheQuery() { ICache cache = MockRepository.GenerateStub <ICache>(); DisposeAtTheEndOfTest(GlobalCache.Override(cache)); var Query = "select Id from Table1 where Name = {param}"; var ExpandedQuery = "select Id from Table1 where Name = :param"; cache.Expect(c => c.Insert(null, null, null, null, null)) .Constraints(RhinoIs.Equal(Query), RhinoIs.Equal("DataAccess"), RhinoIs.Equal(ExpandedQuery), RhinoIs.Anything(), RhinoIs.Anything()) .Return(ExpandedQuery); cache.Expect(c => c.Get <String>(Query)).Return(null); Int64 result = DataAccess.CreateQuery(Query).SetStringParam("param", "OtherTest").ExecuteScalar <Int64>(); Assert.That(result, Is.EqualTo(2)); }
protected override void beforeEach() { theAssetPath = new AssetPath("scripts/something") { ResourceHash = Guid.NewGuid().ToString() }; MockFor <IContentWriter>().Expect(x => x.Write(theAssetPath, null)) .Constraints(Is.Equal(theAssetPath), Is.NotNull()) .Return(false); FubuMode.Reset(); FubuMode.InDevelopment().ShouldBeFalse(); ClassUnderTest.Write(theAssetPath); }
public void RunSubmitAdRequest() { var mockery = new MockRepository(); var restClient = mockery.StrictMock <IRestClient>(); var restRequestFactory = mockery.StrictMock <IRestRequestFactory>(); var restRequest = mockery.StrictMock <IRestRequest>(); var serializer = mockery.Stub <ISerializer>(); var str = "some data"; var adRequest = new AdRequest { NetworkId = Guid.NewGuid().ToString() }; var ad = new AdvertisementMessage { id = "test" }; var ads = new List <AdvertisementMessage> { ad }; var advertisementResponse = new AdvertisementResponseMessage { advertisement = ads }; var restResponse = new RestResponse <AdvertisementResponseMessage>(); restResponse.Data = advertisementResponse; using (mockery.Record()) { Expect.Call(restRequestFactory.Create(null, Method.POST)) .Constraints(Is.Anything(), Is.Equal(Method.POST)) .Return(restRequest); restRequest.RequestFormat = DataFormat.Json; Expect.Call(restRequest.JsonSerializer).Return(serializer); Expect.Call(serializer.Serialize(null)).Constraints( Rhino.Mocks.Constraints.Property.Value("network_id", adRequest.NetworkId) && Is.TypeOf <AdRequestMessage>() ).Return(str); Expect.Call(restRequest.AddParameter("text/json", str, ParameterType.RequestBody)).Return(new RestRequest()); Expect.Call(restClient.Execute <AdvertisementResponseMessage>(restRequest)).Return(restResponse); } using (mockery.Playback()) { var results = new AdRequestor(restClient, restRequestFactory).RunSubmitAdRequest(adRequest); Assert.AreEqual(ad.id, results[0].Id); } }
public void TestThatAddedElementAlwaysRaiseEvent() { BindingListExt <Customer> sut = CreateBindingListOnBasicCustomersList(); IBindingListEventSink mock = mockRepository.CreateMock <IBindingListEventSink>(); sut.AddingNew += mock.HandleAdded; Customer cust = new Customer() { Name = "Mark Fields", Age = 28 }; Expect.Call(() => mock.HandleAdded(sut, null)) .Constraints(RhinoIs.Equal(sut), RhinoIs.Matching <AddingNewEventArgs>(args => args.NewObject == cust)) .Repeat.Once(); mockRepository.ReplayAll(); sut.Filter = "Name == 'Alkampfer'"; sut.Add(cust); }
private void AddPushLine(int line, int indent, string keyword, string key, params AhlAttribute[] ahlAttributes) { var plo = new PushLineObject(line, indent, keyword, key, ahlAttributes); _semanticContext.Expect(sc => sc.PushLine(line, keyword, key, ahlAttributes)) .IgnoreArguments() .Constraints( Is.Equal(line), Is.Equal(keyword), Is.Equal(key), Is.Matching <List <AhlAttribute> >(list => { CollectionAssert.AreEqual(ahlAttributes, list, new AhlAttributeComparer()); return(true); })) .Return(_semanticContext); _scheduledPushLines.Add(plo); }
public void LogExceptionWhenCommitt() { Action <Boolean> mock1 = mockRepository.CreateMock <Action <Boolean> >(); Exception ex = new ArgumentException(); Expect.Call(() => mock1(true)).Throw(ex); //Sets the expectation ILogger mockLogger = mockRepository.CreateMock <ILogger>(); Expect.Call(mockLogger.ActualLevel).Repeat.Any().Return(LogLevel.Info); Expect.Call(() => mockLogger.LogError("", ex)) .Constraints(RhinoIs.Anything(), RhinoIs.Equal(ex)); mockRepository.ReplayAll(); using (Logger.Override(mockLogger)) { using (GlobalTransactionManager.BeginTransaction()) { GlobalTransactionManager.Enlist(mock1); } } }
public void Element() { var sut = MockRepository.GenerateStub <ISimpleModel>(); sut.Stub(x => x.Do(Arg <List <int> > .List.Element(0, RIS.Equal(1)))).Return(1); sut.Stub(x => x.Do(Arg <List <int> > .List.Element(1, RIS.GreaterThanOrEqual(2)))).Return(2); Assert.That(sut.Do(new List <int> { 0, 0 }).Equals(0)); Assert.That(sut.Do(new List <int> { 1, 0 }).Equals(1)); Assert.That(sut.Do(new List <int> { 0, 2 }).Equals(2)); Assert.That(sut.Do(new List <int> { 0, 20 }).Equals(2)); }
public void Handling_ref_parameters_in_stubs() { var stub = MockRepository.GenerateStub <ISampleClass>(); // Here's how you stub an "ref" parameter. The "Dummy" part is // just to satisfy the compiler. (Note: Is.Equal() is part of // the Rhino.Mocks.Contraints namespace, there is also an // Is.EqualTo() in NUnit... you want the Rhino Mocks one.) stub.Stub(s => s.MethodWithRefParameter(ref Arg <string> .Ref(Is.Equal("input"), "output").Dummy)); // If you call the method with the specified input argument, it will // change the parameter to the value you specified. string param = "input"; stub.MethodWithRefParameter(ref param); param.ShouldEqual("output"); // If I call the method with any other input argument, it won't // change the value. param = "some other value"; stub.MethodWithRefParameter(ref param); param.ShouldEqual("some other value"); }
public void RunSubmitAdRequest_Throws_ApiException_When_Error() { var mockery = new MockRepository(); var restClient = mockery.StrictMock <IRestClient>(); var restRequestFactory = mockery.StrictMock <IRestRequestFactory>(); var restRequest = mockery.DynamicMock <IRestRequest>(); var serializer = mockery.Stub <ISerializer>(); var str = "some data"; var error = "Test error message"; var adRequest = new AdRequest { NetworkId = Guid.NewGuid().ToString() }; using (mockery.Record()) { Expect.Call(restRequestFactory.Create(null, Method.POST)) .Constraints(Is.Anything(), Is.Equal(Method.POST)) .Return(restRequest); restRequest.RequestFormat = DataFormat.Json; Expect.Call(restRequest.JsonSerializer).Return(serializer); Expect.Call(serializer.Serialize(null)).Constraints( Rhino.Mocks.Constraints.Property.Value("network_id", adRequest.NetworkId) && Is.TypeOf <AdRequestMessage>() ).Return(str); Expect.Call(restRequest.AddParameter("text/json", str, ParameterType.RequestBody)).Return(new RestRequest()); Expect.Call(restClient.Execute <AdvertisementResponseMessage>(restRequest)).Throw(new Exception(error)); } using (mockery.Playback()) { var ex = Assert.Throws(typeof(ApiException), () => { new AdRequestor(restClient, restRequestFactory).RunSubmitAdRequest(adRequest); }); Assert.AreEqual(error, ex.Message); } }
protected override void beforeEach() { thePart = new Part { Name = "something" }; Services.Inject <ISimplePropertyHandler <Part> >(Services.Container.GetInstance <SimplePropertyHandler <Part> >()); var theProperty = ReflectionHelper.GetProperty <Part>(c => c.WarrantyDays); MockFor <IFieldAccessService>().Stub(x => x.RightsFor(thePart, theProperty)).Return(AccessRight.ReadOnly).Constraints(Is.Equal(thePart), Is.Matching <PropertyInfo>(x => x.Name == theProperty.Name)); var update = new UpdatePropertyModel <Part>() { Id = Guid.NewGuid(), PropertyName = "WarrantyDays", PropertyValue = "abc", }; MockFor <IRepository>().Stub(x => x.Find <Part>(update.Id)).Return(thePart); result = ClassUnderTest.EditProperty(update); }
public void ItShouldUseTheFileCopierToCopyTheFiles() { FileCopier.AssertWasCalled( c => c.CopyFilesToTarget(null, null, null, 0, false), o => o.Constraints(Is.NotNull(), Is.Equal(@"c:\media\blah"), Is.Equal(@"k:\podcasts"), Is.Equal(500L), Is.Equal(false))); }