Exemple #1
0
 public static ExceptionAssertions <TException> WithMessageFormat <TException>(
     this ExceptionAssertions <TException> assertions,
     string format,
     params object[] formatArgs) where TException : Exception
 {
     return(assertions.WithMessage(string.Format(format, formatArgs)));
 }
 public static ExceptionAssertions <TException> WithInnerException <TException> (
     this ExceptionAssertions <TException> exceptionAssertions,
     Exception innerException)
     where TException : Exception
 {
     exceptionAssertions.And.InnerException.Should().BeSameAs(innerException);
     return(exceptionAssertions);
 }
Exemple #3
0
 public static ExceptionAssertions <TException> WithError <TException>(this ExceptionAssertions <TException> exception,
                                                                       HttpStatusCode errorCode, string errorMessage) where TException : ApiException
 {
     return(exception.Where(x =>
                            x.ErrorCode == (int)errorCode &&
                            x.Message == errorMessage,
                            $"exception should have error code: {errorCode} and message: {errorMessage}"));
 }
Exemple #4
0
 public static ExceptionAssertions <TException> WithMessageSubstring <TException>(
     this ExceptionAssertions <TException> assertions,
     string substring,
     string reason = "",
     params object[] reasonArgs) where TException : Exception
 {
     return(assertions.WithMessage("*" + substring + "*", reason, reasonArgs));
 }
Exemple #5
0
 public static ExceptionAssertions <TExpectedException> WithMessageModuloLineEndings <TExpectedException>(
     this ExceptionAssertions <TExpectedException> assertion,
     string expectedMessage,
     string?because = null,
     params object[] becauseArgs)
     where TExpectedException : Exception
 {
     return(assertion.WithMessage(expectedMessage.NormalizeLineEndings(), because, becauseArgs));
 }
Exemple #6
0
        /// <summary>Asserts that the parameter name matches the expected value.</summary>
        /// <typeparam name="T">The exception type.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="expected">The expected name.</param>
        /// <returns>The assertion.</returns>
        public static ExceptionAssertions <T> WithParameter <T> (this ExceptionAssertions <T> source, string expected) where T : ArgumentException
        {
            var e = source.And as ArgumentException;

            Execute.Assertion.ForCondition(String.Compare(e.ParamName, expected, true) == 0)
            .FailWith("Expected parameter '{0}', but found '{1}'", expected, e.ParamName);

            return(source);
        }
 public static AndConstraint <StringAssertions> WithParameter(
     this ExceptionAssertions <ArgumentNullException> assertions,
     string parameter)
 {
     return(assertions.And
            .ParamName
            .Should( )
            .Be(parameter));
 }
Exemple #8
0
        protected void WhenTheResultIsCalculatedThrowsArgumentOutOfRangeException(string input)
        {
            if (Calculator == null)
            {
                throw new ArgumentNullException(nameof(Calculator));
            }

            _exception = Calculator.Invoking(_ => _.Add(input)).Should().Throw <ArgumentOutOfRangeException>();
        }
Exemple #9
0
        /// <summary>
        /// Asserts that an <see cref="ArgumentException"/> (or inherited exception) is thrown with the expected parameter name.
        /// </summary>
        /// <typeparam name="TException">The <see cref="ArgumentException"/> (or inherited exception).</typeparam>
        /// <param name="assertion"></param>
        /// <param name="expectedParameterName">The expected parameter name.</param>
        public static ExceptionAssertions <TException> WithParamName <TException>(this ExceptionAssertions <TException> assertion, string expectedParameterName, string because = "", params object[] becauseArgs)
            where TException : ArgumentException
        {
            ((IAssertionScope)Execute.Assertion.BecauseOf(because, becauseArgs).UsingLineBreaks)
            .ForCondition(assertion.Which.ParamName == expectedParameterName)
            .BecauseOf(because, becauseArgs)
            .FailWith($"Expected {assertion.Which.GetType().Name} with parameter {{0}}{{reason}}, but found {{1}} instead.", expectedParameterName, assertion.Which.ParamName);

            return(assertion);
        }
