public bool IsSatisfiedBy(object argument) { using (var scope = new AssertionScope()) { try { assertion((T)argument); } catch (Exception exception) { var f = scope.Discard(); allFailures = f.Any() ? AggregateFailures(f) : exception.Message; return(false); } var failures = scope.Discard().ToList(); if (failures.Count == 0) { return(true); } allFailures = AggregateFailures(failures); return(false); } }
public bool IsSatisfiedBy(T argument) { using (var scope = new AssertionScope()) { try { assertion(argument); } catch { var f = scope.Discard(); allFailures = string.Join("\n", f); return(false); } var failures = scope.Discard().ToList(); if (failures.Count == 0) { return(true); } allFailures = String.Join("\n", failures); return(false); } }
public bool IsSatisfiedBy(T argument) { using var scope = new AssertionScope(); _assertion(argument); _errors = scope.Discard().ToList(); return(_errors.Count == 0); }
public void Execute(IEnumerable <string> messages, string expectation, string because, params object[] becauseArgs) { using var _ = new AssertionScope(); var results = new AssertionResultSet(); foreach (string message in messages) { using (var scope = new AssertionScope()) { scope.Context = new Lazy <string>(() => Context); message.Should().MatchEquivalentOf(expectation, because, becauseArgs); results.AddSet(message, scope.Discard()); } if (results.ContainsSuccessfulSet()) { break; } } foreach (string failure in results.SelectClosestMatchFor()) { string replacedCurlyBraces = failure.EscapePlaceholders(); AssertionScope.Current.FailWith(replacedCurlyBraces); } }
public static async Task WhenMet(Action condition, IEnumerable <TimeSpan>?checkIntervals, CancellationToken cancellationToken) { foreach (var timeout in checkIntervals ?? DefaultCheckIntervals) { using (var scope = new AssertionScope()) { try { condition(); } catch (Exception error) { error.Should().BeNull("An exception other than assertion was thrown."); } if (!scope.HasFailures()) { return; } if (!cancellationToken.IsCancellationRequested) { scope.Discard(); } } await Task.Delay(timeout, cancellationToken).SuppressCancellation().ConfigureAwait(false); } }
private string[] TryToMatch <T>(object subject, T expectation, int expectationIndex) { using var scope = new AssertionScope(); parent.RecursivelyAssertEquality(new Comparands(subject, expectation, typeof(T)), context.AsCollectionItem <T>(expectationIndex)); return(scope.Discard()); }
/// <summary> /// Asserts that a Bad Request HTTP response content contains an error message identifiable by an wildcard error text. /// </summary> /// <param name="expectedWildcardErrorMessage"> /// The wildcard pattern with which the error field associated error message is matched, where * and ? have special meanings. /// </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 <see paramref="because" />. /// </param> public AndConstraint <BadRequestAssertions> HaveErrorMessage(string expectedWildcardErrorMessage, string because = "", params object[] becauseArgs) { Guard.ThrowIfArgumentIsNullOrEmpty(expectedWildcardErrorMessage, nameof(expectedWildcardErrorMessage), "Cannot verify having an error against a <null> or empty wildcard error message."); Func <Task <JsonDocument> > jsonFunc = () => Subject.GetJsonDocument(); using var json = jsonFunc.ExecuteInDefaultSynchronizationContext().GetAwaiter().GetResult(); var errorsPropertyList = json.GetPropertiesByName(ErrorsPropertyName).ToList(); var hasErrorsProperty = errorsPropertyList.Any(); var errorsProperty = errorsPropertyList.FirstOrDefault(); var allErrors = hasErrorsProperty ? json.GetChildrenNames(ErrorsPropertyName).SelectMany(field => errorsProperty.GetStringValuesOf(field)) : json.GetChildrenNames("").SelectMany(field => json.GetStringValuesOf(field)); var matchFound = allErrors.Any(errorMessage => { using var scope = new AssertionScope(); errorMessage.Should().Match(expectedWildcardErrorMessage); return(!scope.Discard().Any()); }); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(matchFound) .FailWith("Expected {context:response} to contain " + "the error message {0}, " + "but no such message was found in the actual error messages list: " + "{1}", expectedWildcardErrorMessage, Subject); return(new AndConstraint <BadRequestAssertions>(this)); }
public static void Statisfying <T, C>(this IEnumerable <EnumerableElementAssertions <T, C> > assertions, Action <T, C> predicate) { using (var scope = new AssertionScope()) { int index = 0; foreach (var item in assertions) { try { predicate(item.Subject, item.MatchedElement); } catch (Exception ex) { scope.FailWith("Exception thrown: {0}", ex); } var failures = scope.Discard(); if (failures.Length > 0) { scope.FailWith("In the {context} the {0}. item didn't statisfyed all the condition on the matched element.", index); scope.FailWith("Item: {0}", item.Subject); scope.FailWith("MatchedElement: {0}", item.MatchedElement); scope.AddPreFormattedFailure("Failures:"); foreach (var failure in failures) { scope.AddPreFormattedFailure(failure); } break; } index++; } } }
/// <summary> /// Asserts that HTTP response has content that matches a wildcard pattern. /// </summary> /// <param name="expectedWildcardText"> /// The wildcard pattern with which the subject is matched, where * and ? have special meanings. /// </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 <see paramref="because" />. /// </param> public AndConstraint <HttpResponseMessageAssertions> MatchInContent(string expectedWildcardText, string because = "", params object[] becauseArgs) { Guard.ThrowIfArgumentIsNull(expectedWildcardText, nameof(expectedWildcardText), "Cannot verify a HTTP response content match a <null> wildcard pattern."); ExecuteSubjectNotNull(because, becauseArgs); var content = GetContent(); if (string.IsNullOrEmpty(content)) { Execute.Assertion .BecauseOf(because, becauseArgs) .FailWith("Expected {context:response} to match the wildcard pattern {0} in its content, but content was <null>{reason}. {1}", expectedWildcardText, Subject); } string[] failures; using (var scope = new AssertionScope()) { content.Should().Match(expectedWildcardText); failures = scope.Discard(); } Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(failures.Length == 0) .FailWith("Expected {context:response} to match a wildcard pattern in its content, but does not since:{0}{reason}. {1}", new AssertionsFailures(failures), Subject); return(new AndConstraint <HttpResponseMessageAssertions>(this)); }
private static string[] CollectFailuresFromInspectors <T, TAssertions>( this CollectionAssertions <IEnumerable <T>, TAssertions> assertions, Action <T> inspector) where TAssertions : CollectionAssertions <IEnumerable <T>, TAssertions> { using (AssertionScope assertionScope1 = new AssertionScope()) { int num = 0; foreach (var obj in assertions.Subject) { string[] strArray; using (AssertionScope assertionScope2 = new AssertionScope()) { inspector(obj); strArray = assertionScope2.Discard(); } if (strArray.Length != 0) { string str = string.Join(Environment.NewLine, strArray.Select(x => x.IndentLines().TrimEnd('.'))); string valueText = ""; if (obj != null && obj.GetType().GetMethod("ToString")?.DeclaringType != typeof(object)) { valueText = $" with value {obj}"; } assertionScope1.AddPreFormattedFailure($"At index {num}{valueText}:{Environment.NewLine}{str}"); } ++num; } return(assertionScope1.Discard()); } }
private bool ContainsMatch(string content, string wildcardPattern) { using var scope = new AssertionScope(); content.Should().Match(wildcardPattern); return(!scope.Discard().Any()); }
private string[] TryToMatch <T>(object subject, T expectation, int expectationIndex) { using var scope = new AssertionScope(); parent.AssertEqualityUsing(context.CreateForCollectionItem(expectationIndex.ToString(), subject, expectation)); return(scope.Discard()); }
/// <summary> /// Asserts that HTTP response content can be an equivalent representation of the expected model. /// </summary> /// <param name="expectedModel"> /// The expected model. /// </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 <see paramref="because" />. /// </param> public AndConstraint <HttpResponseMessageAssertions> BeAs <TModel>(TModel expectedModel, string because = "", params object[] becauseArgs) { ExecuteSubjectNotNull(because, becauseArgs); if (expectedModel == null) { throw new ArgumentNullException(nameof(expectedModel), "Cannot verify having a content equivalent to a model against a <null> model."); } var expectedModelType = expectedModel.GetType(); var(success, errorMessage) = TryGetSubjectModel(out var subjectModel, expectedModelType); ExecuteModelExtractedAssertion(success, errorMessage, expectedModelType, because, becauseArgs); string[] failures; using (var scope = new AssertionScope()) { subjectModel.Should().BeEquivalentTo(expectedModel); failures = scope.Discard(); } Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(failures.Length == 0) .FailWith("Expected {context:response} to have a content equivalent to a model, but it has differences:{0}{reason}. {1}", new AssertionsFailures(failures), Subject); return(new AndConstraint <HttpResponseMessageAssertions>(this)); }
private string[] CollectFailuresFromInspectors(IEnumerable <Action <T> > elementInspectors) { string[] collectionFailures; using (var collectionScope = new AssertionScope()) { int index = 0; foreach ((T element, Action <T> inspector) in Subject.Zip(elementInspectors, (element, inspector) => (element, inspector))) { string[] inspectorFailures; using (var itemScope = new AssertionScope()) { inspector(element); inspectorFailures = itemScope.Discard(); } if (inspectorFailures.Length > 0) { // Adding one tab and removing trailing dot to allow nested SatisfyRespectively string failures = string.Join(Environment.NewLine, inspectorFailures.Select(x => x.IndentLines().TrimEnd('.'))); // FailWith formatting is not used because of extra quotes being added. Execute.Assertion .FailWith($"At index {index}:{Environment.NewLine}{failures}"); } index++; } collectionFailures = collectionScope.Discard(); } return(collectionFailures); }
/// <summary> /// Asserts that a Bad Request HTTP response content contains an error message identifiable by an wildcard error text. /// </summary> /// <param name="expectedWildcardErrorMessage"> /// The wildcard pattern with which the error field associated error message is matched, where * and ? have special meanings. /// </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 <see paramref="because" />. /// </param> public AndConstraint <BadRequestAssertions> HaveErrorMessage(string expectedWildcardErrorMessage, string because = "", params object[] becauseArgs) { Guard.ThrowIfArgumentIsNullOrEmpty(expectedWildcardErrorMessage, nameof(expectedWildcardErrorMessage), "Cannot verify having an error against a <null> or empty wildcard error message."); Func <Task <JToken> > jsonFunc = () => Subject.GetJsonObject(); var json = jsonFunc.ExecuteInDefaultSynchronizationContext().GetAwaiter().GetResult(); var allErrorsFields = json.GetChildrenKeys("errors"); var allErrors = allErrorsFields.SelectMany(c => json.GetStringValuesByKey(c)); if (!allErrors.Any()) { allErrors = json.GetStringValuesByKey(""); } var matchFound = allErrors.Any(headerValue => { using var scope = new AssertionScope(); headerValue.Should().Match(expectedWildcardErrorMessage); return(!scope.Discard().Any()); }); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(matchFound) .FailWith("Expected {context:response} to contain " + "the error message {0}, " + "but no such message was found in the actual error messages list: " + "{1}", expectedWildcardErrorMessage, Subject); return(new AndConstraint <BadRequestAssertions>(this)); }
public void Execute(IEnumerable <string> messages, string expectation, string reason, params object[] reasonArgs) { using (new AssertionScope()) { var results = new AssertionResultSet(); foreach (string message in messages) { using (var scope = new AssertionScope()) { scope.AddNonReportable("context", Context); message.Should().MatchEquivalentOf(string.Format(Pattern, expectation), reason, reasonArgs); results.AddSet(message, scope.Discard()); } if (results.ContainsSuccessfulSet) { break; } } foreach (string failure in results.SelectClosestMatchFor()) { AssertionScope.Current.FailWith(failure); } } }
public void Execute(IEnumerable <string> messages, string expectation, string because, params object[] becauseArgs) { using (new AssertionScope()) { var results = new AssertionResultSet(); foreach (string message in messages) { using (var scope = new AssertionScope()) { scope.Context = Context; message.Should().MatchEquivalentOf(expectation, because, becauseArgs); results.AddSet(message, scope.Discard()); } if (results.ContainsSuccessfulSet()) { break; } } foreach (string failure in results.SelectClosestMatchFor()) { AssertionScope.Current.FailWith(failure.Replace("{", "{{").Replace("}", "}}")); } } }
protected override Task AssertOnAllResponses(Action <TResponse> assert) { if (!this.ExpectIsValid) { return(base.AssertOnAllResponses(assert)); } return(base.AssertOnAllResponses((r) => { if (TestClient.Configuration.RunIntegrationTests && !r.IsValid && r.ApiCall.OriginalException != null && !(r.ApiCall.OriginalException is ElasticsearchClientException)) { ExceptionDispatchInfo.Capture(r.ApiCall.OriginalException.Demystify()).Throw(); return; } using (var scope = new AssertionScope()) { assert(r); var failures = scope.Discard(); if (failures.Length <= 0) { return; } var failure = failures[0]; scope.AddReportable("Failure", failure); scope.AddReportable("DebugInformation", r.DebugInformation); scope.FailWith($@"{{Failure}} Response Under Test: {{DebugInformation}}"); } })); }
private static string[] CollectFailuresFromInspectors <T, TAssertions>( this CollectionAssertions <IEnumerable <T>, TAssertions> assertions, Action <T> inspector) where TAssertions : CollectionAssertions <IEnumerable <T>, TAssertions> { using (AssertionScope assertionScope1 = new AssertionScope()) { int num = 0; foreach (var obj in assertions.Subject) { string[] strArray; using (AssertionScope assertionScope2 = new AssertionScope()) { inspector(obj); strArray = assertionScope2.Discard(); } if (strArray.Length != 0) { string str = string.Join(Environment.NewLine, strArray.Select(x => x.IndentLines().TrimEnd('.'))); assertionScope1.AddPreFormattedFailure($"At index {num}:{Environment.NewLine}{str}"); } ++num; } return(assertionScope1.Discard()); } }
public void When_a_nested_scope_is_discarded_its_failures_should_also_be_discarded() { // Arrange var scope = new AssertionScope(); AssertionScope.Current.FailWith("Failure1"); using (var nestedScope = new AssertionScope()) { nestedScope.FailWith("Failure2"); using (var deeplyNestedScope = new AssertionScope()) { deeplyNestedScope.FailWith("Failure3"); deeplyNestedScope.Discard(); } } // Act Action act = scope.Dispose; // Assert try { act(); } catch (Exception exception) { exception.Message.Should().Contain("Failure1"); exception.Message.Should().Contain("Failure2"); exception.Message.Should().NotContain("Failure3"); } }
public bool IsSatisfiedBy(IEnumerable <T> argument) { using (var scope = new AssertionScope()) { argument.Should().BeEquivalentTo(_expectation, _configure); _failedExpectations = string.Join(Environment.NewLine, scope.Discard()); return(!_failedExpectations.Any()); } }
private bool ContainsMatch(string wildcardPattern) { using (var scope = new AssertionScope()) { return(Subject.Any(item => { item.Should().Match(wildcardPattern); return !scope.Discard().Any(); })); } }
private IEnumerable <string> AllThatMatch(string wildcardPattern) { return(Subject.Where(item => { using (var scope = new AssertionScope()) { item.Should().Match(wildcardPattern); return !scope.Discard().Any(); } })); }
/// <summary> /// Asserts that a Bad Request HTTP response content contains only a single error message identifiable by an expected field name and a wildcard error text. /// </summary> /// <remarks> /// This assertion considers the HTTP response content a JSON generated by the ASP.NET Core 3.0 framework or less /// </remarks> /// <param name="expectedErrorField"> /// The expected field name. /// </param> /// <param name="expectedWildcardErrorMessage"> /// The wildcard pattern with which the error field associated error message is matched, where * and ? have special meanings. /// </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 <see paramref="because" />. /// </param> public AndConstraint <BadRequestAssertions> OnlyHaveError(string expectedErrorField, string expectedWildcardErrorMessage, string because = "", params object[] becauseArgs) { Guard.ThrowIfArgumentIsNullOrEmpty(expectedErrorField, nameof(expectedErrorField), "Cannot verify having only an error against a <null> or empty field name."); Guard.ThrowIfArgumentIsNullOrEmpty(expectedWildcardErrorMessage, nameof(expectedWildcardErrorMessage), "Cannot verify having only an error against a <null> or empty wildcard error message."); Func <Task <JToken> > jsonFunc = () => Subject.GetJsonObject(); var json = jsonFunc.ExecuteInDefaultSynchronizationContext().GetAwaiter().GetResult(); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(json.HasKey(expectedErrorField)) .FailWith("Expected {context:response} " + "to contain an error message related to the {0} field, but was not found." + "{1}", expectedErrorField, Subject); var parent = json.GetParentKey(expectedErrorField); var children = json.GetChildrenKeys(parent); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(children.Count() == 1) .FailWith("Expected {context:response} " + "to only contain an error message related to the {0} field, but more than this one was found." + "{1}", expectedErrorField, Subject); var values = json.GetStringValuesByKey(expectedErrorField); var expectedWildcardErrorMessageMatchFound = values.Any(headerValue => { using var scope = new AssertionScope(); headerValue.Should().Match(expectedWildcardErrorMessage); return(!scope.Discard().Any()); }); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(expectedWildcardErrorMessageMatchFound) .FailWith("Expected {context:response} to contain " + "the error message {0} related to the {1} field, " + "but no such message was found in the actual error messages list: " + "{2}", expectedWildcardErrorMessage, expectedErrorField, Subject); return(new AndConstraint <BadRequestAssertions>(this)); }
public bool IsSatisfiedBy(T argument) { using var scope = new AssertionScope(); _assertion(argument); var failures = scope.Discard().ToList(); if (failures.Count == 0) { return(true); } failures.ForEach(x => Trace.WriteLine(x)); return(false); }
public static AndConstraint <GenericCollectionAssertions <T> > NotContainEquivalentOf <T>( this GenericCollectionAssertions <T> assert, T expectation, Func <EquivalencyAssertionOptions <T>, EquivalencyAssertionOptions <T> > config, string because = "", params object[] becauseArgs) { if (ReferenceEquals(assert.Subject, null)) { return(new AndConstraint <GenericCollectionAssertions <T> >(assert)); } IEquivalencyAssertionOptions options = config(AssertionOptions.CloneDefaults <T>()); IEnumerable <object> actualItems = assert.Subject.Cast <object>(); using (var scope = new AssertionScope()) { scope.AddReportable("configuration", options.ToString()); foreach (var actualItem in actualItems) { var context = new EquivalencyValidationContext { Subject = actualItem, Expectation = expectation, CompileTimeType = typeof(T), Because = because, BecauseArgs = becauseArgs, Tracer = options.TraceWriter, }; var equivalencyValidator = new EquivalencyValidator(options); equivalencyValidator.AssertEquality(context); var failures = scope.Discard(); if (!failures.Any()) { Execute.Assertion .BecauseOf(because, becauseArgs) .FailWith("Expected {context:collection} {0} to not contain equivalent of {1}.", assert.Subject, expectation); break; } } } return(new AndConstraint <GenericCollectionAssertions <T> >(assert)); }
/// <summary> /// Asserts that a Bad Request HTTP response content contains an error message identifiable by an expected field name and a wildcard error text. /// </summary> /// <remarks> /// This assertion considers the HTTP response content a JSON generated by the ASP.NET Core 3.0 framework or less /// </remarks> /// <param name="expectedErrorField"> /// The expected field name. /// </param> /// <param name="expectedWildcardErrorMessage"> /// The wildcard pattern with which the error field associated error message is matched, where * and ? have special meanings. /// </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 <see paramref="because" />. /// </param> public AndConstraint <BadRequestAssertions> HaveError(string expectedErrorField, string expectedWildcardErrorMessage, string because = "", params object[] becauseArgs) { Guard.ThrowIfArgumentIsNullOrEmpty(expectedErrorField, nameof(expectedErrorField), "Cannot verify having an error against a <null> or empty field name."); Guard.ThrowIfArgumentIsNullOrEmpty(expectedWildcardErrorMessage, nameof(expectedWildcardErrorMessage), "Cannot verify having an error against a <null> or empty wildcard error message."); Func <Task <JsonDocument> > jsonFunc = () => Subject.GetJsonDocument(); using var json = jsonFunc.ExecuteInDefaultSynchronizationContext().GetAwaiter().GetResult(); var errorsProperty = json.GetPropertiesByName(ErrorsPropertyName).ToList(); var hasErrorsProperty = errorsProperty.Any(); var fieldsOfErrorsProperty = json.GetChildrenNames(ErrorsPropertyName); var allFields = json.GetChildrenNames(""); var fields = hasErrorsProperty ? fieldsOfErrorsProperty : allFields; Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(fields.Any(field => string.Equals(field, expectedErrorField, StringComparison.OrdinalIgnoreCase))) .FailWith("Expected {context:response} " + "to contain an error message related to the {0} field, but was not found." + "{1}", expectedErrorField, Subject); var errorsMessages = hasErrorsProperty ? errorsProperty.First().GetStringValuesOf(expectedErrorField) : json.GetStringValuesOf(expectedErrorField); var matchFound = errorsMessages.Any(errorMessage => { using var scope = new AssertionScope(); errorMessage.Should().Match(expectedWildcardErrorMessage); return(!scope.Discard().Any()); }); Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(matchFound) .FailWith("Expected {context:response} to contain " + "the error message {0} related to the {1} field, " + "but no such message was found in the actual error messages list: " + "{2}", expectedWildcardErrorMessage, expectedErrorField, Subject); return(new AndConstraint <BadRequestAssertions>(this)); }
public bool IsSatisfiedBy(T argument) { using (var scope = new AssertionScope()) { _assertion(argument); var failures = scope.Discard(); foreach (var x in failures) { Trace.WriteLine(x); } var hasFailures = failures.Any(); return(hasFailures == false); } }
/// <summary> /// Determines whether the specified action passes assertion evaluation. /// </summary> /// <param name="action"> /// The action. /// </param> /// <returns> /// <c>true</c> if there are no assertion failures; otherwise <c>false</c>. /// </returns> public static bool Is(Action action) { using (var scope = new AssertionScope()) { action(); var failures = scope.Discard().ToList(); if (failures.Count == 0) { return(true); } failures.ForEach(x => Trace.WriteLine(x)); return(false); } }
public void When_the_previous_assertion_failed_it_should_not_execute_the_succeeding_failure() { // Arrange using var scope = new AssertionScope(); // Act Execute.Assertion .ForCondition(false) .FailWith("First assertion") .Then .ForCondition(false) .FailWith("Second assertion"); string[] failures = scope.Discard(); scope.Dispose(); Assert.Single(failures); Assert.Contains("First assertion", failures); }
public void When_a_nested_scope_is_discarded_its_failures_should_also_be_discarded() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var scope = new AssertionScope(); AssertionScope.Current.FailWith("Failure1"); using (var nestedScope = new AssertionScope()) { nestedScope.FailWith("Failure2"); using (var deeplyNestedScope = new AssertionScope()) { deeplyNestedScope.FailWith("Failure3"); deeplyNestedScope.Discard(); } } //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = scope.Dispose; //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- try { act(); } catch (Exception exception) { Assert.IsTrue(exception.Message.Contains("Failure1")); Assert.IsTrue(exception.Message.Contains("Failure2")); Assert.IsFalse(exception.Message.Contains("Failure3")); } }
private string[] TryToMatch(object subject, object expectation, int expectationIndex) { using (var scope = new AssertionScope()) { parent.AssertEqualityUsing(context.CreateForCollectionItem(expectationIndex, subject, expectation)); return scope.Discard(); } }