Example #1
0
        public void VoidMethodWithThrows(
            IFoo foo,
            Action action,
            Exception exception)
        {
            "Given a fake"
                .x(() => foo = A.Fake<IFoo>());

            "And an action"
                .x(() => action = A.Fake<Action>());

            "When a void method is configured to invoke a delegate twice then throw an exception"
                .x(() =>
                    A.CallTo(() => foo.Bar()).Invokes(action).DoesNothing().Twice()
                        .Then.Throws<InvalidOperationException>());

            "And the method is called 3 times"
                .x(() =>
                {
                    foo.Bar();
                    foo.Bar();
                    exception = Record.Exception(() => foo.Bar());
                });

            "Then the delegate is invoked twice"
                .x(() => A.CallTo(() => action()).MustHaveHappened(Repeated.Exactly.Twice));

            "And the third call throws an exception"
                .x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
        }
Example #2
0
        public void ExceptionInStage(TrackedCommand command, Exception exception)
        {
            "Given I have a command"
                .Given(() =>
                {
                    command = new TrackedCommand { A = 1, B = 2 };
                });

            "And a pipeline stage which causes an exception"
                .And(() =>
                {
                    var stageA = new ExceptionPipelineStage {Next = pipeline.IssueCommand};
                    pipeline.SetRoot(stageA);
                });

            "When the command is processed in the pipeline"
                .When(async () =>
                {
                    try
                    {
                        await pipeline.Execute(command);
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }
                });

            "Then the exception is not captured"
                .Then(() =>
                {
                    exception.Should().NotBeNull();
                });
        }
        public static void TryingToGetAnIncorrectlyTypedConfigurationItem(Exception ex)
        {
            "Given a config file with a string named 'foo'"
                .f(() =>
                {
                    using (var writer = new StreamWriter("foo1.csx"))
                    {
                        writer.WriteLine(@"Configurator.Add(""foo"", ""abc"");");
                        writer.Flush();
                    }
                })
                .Teardown(() => File.Delete("foo1.csx"));

            "When I load the file"
                .When(() => Configurator.Load("foo1.csx"));

            "And I try to get an integer named 'foo'"
                .f(() => ex = Record.Exception(() => Configurator.Get<int>("foo")))
                .Teardown(() => Configurator.Unload());

            "Then an exception is thrown"
                .f(() => ex.Should().NotBeNull());

            "And the exception message contains 'foo'"
                .f(() => ex.Message.Should().Contain("foo"));

            "And the exception contains an inner exception"
                .f(() => ex.InnerException.Should().NotBeNull());

            "And the inner exception message contains 'string'"
                .f(() => ex.InnerException.Message.Should().Contain("string"));

            "And the inner exception message contains 'int'"
                .f(() => ex.InnerException.Message.Should().Contain("int"));
        }