Exemple #10
0
        /// <summary>
        /// Asserts that a <see cref="ValidationErrorException"/> has the specified <paramref name="errorCode"/>.
        /// </summary>
        /// <param name="errorCode">The expected error code contained in the exception.</param>
        /// <returns>
        /// The modified assertion for continued chaining.
        /// </returns>
        public static ExceptionAssertions <TException> WithErrorCode <TException>(this ExceptionAssertions <TException> parent, string errorCode)
            where TException : ValidationErrorException
        {
            var exception = parent.Which;

            Execute.Assertion
            .ForCondition(errorCode.Equals(exception.ErrorCode))
            .FailWith("Expected exception with ErrorCode {0}{reason}, but found {1}.", errorCode, exception.ErrorCode);

            return(parent);
        }
Exemple #11
0
        public void SplitAtIndices_WithIndexIsNegative_ThrowsArgumentOutOfRangeException()
        {
            // ARRANGE
            const string input = "FooBarBaz";

            // ACT
            Action action = () => input.SplitAtIndices(new[] { -1 }, StringSplitOptions.None);

            // ASSERT
            ExceptionAssertions <ArgumentOutOfRangeException> expectation = action.ShouldThrow <ArgumentOutOfRangeException>();

            expectation.And.ParamName.Should().Be("indices");
            expectation.And.Message.Should().Contain("length");
        }
Exemple #12
0
        public void SplitAtIndices_WithOutOfOrderIndices_ThrowsArgumentException()
        {
            // ARRANGE
            const string input = "FooBarBaz";

            // ACT
            Action action = () => input.SplitAtIndices(new[] { 1, 0 }, StringSplitOptions.None);

            // ASSERT
            ExceptionAssertions <ArgumentException> expectation = action.ShouldThrow <ArgumentException>();

            expectation.And.ParamName.Should().Be("indices");
            expectation.And.Message.Should().Contain("ascending order");
        }
        /// <summary>
        /// Asserts that the thrown exception has a parameter which name matches <paramref name="paramName" />.
        /// </summary>
        /// <param name="parent">The <see cref="ExceptionAssertions{TException}"/> containing the thrown exception.</param>
        /// <param name="paramName">The expected name of the parameter</param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
        /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
        /// </param>
        /// <param name="becauseArgs">
        /// Zero or more objects to format using the placeholders in <paramref name="because"/>.
        /// </param>
        public static ExceptionAssertions <TException> WithParameterName <TException>(
            this ExceptionAssertions <TException> parent,
            string paramName,
            string because = "",
            params object[] becauseArgs)
            where TException : ArgumentException
        {
            Execute.Assertion
            .ForCondition(parent.Which.ParamName == paramName)
            .BecauseOf(because, becauseArgs)
            .FailWith("Expected exception with parameter name {0}{reason}, but found {1}.", paramName, parent.Which.ParamName);

            return(parent);
        }
        public static ExceptionAssertions <TException> WithValidationMessageForNotEmpty <TException>(
            this ExceptionAssertions <TException> @throw, string because = "",
            params object[] becauseArgs) where TException : Exception
        {
            var exception = @throw.Subject.Single();

            Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .UsingLineBreaks
            .ForCondition(IsValidationExceptionForMessage(exception, " must not be empty."))
            .FailWith(
                $"Expected validation exception message to be\n\"\", but\n\"{exception.Message}\" was not.")
            ;

            return(new ExceptionAssertions <TException>(@throw.Subject));
        }
        public static ExceptionAssertions <TException> WithValidationMessageLike <TException>(
            this ExceptionAssertions <TException> @throw, string messageWithFormatters, string because = "",
            params object[] becauseArgs) where TException : Exception
        {
            var exception      = @throw.Subject.Single();
            var expectedFormat = messageWithFormatters.Replace("{", "{{").Replace("}", "}}");

            Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .UsingLineBreaks
            .ForCondition(IsValidationException(exception) &&
                          ExceptionAssertionExtensions.IsFormattedFrom(exception.Message, messageWithFormatters))
            .FailWith(
                $"Expected validation exception message to match the equivalent of\n\"{expectedFormat}\", but\n\"{exception.Message}\" does not.")
            ;

            return(new ExceptionAssertions <TException>(@throw.Subject));
        }
