public void HandlesAndRethrowsExceptionWhenNegativeNumber() { var mocks = new MockRepository(); var knaryTreeApp = mocks.PartialMock <KnaryTreeApp>(); var knaryTree = mocks.PartialMock <KnaryTree>(2); var readerStream = new MemoryStream(Encoding.ASCII.GetBytes("2\n-1\n0")); var result = new byte[3]; var writerStream = new MemoryStream(result); using (mocks.Record()) { Expect.Call(knaryTreeApp.CreateTree(2)).Return(knaryTree); knaryTree.StoreNumber(1); LastCall.Throw(new OverflowException("exception")); Expect.Call(knaryTree.OutputPostOrder()).Return("01"); } try { knaryTreeApp.ParseData(readerStream, writerStream); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(ApplicationException)); Assert.AreEqual("Please verify line number: 2. Numbers can not be negative.", e.Message); } }
public void WhenThrowingExceptionAfterEmptyLine_GivesLineNumberOfTheFirstInvalidLine() { var mocks = new MockRepository(); var knaryTreeApp = mocks.PartialMock <KnaryTreeApp>(); var knaryTree = mocks.PartialMock <KnaryTree>(2); var readerStream = new MemoryStream(Encoding.ASCII.GetBytes("20\n\na")); var result = new byte[3]; var writerStream = new MemoryStream(result); using (mocks.Record()) { Expect.Call(knaryTreeApp.CreateTree(2)).Return(knaryTree); knaryTree.StoreNumber(1); LastCall.Throw(new FormatException("exception")); Expect.Call(knaryTree.OutputPostOrder()).Return("01"); } try { knaryTreeApp.ParseData(readerStream, writerStream); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(ApplicationException)); Assert.AreEqual( "Input has to start with K-nary tree order number. Order must be higher than 1 or lower than 10. Please verify line number: 1", e.Message); } }
public static void RhinoMockReturnsTestValue() { MockRepository rhinoEngine = new MockRepository(); ITestMock testMock = rhinoEngine.DynamicMock <ITestMock>(); using (rhinoEngine.Record()) { testMock.ReturnSomeString(1); LastCall.Return("string1"); testMock.ReturnSomeString(2); LastCall.Throw(new ArgumentException()); int input = 3; testMock.ReturnSomeString(input); LastCall.Do(new TestDelegate((inp) => "string" + inp)); } string result = testMock.ReturnSomeString(1); Assert.AreEqual("string1", result); Assert.Throws <ArgumentException>(() => testMock.ReturnSomeString(2)); result = testMock.ReturnSomeString(3); Assert.AreEqual("string3", result); }
public void WhenInvalidCharacters_ThrowsExceptionGivesNumberOfFirstInvalidLine() { var mocks = new MockRepository(); var knaryTreeApp = mocks.PartialMock <KnaryTreeApp>(); var knaryTree = mocks.PartialMock <KnaryTree>(2); var readerStream = new MemoryStream(Encoding.ASCII.GetBytes("2\na")); var result = new byte[3]; var writerStream = new MemoryStream(result); using (mocks.Record()) { Expect.Call(knaryTreeApp.CreateTree(2)).Return(knaryTree); knaryTree.StoreNumber(1); LastCall.Throw(new FormatException("exception")); Expect.Call(knaryTree.OutputPostOrder()).Return("01"); } try { knaryTreeApp.ParseData(readerStream, writerStream); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(ApplicationException)); Assert.AreEqual("Please verify line number: 2", e.Message); } }
public static void PropertyConstraintTestUsingAnd() { var excepetionToThrow = new Exception("TestMessage"); MockRepository rhinoEngine = new MockRepository(); var mailService = rhinoEngine.DynamicMock <IMailService>(); var logService = rhinoEngine.Stub <ILogService>(); FileManager mgr = new FileManager(logService, mailService); And addStatement = new And(Property.Value("Destination", "*****@*****.**"), Property.Value("Theme", excepetionToThrow.GetType().Name)); And combinedAnd = new And(addStatement, Property.Value("MessageText", excepetionToThrow.Message)); using (rhinoEngine.Record()) { logService.LogError("Anything"); LastCall.Constraints(new Anything()); LastCall.Throw(excepetionToThrow); mailService.SendMail(null); LastCall.Constraints(combinedAnd); } mgr.Analize("file.exe"); rhinoEngine.VerifyAll(); }
public void LastCallThrow() { demo.VoidNoArgs(); LastCall.Throw(new Exception("Bla!")); mocks.ReplayAll(); Assert.Throws <Exception>("Bla!", demo.VoidNoArgs); }
public void NoExceptionHandling() { var repo = new MockRepository(); var action = repo.CreateMock <Action>(); var failure = new Exception(); action(); LastCall.Throw(failure); repo.ReplayAll(); var queue = new DefaultQueue(); queue.Enqueue(action); try { queue.ExecuteNextBatch(); Assert.Fail("Should throw Exception"); } catch (Exception commFailure) { Assert.AreSame(failure, commFailure); } repo.VerifyAll(); }
public void JustPassesAfterReturningAdviceExceptionUpWithoutAnyWrapping() { MockRepository repository = new MockRepository(); IMethodInvocation mockInvocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); IAfterReturningAdvice mockAdvice = (IAfterReturningAdvice)repository.CreateMock(typeof(IAfterReturningAdvice)); mockAdvice.AfterReturning(null, null, null, null); LastCall.IgnoreArguments(); LastCall.Throw(new FormatException()); Expect.Call(mockInvocation.Method).Return(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { })); Expect.Call(mockInvocation.Arguments).Return(null); Expect.Call(mockInvocation.This).Return(new object()); Expect.Call(mockInvocation.Proceed()).Return(null); repository.ReplayAll(); try { AfterReturningAdviceInterceptor interceptor = new AfterReturningAdviceInterceptor(mockAdvice); interceptor.Invoke(mockInvocation); Assert.Fail("Must have thrown a FormatException by this point."); } catch (FormatException) { } repository.VerifyAll(); }
public void Correctly_handles_when_service_agent_aggregator_throws_exception() { ApplicationException exception = new ApplicationException(); MockRepository mocks = new MockRepository(); IApplicationSettings settings = mocks.CreateMock <IApplicationSettings>(); IServiceAgentAggregator aggregator = mocks.CreateMock <IServiceAgentAggregator>(); IServiceRunner runner = new ServiceRunner(aggregator, settings); using (mocks.Record()) { aggregator.ExecuteServiceAgentCycle(); LastCall.Throw(exception); } using (mocks.Playback()) { runner.Start(); Thread.Sleep(500); runner.Stop(); } mocks.VerifyAll(); }
public void CanUseBackToRecordOnMethodsThatCallToCallOriginalMethod() { MockRepository repository = new MockRepository(); TestClass mock = repository.StrictMock <TestClass>(); mock.Method(); LastCall.CallOriginalMethod (OriginalCallOptions.NoExpectation); repository.ReplayAll(); mock.Method(); repository.VerifyAll(); repository.BackToRecordAll(); mock.Method(); LastCall.Throw(new ApplicationException()); repository.ReplayAll(); try { mock.Method(); Assert.False(true); } catch { } repository.VerifyAll(); }
public void WhenInputDoesntEndWithZero_ThrowsExceptionAndGivesLineNumberOfTheInvalidLine() { var mocks = new MockRepository(); var knaryTreeApp = mocks.PartialMock <KnaryTreeApp>(); var knaryTree = mocks.PartialMock <KnaryTree>(2); var readerStream = new MemoryStream(Encoding.ASCII.GetBytes("2\n\n")); var result = new byte[3]; var writerStream = new MemoryStream(result); using (mocks.Record()) { Expect.Call(knaryTreeApp.CreateTree(2)).Return(knaryTree); knaryTree.StoreNumber(1); LastCall.Throw(new FormatException("exception")); Expect.Call(knaryTree.OutputPostOrder()).Return("01"); } try { knaryTreeApp.ParseData(readerStream, writerStream); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(ApplicationException)); Assert.AreEqual("Input file has to be ended with '0'", e.Message); } }
public static void FileManagerIsMatchingConstraintTest() { var excepetionToThrow = new Exception("TestMessage"); MockRepository rhinoEngine = new MockRepository(); var mailService = rhinoEngine.DynamicMock <IMailService>(); var logService = rhinoEngine.Stub <ILogService>(); FileManager mgr = new FileManager(logService, mailService); using (rhinoEngine.Record()) { logService.LogError("Anything"); LastCall.Constraints(new Anything()); LastCall.Throw(excepetionToThrow); mailService.SendMail(null); LastCall.Constraints(Rhino.Mocks.Constraints.Is.Matching <MailMessage>( message => { if (message.Destination == "*****@*****.**" && message.Theme == excepetionToThrow.GetType().Name&& message.MessageText == excepetionToThrow.Message) { return(true); } return(false); })); } mgr.Analize("file.exe"); rhinoEngine.VerifyAll(); }
public void Analyze_WebServiceThrows_SendsEmail() { MockRepository mocks = new MockRepository(); IWebService stubService = mocks.Stub <IWebService>(); IEmailService mockEmail = mocks.StrictMock <IEmailService>(); using (mocks.Record()) { stubService.LogError("aaa"); LastCall.Constraints(Is.Anything()); LastCall.Throw(new Exception("가짜 예외")); mockEmail.SendEmail("a", "subject", "가짜 예외"); } LogAnalyzer2 log = new LogAnalyzer2(); log.Service = stubService; log.Email = mockEmail; string tooShortFileName = "abc.ext"; log.Analyze(tooShortFileName); mocks.VerifyAll(); }
public void Migrate_NoDiagnosticsAndThrows_Rollsback() { _steps[string.Empty][0].DatabaseMigration = _migration1; _steps[string.Empty][1].DatabaseMigration = _migration2; using (_mocks.Record()) { Expect.Call(_transactionProvider.Begin()).Return(_transaction); _migration1.Up(); _schemaStateManager.SetMigrationVersionApplied(1, null); _transaction.Commit(); Expect.Call(_transactionProvider.Begin()).Return(_transaction); _migration2.Up(); LastCall.Throw(new ArgumentException()); _transaction.Rollback(); } bool caught = false; try { _target.Migrate(_steps); } catch (ArgumentException) { caught = true; } Assert.IsTrue(caught); _mocks.VerifyAll(); }
public void StubSimulatingException() { MockRepository repository = new MockRepository(); IGetRestuls resultGetter = repository.Stub <IGetRestuls>(); using (repository.Record()) { resultGetter.GetSomeNumber("A"); LastCall.Throw(new OutOfMemoryException("The system is out of memory!")); } resultGetter.GetSomeNumber("A"); }
private void AssertExceptionIsCaughtAndHttpStatusCodeReturnedForCreateWorkItem(Exception exception, HttpStatusCode httpStatusCode) { using (_mocks.Record()) { _workflow.CreateWorkItem(WorkItem.New("id1", "/")); LastCall.Throw(exception); } using (_mocks.Playback()) { var request = CreateCsvPostRequest("/", "id=id1"); Assert.AreEqual(httpStatusCode, _httpHandler.HandleRequest(request).HttpStatusCode); } }
private void AssertExceptionIsCaughtAndHttpStatusCodeReturnedForCreateWorkStep(Exception exception, HttpStatusCode httpStatusCode) { using (_mocks.Record()) { _workflow.CreateWorkStep(WorkStep.New("/scheduled").UpdateWorkItemClass("cr")); LastCall.Throw(exception); } using (_mocks.Playback()) { var request = CreateCsvPostRequest("/", "step=scheduled,class=cr"); Assert.AreEqual(httpStatusCode, _httpHandler.HandleRequest(request).HttpStatusCode); } }
public void IgnoreExceptionWhenCommitt() { Action <Boolean> mock1 = mockRepository.CreateMock <Action <Boolean> >(); mock1(true); //Sets the expectation LastCall.Throw(new ApplicationException()); Action <Boolean> mock2 = mockRepository.CreateMock <Action <Boolean> >(); mock2(true); //Sets the expectation mockRepository.ReplayAll(); using (GlobalTransactionManager.BeginTransaction()) { GlobalTransactionManager.Enlist(mock1); GlobalTransactionManager.Enlist(mock2); } }
public void CanStrictMockOnClassWithInternalMethod() { WithInternalMethod withInternalMethod = mocks.StrictMock <WithInternalMethod>(); withInternalMethod.Foo(); LastCall.Throw(new Exception("foo")); mocks.ReplayAll(); try { withInternalMethod.Foo(); Assert.False(true, "Should have thrown"); } catch (Exception e) { Assert.Equal("foo", e.Message); } }
public void WhenExceptionOccures_WritesMessageToConsole() { var mocks = new MockRepository(); var knaryTreeApp = mocks.StrictMock <KnaryTreeApp>(); var applicationRunner = mocks.StrictMock <ApplicationRunner>(knaryTreeApp); using (mocks.Record()) { applicationRunner.WriteToConsole(null); LastCall.IgnoreArguments(); LastCall.Throw(new Exception("Exception Message")); applicationRunner.WriteToConsole("Exception Message"); } using (mocks.Playback()) { applicationRunner.Run(new string[] { }); } }
public void SchedulerHandlesJobStoreConcurrentModificationExceptionByIgnoringTheJob() { // The mock job watcher will return job detail on the first GetNextJobToProcess // but the mock job store will throw ConcurrentModificationException during SaveJobDetails. // On the second call to GetNextJobToProcess the mock job watcher will cause us to wake up. // There should be no noticeable delay, particularly not one as big as the error recovery delay. JobDetails jobDetails = new JobDetails(dummyJobSpec, DateTime.UtcNow); jobDetails.JobState = JobState.Pending; Expect.Call(mockTrigger.Schedule(TriggerScheduleCondition.Latch, DateTime.UtcNow, null)) .Constraints(Rhino.Mocks.Constraints.Is.Equal(TriggerScheduleCondition.Latch), Rhino.Mocks.Constraints.Is.Anything(), Rhino.Mocks.Constraints.Is.Null()) .Return(TriggerScheduleAction.Stop); Expect.Call(mockTrigger.NextFireTimeUtc).Return(new DateTime(1970, 1, 5, 0, 0, 0, DateTimeKind.Utc)); Expect.Call(mockTrigger.NextMisfireThreshold).Return(new TimeSpan(0, 1, 0)); mockJobStore.SaveJobDetails(jobDetails); LastCall.Throw(new ConcurrentModificationException("Another scheduler grabbed it.")); IJobWatcher mockJobWatcher = Mocks.CreateMock <IJobWatcher>(); Expect.Call(mockJobWatcher.GetNextJobToProcess()).Return(jobDetails); Expect.Call(mockJobWatcher.GetNextJobToProcess()).Do((GetNextJobToProcessDelegate) delegate { Wake(); return(null); }); mockJobWatcher.Dispose(); LastCall.Repeat.AtLeastOnce(); Expect.Call(mockJobStore.CreateJobWatcher(scheduler.Guid)).Return(mockJobWatcher); Mocks.ReplayAll(); scheduler.ErrorRecoveryDelayInSeconds = 2; Stopwatch stopWatch = Stopwatch.StartNew(); RunSchedulerUntilWake(); Assert.Less(stopWatch.ElapsedMilliseconds, 2000); }
public void SchedulerHandlesJobStoreExceptionByInsertingAnErrorRecoveryDelay() { // The mock job watcher will return job detail on the first GetNextJobToProcess // but the mock job store will throw Expection during SaveJobDetails. // On the second call to GetNextJobToProcess the mock job watcher will cause us to wake up. // There should be a total delay at least as big as the error recovery delay. JobDetails jobDetails = new JobDetails(dummyJobSpec, DateTime.UtcNow); jobDetails.JobState = JobState.Pending; Expect.Call(mockTrigger.Schedule(TriggerScheduleCondition.Latch, DateTime.UtcNow, null)) .Constraints(Rhino.Mocks.Constraints.Is.Equal(TriggerScheduleCondition.Latch), Rhino.Mocks.Constraints.Is.Anything(), Rhino.Mocks.Constraints.Is.Null()) .Return(TriggerScheduleAction.Stop); Expect.Call(mockTrigger.NextFireTimeUtc).Return(new DateTime(1970, 1, 5, 0, 0, 0, DateTimeKind.Utc)); Expect.Call(mockTrigger.NextMisfireThreshold).Return(new TimeSpan(0, 1, 0)); mockJobStore.SaveJobDetails(jobDetails); LastCall.Throw(new Exception("Uh oh!")); IJobWatcher mockJobWatcher = Mocks.CreateMock <IJobWatcher>(); Expect.Call(mockJobWatcher.GetNextJobToProcess()).Return(jobDetails); Expect.Call(mockJobWatcher.GetNextJobToProcess()).Do((GetNextJobToProcessDelegate) delegate { Wake(); return(null); }); mockJobWatcher.Dispose(); LastCall.Repeat.AtLeastOnce(); Expect.Call(mockJobStore.CreateJobWatcher(scheduler.Guid)).Return(mockJobWatcher); Mocks.ReplayAll(); scheduler.ErrorRecoveryDelayInSeconds = 2; Stopwatch stopWatch = Stopwatch.StartNew(); RunSchedulerUntilWake(); Assert.That(stopWatch.ElapsedMilliseconds, NUnit.Framework.Is.GreaterThanOrEqualTo(2000).And.LessThanOrEqualTo(10000)); }
//[Test] public void Analyze_WebServiceThrows_SendsEmail2() { var mocks = new MockRepository(); var stubService = mocks.Stub <IWebService>(); var mockEmail = mocks.StrictMock <IEmailService>(); using (mocks.Record()) { stubService.LogError("whatever"); LastCall.Constraints(new Anything()); LastCall.Throw(new Exception("fake exception")); mockEmail.SendEmail("a", "subject", "fake exception"); } LogAnalyzer2 log = new LogAnalyzer2(stubService, mockEmail); string tooShortFileName = "abc.ext"; log.Analyze(tooShortFileName); mocks.VerifyAll(); }
public static void MockAndStubTest() { string fileName = "SomeFile.log"; MockRepository rhinoEngine = new MockRepository(); var logService = rhinoEngine.Stub <ILogService>(); var mailService = rhinoEngine.DynamicMock <IMailService>(); using (rhinoEngine.Record()) { logService.LogError("Whatever"); LastCall.Constraints(new Rhino.Mocks.Constraints.Anything()); LastCall.Throw(new Exception("TestMessage")); mailService.SendMail("*****@*****.**", "TestMessage"); } FileManager mgr = new FileManager(logService, mailService); mgr.Analize(fileName); rhinoEngine.VerifyAll(); }
public void TestDisposeWithException() { Context context = new Context(); context.DisposeMembersOnTestCaseCompletion = true; IDisposable disposable = mockery.DynamicMock <IDisposable>(); IEnumerable notDisposable = mockery.DynamicMock <IEnumerable>(); context.Add("DisposableClassKey", disposable); context.Add("NotDisposableClassKey", notDisposable); using (mockery.Record()) { disposable.Dispose(); LastCall.Throw(new ApplicationException("Exception thrown during dispose.")).Repeat.Once(); } using (mockery.Playback()) { BizUnit.BizUnit bizUnit = new BizUnit.BizUnit(new BizUnitTestCase("TestDisposeWithException"), context); bizUnit.RunTest(); } }
public void Correctly_swallows_exception_from_render_and_returns_error_message() { MockRepository mocks = new MockRepository(); ILoadBalanceStatusManager manager = mocks.CreateMock <ILoadBalanceStatusManager>(); ILoadBalancerView view = mocks.CreateMock <ILoadBalancerView>(); IWebContext context = mocks.CreateMock <IWebContext>(); Exception exception = mocks.PartialMock <Exception>(); using (mocks.Record()) { SetupResult.For(exception.ToString()).Return("My exception message"); Expect.Call(manager.HandleLoadBalanceRequest()).Return(string.Empty); view.Render(string.Empty); LastCall.Throw(exception); context.WriteToResponse("My exception message"); } using (mocks.Playback()) { IExceptionHandlingLoadBalanceStatusManager statusManager = new ExceptionHandlingLoadBalanceStatusManager(manager, view, context); statusManager.HandleLoadBalancing(); } }