Example #4
0
        public static void DependencyFails(ITaskBuilder builder, bool defaultExecuted, Exception ex)
        {
            "And a non-default task which fails"
                .f(c => builder = ScriptCs.Require<Bau>()
                    .Task("non-default").DependsOn("default")
                        .Do(() =>
                        {
                            throw new Exception();
                        }));

            "And a default task which depends on the non-default task"
                .f(c => builder
                    .Task("default").DependsOn("non-default")
                        .Do(() => defaultExecuted = true));

            "When I run the builder"
                .f(() => ex = Record.Exception(() => builder.Run()));

            "Then execution should fail"
                .f(() => ex.Should().NotBeNull());

            "And the default task is not executed"
                .f(() => defaultExecuted.Should().BeFalse());

            "And I am informed that the non-default task was executed"
                .f(() => ex.Message.Should().Contain("'non-default' task failed."));
        }
        public static void TryingToGetAnIncorrectlyTypedConfigurationItem(Exception ex)
        {
            "Given a config file with a string named 'foo'"
                .f(() =>
                {
                    // TODO (Adam): add DSL - new TempFile(string path, string content).Using();
                    using (var writer = new StreamWriter("foo1.csx"))
                    {
                        writer.WriteLine(@"Add(""foo"", ""abc"");");
                        writer.Flush();
                    }
                })
                .Teardown(() => File.Delete("foo1.csx"));

            "When I load the file"
                .f(() => Config.Global.LoadScriptFile("foo1.csx"));

            "And I try to get an integer named 'foo'"
                .f(() => ex = Record.Exception(() => Config.Global.Get<int>("foo")));

            "Then an exception is thrown"
                .f(() => ex.Should().NotBeNull());

            "And the exception message contains 'foo'"
                .f(() => ex.Message.Should().Contain("foo"));

            "And the exception message contains the full type name of int"
                .f(() => ex.Message.Should().Contain(typeof(int).FullName));

            "And the exception message contains the full type name of string"
                .f(() => ex.Message.Should().Contain(typeof(string).FullName));
        }
        public static void RepeatedAssertion(
            IMyInterface fake,
            Exception exception)
        {
            "establish"
                .x(() =>
                    {
                        fake = A.Fake<IMyInterface>(o => o.Strict());
                        ////fake = A.Fake<IMyInterface>();

                        A.CallTo(() => fake.DoIt(Guid.Empty)).Invokes(() => { });

                        fake.DoIt(Guid.Empty);
                        fake.DoIt(Guid.Empty);
                    });

            "when asserting must have happened when did not happen"
                .x(() => exception = Record.Exception(() => A.CallTo(() => fake.DoIt(Guid.Empty)).MustHaveHappened(Repeated.Exactly.Once)));

            "it should throw an expectation exception"
                .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>());

            "it should have an exception message containing the name of the method"
                .x(() => exception.Message.Should().Contain("DoIt"));
        }
 public void Should_support_chaining_constraints_with_and()
 {
     var someObject = new Exception();
     someObject.Should()
         .BeOfType<Exception>()
         .And
         .NotBeNull();
 }
        public static void ConfiguringSetterWithNull(
            Exception exception)
        {
            "When assignment of a property is configured using a null expression"
                .x(() => exception = Record.Exception(() => A.CallToSet<int>(null)));

            "Then an argument null exception is thrown"
                .x(() => exception.Should().BeAnExceptionOfType<ArgumentNullException>());

            "And the parameter name is 'propertySpecification'"
                .x(() => exception.As<ArgumentNullException>().ParamName.Should().Be("propertySpecification"));
        }
        public static void ConfiguringNonConfigurableSetter(
            ClassWithInterestingProperties subject,
            Exception exception)
        {
            "Given a Fake with a property that can't be configured"
                .x(() => subject = A.Fake<ClassWithInterestingProperties>());

            "When assignment of the property is configured"
                .x(() => exception = Record.Exception(() => A.CallToSet(() => subject.NonConfigurableProperty).DoesNothing()));

            "Then a fake configuration exception is thrown"
                .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>());
        }
Example #10
0
        public static void NoTasksExist(ITaskBuilder builder, Exception ex)
        {
            "Given no tasks"
                .f(() => builder = ScriptCs.Require<Bau>());

            "When I run the builder"
                .f(() => ex = Record.Exception(() => builder.Run()));

            "Then execution should fail"
                .f(() => ex.Should().NotBeNull());

            "And I am informed that the default task was not found"
                .f(() => ex.Message.Should().Contain("'default' task not found"));
        }
        public void OverrideInternalMethod(
            TypeWithInternalMethod fake,
            Exception exception)
        {
            "establish"
                .x(() => fake = A.Fake<TypeWithInternalMethod>());

            "when trying to override internal method on type"
                .x(() => exception = Record.Exception(() => A.CallTo(() => fake.InternalMethod()).Returns(17)));

            "it should throw an exception with a message complaining about accessibility"
                .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
                             .And.Message.Should().Contain("not accessible to DynamicProxyGenAssembly2"));
        }