Exemple #16
0
        /// <summary>
        /// Asserts that a <see cref="ValidationException"/> references all members included in <paramref name="memberNames"/>; no more,no less.
        /// </summary>
        /// <typeparam name="TException">The expected type of the exception.</typeparam>
        /// <param name="parent">The <see cref="ExceptionAssertions{TException}"/> containing the thrown exception.</param>
        /// <param name="memberNames">
        /// The member (property) names to check for. Each member must
        /// be present in the validation exception for the assertion to pass.
        /// </param>
        /// <returns>
        /// The modified <see cref="ExceptionAssertions{TException}"/> for continued chaining.
        /// </returns>
        public static ExceptionAssertions <TException> WithMemberNames <TException>(this ExceptionAssertions <TException> parent, params string[] memberNames)
            where TException : ValidationException
        {
            var exception          = parent.Which;
            var numMatchingMembers = exception
                                     .ValidationResult
                                     .MemberNames
                                     .Where(m => memberNames.Contains(m))
                                     .Count();

            var isMatch = numMatchingMembers == memberNames.Length;
            var exceptionMemberNames = string.Join(", ", exception.ValidationResult.MemberNames);

            Execute.Assertion
            .ForCondition(isMatch)
            .FailWith("Expected exception with member names {0}{reason}, but found {1}.", string.Join(", ", memberNames), exceptionMemberNames);

            return(parent);
        }
        public static ExceptionAssertions <WebServiceException> WithStatusCode(
            this ExceptionAssertions <WebServiceException> @throw, HttpStatusCode statusCode, string because = "",
            params object[] becauseArgs)
        {
            var exception = @throw.Subject.Single();

            Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(exception != null)
            .FailWith("Expected {context} to throw {0}{reason}, but found <null>.", typeof(WebServiceException))
            .Then
            .Given(() => exception.GetStatus().GetValueOrDefault(HttpStatusCode.OK))
            .ForCondition(thrownStatusCode => thrownStatusCode == statusCode)
            .FailWith("Expected {context} to throw {0}{reason} with {1}, but was {2}.",
                      _ => typeof(WebServiceException),
                      _ => statusCode, thrownStatusCode => thrownStatusCode);

            return(new ExceptionAssertions <WebServiceException>(@throw.Subject));
        }
Exemple #18
0
        public void Given_invalid_data_when_reading_should_throw(SoundInfoTestCase testCase)
        {
            // Act
            Func <Task> act = () =>
            {
                using (var ms = new MemoryStream(testCase.Data))
                {
                    return(_sut.LoadAsync(ms));
                }
            };

            // Assert
            ExceptionAssertions <SdlFileException> ex = act.Should().Throw <SdlFileException>();

            ex.WithInnerExceptionExactly <SilentHunterParserException>()
            .WithMessage(testCase.ExpectedError);
            ex.Which.ItemIndex.Should().Be(testCase.ExpectedIndex);
            ex.Which.FileOffset.Should().Be(testCase.ExpectedOffset);
        }
Exemple #19
0
 /// <summary>Asserts that the message contains some text.</summary>
 /// <typeparam name="T">The exception type.</typeparam>
 /// <param name="source">The source.</param>
 /// <param name="expected">The expected message.  Only a portion of the entire message needs to match.</param>
 /// <returns>The assertion.</returns>
 public static ExceptionAssertions <T> ContainingMessage <T> (this ExceptionAssertions <T> source, string expected) where T : Exception
 {
     //Ensure it is wrapped with *
     return(source.WithMessage(EnsureWrappedWithWildcards(expected)));
 }
 internal static ExceptionAssertions <T> WhereMessageContains <T>(this ExceptionAssertions <T> exception, string s, string because) where T : System.Exception
 {
     exception.Where(e => e.Message.Contains(s), because);
     return(exception);
 }