Example #12
0
        public static void NonexistentTask(string tag, string code, Baufile baufile, Exception ex)
        {
            var scenario = MethodBase.GetCurrentMethod().GetFullName();

            "Given a baufile containing {0}"
                .f(() => baufile = Baufile.Create(string.Concat(scenario, ".", tag)).WriteLine(code));

            "When I execute a non-existent task"
                .f(() => ex = Record.Exception(() => baufile.Run("non-existent")));

            "Then execution should fail"
                .f(() => ex.Should().NotBeNull());

            "And I am informed that the non-existent task was not found"
                .f(() => ex.Message.Should().ContainEquivalentOf("'non-existent' task not found"));
        }
Example #13
0
        public static void CompilationFails(Baufile baufile, Exception ex)
        {
            var scenario = MethodBase.GetCurrentMethod().GetFullName();

            "Given a baufile containing an unknown name"
                .f(() => baufile = Baufile.Create(scenario).WriteLine(@"x"));

            "When I execute the baufile"
                .f(() => ex = Record.Exception(() => baufile.Run()));

            "Then execution should fail"
                .f(() => ex.Should().NotBeNull());

            "And I am informed that member could not be found"
                .f(() => ex.Message.Should().ContainEquivalentOf("the name 'x' does not exist in the current context"));
        }
        public static void CallsToVoidMethodThrows(
            Fake<IFoo> fake,
            Exception exception)
        {
            "Given an unnatural fake"
                .x(() => fake = new Fake<IFoo>());

            "And I configure a void method to throw an exception"
                .x(() => fake.CallsTo(f => f.VoidMethod()).Throws<ArithmeticException>());

            "When I call the method on the faked object"
                .x(() => exception = Record.Exception(() => fake.FakedObject.VoidMethod()));

            "Then it throws the exception"
                .x(() => exception.Should().BeAnExceptionOfType<ArithmeticException>());
        }
        public static void CallsToVoidMethodDoesNothing(
            Fake<AClass> fake,
            Exception exception)
        {
            "Given a strict unnatural fake"
                .x(() => fake = new Fake<AClass>(options => options.Strict()));

            "And I configure a void method to do nothing"
                .x(() => fake.CallsTo(f => f.VoidMethod()).DoesNothing());

            "When I call the method on the faked object"
                .x(() => exception = Record.Exception(() => fake.FakedObject.VoidMethod()));

            "Then it doesn't throw"
                .x(() => exception.Should().BeNull());
        }
Example #16
0
        public static void ExecutionFails(Baufile baufile, Exception ex, string message)
        {
            var scenario = MethodBase.GetCurrentMethod().GetFullName();

            "Given a baufile which throws an exception"
                .f(() => baufile = Baufile.Create(scenario).WriteLine(
                    @"throw new Exception(""" + (message = Guid.NewGuid().ToString()) + @""");"));

            "When I execute the baufile"
                .f(() => ex = Record.Exception(() => baufile.Run()));

            "Then execution should fail"
                .f(() => ex.Should().NotBeNull());

            "And I see details of the exception"
                .f(() => ex.Message.Should().Contain(message));
        }
Example #17
0
        public static void NoTasksExist(ITaskBuilder builder, Exception ex)
        {
            "Given a non-existent task is specified"
                .f(() => builder = ScriptCs.Require<Bau>(new[] { "non-existent" }));

            "And no tasks"
                .f(() => { });

            "When I run the builder"
                .f(() => ex = Record.Exception(() => builder.Run()));

            "Then execution should fail"
                .f(() => ex.Should().NotBeNull());

            "And I am informed that the non-existent task was not found"
                .f(() => ex.Message.Should().Contain("'non-existent' task not found"));
        }
Example #18
0
        public void CanceledToken(
            IFoo fake,
            CancellationToken cancellationToken,
            Exception exception)
        {
            "Given a fake"
                .x(() => fake = A.Fake<IFoo>());

            "And a cancellation token that is canceled"
                .x(() => cancellationToken = new CancellationToken(true));

            "When a method is called with this cancellation token"
                .x(() => exception = Record.Exception(() => fake.Bar(cancellationToken)));

            "Then it throws an OperationCanceledException"
                .x(() => exception.Should().BeAnExceptionAssignableTo<OperationCanceledException>());
        }
        public static void ConfiguringSetterForReadOnlyProperty(
            IHaveInterestingProperties subject,
            Exception exception)
        {
            "Given a Fake with a read-only property"
                .x(() => subject = A.Fake<IHaveInterestingProperties>());

            "When assignment of the property is configured"
                .x(() => exception = Record.Exception(() => A.CallToSet(() => subject.ReadOnlyProperty).DoesNothing()));

            "Then an argument exception is thrown"
                .x(() => exception.Should().BeAnExceptionOfType<ArgumentException>());

            "And the exception message indicates that the property is read-only"
                .x(() => exception.Message.Should().Be(
                    $"The property '{nameof(IHaveInterestingProperties.ReadOnlyProperty)}' does not have a setter."));
        }
Example #20
0
        public void ThrowingConstructor(
            Exception exception)
        {
            "when faking a class whose constructor throws"
                .x(() => exception = Record.Exception(() => A.Fake<ClassWhoseConstructorThrows>()));

            "it should throw a fake creation exception"
                .x(() => exception.Should().BeOfType<FakeCreationException>());

            "it should throw an exception whose message includes original exception type"
                .x(() => exception.Message.Should().Contain("of type System.NotSupportedException"));

            "it should throw an exception whose message includes original exception message"
                .x(() => exception.Message.Should().Contain("I don't like being constructed."));

            "it should throw an exception whose message includes original exception stack trace"
                .x(() => exception.Message.Should().Contain("FakeItEasy.Specs.ClassWhoseConstructorThrows..ctor()"));
        }
Example #21
0
        public static void ConfigValueHasActionProperty(Exception exception)
        {
            "Given a local config file containing a value with an action property"
                .f(() =>
                {
                    using (var writer = new StreamWriter(LocalScriptFileConfig.Path))
                    {
                        writer.WriteLine(@"#r ""ConfigR.Features.dll""");
                        writer.WriteLine(@"using ConfigR.Features;");
                        writer.WriteLine(@"Add(""foo"", new Foo { Action = () => Console.WriteLine(""hello world"") });");
                        writer.Flush();
                    }
                })
                .Teardown(() => File.Delete(LocalScriptFileConfig.Path));

            "When I get the value"
                .f(() => exception = Record.Exception(() => Config.Global.Get<Foo>("foo")));

            "Then no exception is thrown"
                .f(() => exception.Should().BeNull());
        }
        public static void Throws(
            Func<string, int> fakedDelegate,
            FormatException expectedException,
            Exception exception)
        {
            "establish"
                .x(() => fakedDelegate = A.Fake<Func<string, int>>());

            "establish"
                .x(() =>
                    {
                        expectedException = new FormatException();
                        A.CallTo(() => fakedDelegate.Invoke(A<string>._)).Throws(expectedException);
                    });

            "when faking a delegate type and invoking with throwing configuration"
                .x(() => exception = Record.Exception(() => fakedDelegate(null)));

            "it should throw the configured exception"
                .x(() => exception.Should().BeSameAs(expectedException));
        }