Exemple #21
0
 public static ExceptionAssertions <TEx> WithAnyMessage <TEx>(this ExceptionAssertions <TEx> self)
     where TEx : Exception
 {
     return(self.WithMessage("*"));
 }
Exemple #22
0
 public static List <string> ExtractErrorMessages(this ExceptionAssertions <ValidationException> exceptionAssertions)
 => exceptionAssertions.Subject
 .SelectMany(x => x.Errors)
 .Select(x => x.ErrorMessage)
 .ToList();
Exemple #23
0
 public static ExceptionAssertions <ValidationException> WithType(this ExceptionAssertions <ValidationException> exceptionAssertions, string type)
 {
     exceptionAssertions.And.Type.Should().Be(type);
     return(exceptionAssertions);
 }
Exemple #24
0
 public static void WriteExceptionTo <T>(this ExceptionAssertions <T> exceptionAssertions, ITestOutputHelper output) where T : Exception =>
 output.WriteLine(exceptionAssertions.Which.ToString());
Exemple #25
0
 public static AndConstraint <StringAssertions> ForField <T>(this ExceptionAssertions <T> exception,
                                                             string fieldName) where T : AckeeException
 {
     fieldName = fieldName.ToLower();
     return(exception.And.Message.ToLower().Should().Contain(fieldName));
 }
Exemple #26
0
 public void Then_it_should_throw_NoSuchElementException()
 {
     _exceptionThrown = _selectedButtonInRadioGroupAction.Should().Throw <NoSuchElementException>();
 }
Exemple #27
0
 /// <summary>Asserts that the message contains some text.</summary>
 /// <typeparam name="T">The exception type.</typeparam>
 /// <param name="source">The source.</param>
 /// <param name="expected">The expected message.  Only a portion of the entire message needs to match.</param>
 /// <param name="reason">The reason.</param>
 /// <param name="reasonArgs">The reason arguments.</param>
 /// <returns>The assertion.</returns>
 public static ExceptionAssertions <T> ContainingMessage <T> (this ExceptionAssertions <T> source, string expected,
                                                              string reason, params object[] reasonArgs) where T : Exception
 {
     return(source.WithMessage(EnsureWrappedWithWildcards(expected), reason, reasonArgs));
 }
Exemple #28
0
        /// <summary>
        /// Asserts that a <see cref="ValidationException"/> references all members included in <paramref name="memberNames"/>; no more,no less.
        /// </summary>
        /// <typeparam name="TException">The expected type of the exception.</typeparam>
        /// <param name="parent">The <see cref="ExceptionAssertions{TException}"/> containing the thrown exception.</param>
        /// <param name="memberNames">
        /// The member (property) names to check for. Each member must
        /// be present in the validation exception for the assertion to pass.
        /// </param>
        /// <returns>
        /// The modified <see cref="ExceptionAssertions{TException}"/> for continued chaining.
        /// </returns>
        public static ExceptionAssertions <EntityNotFoundException <TEntity> > WithId <TEntity>(this ExceptionAssertions <EntityNotFoundException <TEntity> > parent, object id)
            where TEntity : class
        {
            var exception = parent.Which;

            Execute.Assertion
            .ForCondition(id.Equals(exception.Id))
            .FailWith("Expected exception with id {0}{reason}, but found {1}.", id, exception.Id);

            return(parent);
        }
 public void Then_an_ArgumentException_should_be_thrown()
 {
     _argumentExceptionAssertion = _failingToMapFormAction.ShouldThrow<ArgumentException>();
 }