Example #23
0
        public void InitializeALoadedStateMachine(
            PassiveStateMachine<int, int> machine,
            Exception receivedException)
        {
            "establish a loaded state machine"._(() =>
                {
                    machine = new PassiveStateMachine<int, int>();

                    machine.Load(A.Fake<IStateMachineLoader<int>>());
                });

            "when initializing the state machine"._(() =>
                    receivedException = Catch.Exception(() =>
                        machine.Initialize(0)));

            "should throw an invalid operation exception"._(() =>
                {
                    receivedException
                        .Should().BeAssignableTo<InvalidOperationException>();
                    receivedException.Message
                        .Should().Be(ExceptionMessages.StateMachineIsAlreadyInitialized);
                });
        }
        public void When_object_type_is_exactly_equal_to_the_specified_type_it_should_not_fail()
        {
            //-------------------------------------------------------------------------------------------------------------------
            // Arrange
            //-------------------------------------------------------------------------------------------------------------------
            var someObject = new Exception();

            //-------------------------------------------------------------------------------------------------------------------
            // Act
            //-------------------------------------------------------------------------------------------------------------------
            Action act = () => someObject.Should().BeOfType<Exception>();

            //-------------------------------------------------------------------------------------------------------------------
            // Assert
            //-------------------------------------------------------------------------------------------------------------------
            act.ShouldNotThrow();
        }
        public void When_object_is_of_the_expected_type_it_should_cast_the_returned_object_for_chaining()
        {
            //-------------------------------------------------------------------------------------------------------------------
            // Arrange
            //-------------------------------------------------------------------------------------------------------------------
            var someObject = new Exception("Actual Message");

            //-------------------------------------------------------------------------------------------------------------------
            // Act
            //-------------------------------------------------------------------------------------------------------------------
            Action act = () => someObject.Should().BeOfType<Exception>().Which.Message.Should().Be("Other Message");

            //-------------------------------------------------------------------------------------------------------------------
            // Assert
            //-------------------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>().WithMessage("*Expected*Other*Actual*");
        }
        public static void WithAdditionalAttributesAndNullSetOfAttributes(
            Exception exception)
        {
            "When a fake is built with a null set of additional attributes"
                .x(() => exception = Record.Exception(() => A.Fake<IInterfaceThatWeWillAddAttributesTo2>(options => options.WithAdditionalAttributes(null))));

            "Then it should throw an argument null exception"
                .x(() => exception.Should().BeAnExceptionOfType<ArgumentNullException>()
                             .WithMessage("*customAttributeBuilders*"));
        }
        public static void MultipleReturns(
            IFoo fake,
            IReturnValueArgumentValidationConfiguration<int> configuration,
            Exception exception)
        {
            "establish"
                .x(() => fake = A.Fake<IFoo>());

            "when configuring multiple returns on the same configuration"
                .x(() =>
                {
                    configuration = A.CallTo(() => fake.Baz());
                    configuration.Returns(42);
                    exception = Record.Exception(() => configuration.Returns(0));
                });

            "it should throw an invalid operation exception"
                .x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
        }
        public static void MultipleReturns(
            IFoo fake,
            IReturnValueArgumentValidationConfiguration<int> configuration,
            Exception exception)
        {
            "Given a fake"
                .x(() => fake = A.Fake<IFoo>());

            "And I configure the return value for the method"
                .x(() =>
                {
                    configuration = A.CallTo(() => fake.Baz());
                    configuration.Returns(42);
                });

            "When I use the same configuration object to set the return value again"
                .x(() => exception = Record.Exception(() => configuration.Returns(0)));

            "Then it throws an invalid operation exception"
                .x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
        }
        public static void UnusedNonVoidCallSpec(
            IFoo fake,
            Exception exception)
        {
            "Given a strict fake"
                .x(() => fake = A.Fake<IFoo>(o => o.Strict()));

            "When I specify a call to a void method without configuring its behavior"
                .x(() => A.CallTo(() => fake.Baz()));

            "And I make a call to that method"
                .x(() => exception = Record.Exception(() => fake.Baz()));

            "Then it throws an expectation exception"
                .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>());
        }
        public static void InvokesAfterStrictVoid(
            IFoo fake,
            Exception exception)
        {
            "Given a strict fake"
                .x(() => fake = A.Fake<IFoo>(options => options.Strict()));

            "And I configure a void method to invoke an action"
                .x(() => A.CallTo(() => fake.Bar()).Invokes(() => { }));

            "When I call the method"
                .x(() => exception = Record.Exception(() => fake.Bar()));

            "Then it does not throw an exception"
                .x(() => exception.Should().BeNull());
        }