From 29237d0c45497e41586f9e42226d106cfe239f07 Mon Sep 17 00:00:00 2001 From: Laila Bougria Date: Sat, 17 Aug 2024 00:35:47 +0200 Subject: [PATCH 1/2] Migrate NUnit assertions to the constraint model in preparation of the NUnit 4 upgrade (#7140) * Add Nunit.Analyzer to test projects * Autoformat of test projects for NUnit2001 * Autoformat of test projects for NUnit2002 * Autoformat of test projects for NUnit2003 * Autoformat of test projects for NUnit2004 * Autoformat of test projects for NUnit2005 * Autoformat of test projects for NUnit2006 * Autoformat of test projects for NUnit2007 * Autoformat of test projects for NUnit2010 * Autoformat of test projects for NUnit2011 * Autoformat of test projects for NUnit2012 * Autoformat of test projects for NUnit2013 * Autoformat of test projects for NUnit2014 * Autoformat of test projects for NUnit2015 * Autoformat of test projects for NUnit2016 * Autoformat of test projects for NUnit2017 * Autoformat of test projects for NUnit2018 * Autoformat of test projects for NUnit2019 * Autoformat of test projects for NUnit2028 * Autoformat of test projects for NUnit2030 * Autoformat of test projects for NUnit2031 * Autoformat of test projects for NUnit2035 * Autoformat of test projects for NUnit2036 * Autoformat of test projects for NUnit2037 * Autoformat of test projects for NUnit2038 * Autoformat of test projects for NUnit2039 * Autoformat of test projects for NUnit2043 * Autoformat of test projects for NUnit2045 * Autoformat of test projects for NUnit2046 * Autoformat of test projects for NUnit2048 * Autoformat of test projects for NUnit2049 * handle remaining errors and warnings * Fix Assert --------- Co-authored-by: Daniel Marbach (cherry picked from commit f5662da9ffcb3cd69e1f29a26c84b9308d12a5cb) --- .../ContextAppender.cs | 2 +- .../NServiceBus.AcceptanceTesting.csproj | 1 + .../ScenarioWithContext.cs | 2 +- .../Support/EndpointBehavior.cs | 2 +- .../Audit/When_a_message_is_audited.cs | 2 +- .../Audit/When_a_replymessage_is_audited.cs | 9 +- .../Audit/When_audit_is_overridden_in_code.cs | 2 +- .../Audit/When_auditing.cs | 4 +- ..._auditing_message_with_TimeToBeReceived.cs | 2 +- .../Core/Audit/When_a_message_is_audited.cs | 2 +- ...excluding_event_type_from_autosubscribe.cs | 6 +- .../When_starting_an_endpoint_with_a_saga.cs | 4 +- ...oint_with_a_saga_autosubscribe_disabled.cs | 2 +- ...starting_an_endpoint_with_autosubscribe.cs | 15 +- ...an_endpoint_with_autosubscribe_disabled.cs | 2 +- ...injecting_message_session_into_handlers.cs | 2 +- .../BestPractices/When_publishing_command.cs | 2 +- ...blishing_command_bestpractices_disabled.cs | 2 +- ...mand_bestpractices_disabled_on_endpoint.cs | 2 +- .../Core/BestPractices/When_sending_event.cs | 2 +- ...n_sending_events_bestpractices_disabled.cs | 2 +- .../When_subscribing_to_command.cs | 2 +- .../When_unsubscribing_to_command.cs | 2 +- .../Core/Causation/When_a_message_is_sent.cs | 7 +- ...n_overriding_conversation_id_generation.cs | 7 +- ...new_conversation_inside_message_handler.cs | 14 +- ...ew_conversation_outside_message_handler.cs | 21 ++- ...iving_non_matching_message_with_handler.cs | 2 +- ...ing_unobtrusive_message_without_handler.cs | 9 +- ...ding_interface_message_with_conventions.cs | 2 +- .../When_sending_with_conventions.cs | 7 +- .../When_using_a_greedy_convention.cs | 2 +- .../When_raising_critical_error_at_startup.cs | 7 +- ...n_raising_critical_error_from_a_handler.cs | 2 +- .../When_delayed_delivery_is_not_supported.cs | 7 +- ...erriding_services_in_registercomponents.cs | 11 +- ...ng_async_disposables_externally_managed.cs | 7 +- ...ng_async_disposables_internally_managed.cs | 7 +- .../When_resolving_address_translator.cs | 2 +- ...When_using_externally_managed_container.cs | 7 +- .../Diagnostics/When_a_message_is_audited.cs | 11 +- .../Diagnostics/When_a_message_is_faulted.cs | 11 +- .../Diagnostics/When_endpoint_is_started.cs | 4 +- .../Core/Diagnostics/When_license_expired.cs | 4 +- .../Diagnostics/When_message_is_audited.cs | 11 +- .../Diagnostics/When_message_is_faulted.cs | 22 ++- .../When_overriding_input_queue_name.cs | 7 +- .../When_sending_ensure_proper_headers.cs | 11 +- ...gistering_custom_critical_error_handler.cs | 7 +- .../When_using_concurrency_limit.cs | 2 +- .../Core/Feature/When_depending_on_feature.cs | 7 +- .../When_registering_a_startup_task.cs | 2 +- .../When_custom_host_id_is_configured.cs | 7 +- .../When_disabling_assembly_scanning.cs | 2 +- .../Core/Hosting/When_endpoint_starts.cs | 4 +- .../When_failing_write_startup_diagnostics.cs | 2 +- .../Core/Installers/When_creating_queues.cs | 20 +-- .../Installers/When_installers_enabled.cs | 2 +- .../Installers/When_installers_not_enabled.cs | 2 +- .../Installers/When_installing_endpoint.cs | 13 +- .../When_deserializing_interface_message.cs | 2 +- .../When_using_system_json_serializer.cs | 2 +- ...When_defining_outgoing_message_mutators.cs | 9 +- ...n_incoming_mutator_changes_message_type.cs | 11 +- .../Core/Mutators/When_mutating.cs | 44 ++++-- ...When_outgoing_mutator_replaces_instance.cs | 7 +- .../When_using_outgoing_tm_mutator.cs | 7 +- .../ActivityTestingExtensions.cs | 7 +- .../Metrics/TestingMetricListener.cs | 17 ++- .../When_message_is_processed_successfully.cs | 11 +- .../Traces/TestingActivityListener.cs | 2 +- .../When_ambient_trace_in_message_session.cs | 15 +- .../Traces/When_ambient_trace_in_pipeline.cs | 13 +- .../Traces/When_incoming_event_has_trace.cs | 13 +- ...hen_incoming_message_has_baggage_header.cs | 6 +- .../When_incoming_message_has_no_trace.cs | 2 +- .../Traces/When_incoming_message_has_trace.cs | 30 ++-- ...n_incoming_message_moved_to_error_queue.cs | 7 +- .../When_incoming_message_was_delayed.cs | 79 ++++++---- .../When_outgoing_activity_has_baggage.cs | 2 +- .../Traces/When_processing_fails.cs | 16 +- .../When_processing_incoming_message.cs | 11 +- ...ocessing_message_with_multiple_handlers.cs | 20 ++- ...en_processing_message_with_saga_handler.cs | 2 +- .../Traces/When_publishing_messages.cs | 45 ++++-- .../Traces/When_retrying_messages.cs | 32 ++-- .../Traces/When_sending_messages.cs | 43 ++++-- .../When_sending_messages_from_pipeline.cs | 8 +- .../Traces/When_sending_replies.cs | 11 +- .../OpenTelemetry/Traces/When_subscribing.cs | 14 +- .../Traces/When_unsubscribing.cs | 14 +- .../When_incoming_message_handled.cs | 16 +- ...n_incoming_message_handled_successfully.cs | 6 +- .../When_outbox_enabled_for_send_only.cs | 2 +- ...ith_transaction_mode_above_receive_only.cs | 2 +- ...en_outbox_enabled_with_transactions_off.cs | 7 +- ...enabled_without_persister_supporting_it.cs | 2 +- ...rsistence_provides_synchronized_session.cs | 9 +- .../When_aborting_the_behavior_chain.cs | 7 +- .../When_discontinuing_message_dispatch.cs | 7 +- .../When_extending_behavior_context.cs | 7 +- .../Pipeline/When_extending_sendoptions.cs | 2 +- .../When_extending_the_publish_api.cs | 4 +- ...ng_message_with_several_messagehandlers.cs | 7 +- .../When_overwriting_conversation_id.cs | 4 +- .../When_providing_custom_handler_registry.cs | 11 +- ...ving_with_catch_all_handlers_registered.cs | 9 +- .../When_registering_handlers_explicitly.cs | 2 +- .../Core/Pipeline/When_replacing_behavior.cs | 7 +- .../Core/Pipeline/When_reusing_sendoptions.cs | 4 +- .../Pipeline/When_sending_from_a_send_only.cs | 2 +- .../When_setting_handler_execution_order.cs | 2 +- .../When_setting_ttbr_in_outer_publish.cs | 7 +- ...skipping_serialization_with_nested_send.cs | 9 +- ..._subscribed_to_ReceivePipelineCompleted.cs | 11 +- .../When_transport_transaction_provided.cs | 2 +- .../When_using_custom_conversation_id.cs | 2 +- ...using_per_uow_component_in_the_pipeline.cs | 7 +- ...When_using_polymorphic_message_handlers.cs | 7 +- ...hen_configuring_subscription_authorizer.cs | 4 +- .../When_disabling_publishing.cs | 2 +- .../When_subscribing_on_send_only_endpoint.cs | 4 +- ...hen_unsubscribing_on_send_only_endpoint.cs | 4 +- .../When_applying_message_recoverability.cs | 7 +- ...hen_configuring_unrecoverable_exception.cs | 9 +- .../When_custom_policy_executed.cs | 17 ++- .../When_custom_policy_provided.cs | 9 +- ...delayed_retries_enabled_with_no_support.cs | 2 +- ..._delayed_retries_with_regular_exception.cs | 2 +- .../When_failing_mutated_message.cs | 2 +- ...en_message_is_dispatched_to_error_queue.cs | 2 +- ..._error_queue_with_header_customizations.cs | 9 +- ...ribing_to_delayed_retries_notifications.cs | 13 +- ...When_subscribing_to_error_notifications.cs | 15 +- ...bing_to_immediate_retries_notifications.cs | 13 +- ...actions_off_and_delayed_retries_enabled.cs | 2 +- ...tions_off_and_immediate_retries_enabled.cs | 2 +- .../When_transport_transaction_provided.cs | 2 +- ...pening_storage_session_outside_pipeline.cs | 9 +- .../When_handling_local_event.cs | 2 +- ...acks_are_used_to_reply_with_int_or_enum.cs | 11 +- ...nding_command_routing_with_thisinstance.cs | 7 +- ...nner_send_with_outer_immediate_dispatch.cs | 7 +- ..._nested_send_with_outer_replyTo_routing.cs | 7 +- ...hen_replying_with_pre_created_interface.cs | 7 +- .../Routing/When_routing_interface_message.cs | 2 +- .../When_sending_from_outgoing_pipeline.cs | 14 +- ...age_with_routing_configured_by_assembly.cs | 2 +- ...message_with_routing_configured_by_type.cs | 2 +- .../Core/Sagas/When_a_saga_is_completed.cs | 7 +- .../Sagas/When_adding_state_to_context.cs | 7 +- .../Core/Sagas/When_completing_a_saga.cs | 2 +- .../When_finder_cant_find_saga_instance.cs | 7 +- .../When_finder_returns_existing_saga.cs | 2 +- ...essage_with_handler_and_timeout_handler.cs | 7 +- ...apping_saga_messages_using_base_classes.cs | 2 +- .../Sagas/When_overriding_saga_id_creation.cs | 2 +- .../Core/Sagas/When_starting_a_new_saga.cs | 2 +- .../Sagas/When_using_ReplyToOriginator.cs | 7 +- ...ReplyToOriginator_and_outgoing_behavior.cs | 9 +- ...en_using_ReplyToOriginator_with_headers.cs | 2 +- .../ConventionEnforcementTests.cs | 10 +- .../EndpointNameEnforcementTests.cs | 2 +- .../When_running_saga_tests.cs | 4 +- .../When_using_custom_components.cs | 9 +- ...hen_feature_startup_task_throws_on_stop.cs | 4 +- .../Core/Stopping/When_pump_throws_on_stop.cs | 4 +- ...transport_infrastructure_throws_on_stop.cs | 4 +- ...has_subscription_migration_mode_enabled.cs | 9 +- ..._send_only_endpoint_uses_migration_mode.cs | 4 +- ...has_subscription_migration_mode_enabled.cs | 9 +- ...t_supports_transaction_scope_on_windows.cs | 2 +- .../When_configuring_transport.cs | 2 +- .../When_initializing_transport.cs | 8 +- .../When_querying_for_transaction_mode.cs | 2 +- .../When_transport_is_started.cs | 15 +- .../When_transport_is_started_send_only.cs | 2 +- .../When_transactionscope_enabled.cs | 7 +- ...When_used_with_default_transaction_mode.cs | 2 +- .../When_used_with_transport_scopes.cs | 2 +- ..._using_timeout_greater_than_machine_max.cs | 2 +- ..._received_message_without_correlationid.cs | 2 +- .../When_sending_with_no_correlation_id.cs | 2 +- .../DataBus/When_sender_serializer_differ.cs | 2 +- ..._properties_from_different_environments.cs | 4 +- ...ties_with_systemjson_message_serializer.cs | 2 +- ..._properties_with_xml_message_serializer.cs | 2 +- ...ties_with_systemjson_message_serializer.cs | 2 +- ..._properties_with_xml_message_serializer.cs | 2 +- .../DataBus/When_using_custom_IDataBus.cs | 2 +- .../When_Deferring_a_message.cs | 2 +- .../When_deferring_a_message_to_the_past.cs | 2 +- .../When_deferring_outer_send.cs | 7 +- .../When_deferring_to_non_local.cs | 2 +- .../Feature/When_purging_queues.cs | 2 +- .../Feature/When_subscribing_in_FST.cs | 4 +- ...When_requesting_message_to_be_forwarded.cs | 4 +- .../When_message_has_empty_id_header.cs | 7 +- .../When_message_has_no_id_header.cs | 2 +- .../NServiceBus.AcceptanceTests.csproj | 1 + .../NServiceBusAcceptanceTest.cs | 14 +- .../When_a_duplicate_message_arrives.cs | 7 +- .../Outbox/When_a_message_is_audited.cs | 2 +- .../When_blowing_up_just_after_dispatch.cs | 2 +- ...When_headers_contain_special_characters.cs | 4 +- .../Outbox/When_publishing_with_outbox.cs | 7 +- .../Outbox/When_receiving_a_message.cs | 2 +- .../Pipeline/When_a_message_is_audited.cs | 7 +- .../Pipeline/When_a_message_is_faulted.cs | 7 +- .../Pipeline/When_message_processing_fails.cs | 13 +- .../When_sending_record_class_messages.cs | 4 +- .../When_sending_record_struct_messages.cs | 4 +- .../When_sending_to_another_endpoint.cs | 13 +- .../Cross_q_tx_msg_moved_to_error_q.cs | 7 +- ...PolicyDoes1DelayedRetryThenSendsToError.cs | 4 +- ...hen_custom_policy_always_moves_to_error.cs | 4 +- .../When_custom_policy_discards_message.cs | 7 +- ..._policy_moves_to_overridden_error_queue.cs | 2 +- ...retries_with_immediate_retries_disabled.cs | 2 +- .../When_error_is_overridden_in_code.cs | 2 +- .../When_immediate_retries_are_enabled.cs | 11 +- .../When_immediate_retries_disabled.cs | 2 +- .../When_immediate_retries_fail.cs | 2 +- .../When_message_fails_retries.cs | 13 +- ...s_deferred_by_delayed_retries_using_dtc.cs | 7 +- ...hen_message_with_TimeToBeReceived_fails.cs | 7 +- ...ctional_message_is_moved_to_error_queue.cs | 2 +- ...iveonly_message_is_moved_to_error_queue.cs | 2 +- ...trying_control_message_from_error_queue.cs | 2 +- .../When_retrying_message_from_error_queue.cs | 14 +- ...onscope_message_is_moved_to_error_queue.cs | 7 +- .../Extend_event_routing.cs | 2 +- .../Missing_pub_info.cs | 11 +- .../Multi_sub_to_poly_event.cs | 7 +- .../Pub_from_sendonly.cs | 2 +- .../Pub_to_scaled_out_subs.cs | 7 +- .../Sub_to_base_event.cs | 7 +- .../Sub_to_derived_event.cs | 2 +- .../Sub_to_multiple_pubs.cs | 7 +- .../Sub_to_scaled_out_pubs.cs | 2 +- .../Unsub_from_event.cs | 9 +- .../Unsub_from_scaled_out_pubs.cs | 2 +- .../MultiSubscribeToPolymorphicEvent.cs | 7 +- .../When_publishing_from_sendonly.cs | 2 +- ...en_publishing_to_scaled_out_subscribers.cs | 7 +- .../When_subscribing_to_a_base_event.cs | 7 +- .../When_subscribing_to_a_derived_event.cs | 2 +- .../When_unsubscribing_from_event.cs | 9 +- .../When_base_event_from_2_publishers.cs | 7 +- .../Routing/When_extending_command_routing.cs | 2 +- ...en_making_endpoint_uniquely_addressable.cs | 2 +- .../Routing/When_multiple_mappings_exists.cs | 7 +- .../Routing/When_overriding_local_address.cs | 2 +- .../Routing/When_publishing.cs | 11 +- ...t_implementing_two_unrelated_interfaces.cs | 7 +- .../Routing/When_publishing_an_interface.cs | 7 +- ...ublishing_an_interface_with_unobtrusive.cs | 7 +- .../When_publishing_pre_created_interface.cs | 7 +- .../When_publishing_using_base_type.cs | 2 +- ...ublishing_with_overridden_local_address.cs | 2 +- ...ng_publishers_unobtrusive_messages_code.cs | 7 +- ..._publishers_unobtrusive_messages_config.cs | 7 +- .../Routing/When_replying_to_message.cs | 18 ++- ..._message_with_interface_and_unobtrusive.cs | 7 +- .../When_routing_reply_to_any_instance.cs | 4 +- .../When_routing_reply_to_specific_address.cs | 4 +- ...When_routing_reply_to_specific_instance.cs | 4 +- .../When_using_custom_routing_strategy.cs | 7 +- ..._to_a_message_sent_to_specific_instance.cs | 2 +- .../When_an_endpoint_replies_to_a_saga.cs | 2 +- ...en_correlated_property_value_is_changed.cs | 8 +- .../When_correlating_on_special_characters.cs | 2 +- .../When_correlation_property_is_guid.cs | 7 +- .../Sagas/When_correlation_property_is_int.cs | 7 +- .../When_correlation_property_is_null.cs | 2 +- ...en_doing_request_response_between_sagas.cs | 2 +- .../When_handling_concurrent_messages.cs | 10 +- .../Sagas/When_message_has_a_saga_id.cs | 9 +- .../Sagas/When_receiving_multiple_timeouts.cs | 9 +- .../When_reply_from_saga_not_found_handler.cs | 11 +- .../Sagas/When_replying_to_originator.cs | 2 +- ...n_replying_to_originator_from_a_timeout.cs | 2 +- .../Sagas/When_replying_to_saga_event.cs | 2 +- .../When_saga_exists_for_start_message.cs | 4 +- .../When_saga_handles_unmapped_message.cs | 13 +- .../Sagas/When_saga_id_changed.cs | 9 +- ...en_saga_is_mapped_to_complex_expression.cs | 7 +- .../Sagas/When_saga_started_concurrently.cs | 9 +- .../Sagas/When_sagas_cant_be_found.cs | 13 +- .../When_sagas_share_timeout_messages.cs | 7 +- .../Sagas/When_sending_from_a_saga_handle.cs | 2 +- .../Sagas/When_sending_from_a_saga_timeout.cs | 2 +- ...n_started_by_base_event_from_other_saga.cs | 2 +- ...When_started_by_event_from_another_saga.cs | 2 +- .../Sagas/When_timeout_hit_not_found_saga.cs | 2 +- ...n_two_sagas_subscribe_to_the_same_event.cs | 2 +- ..._updating_existing_correlation_property.cs | 13 +- ...en_using_a_received_message_for_timeout.cs | 7 +- .../Sagas/When_using_contain_saga_data.cs | 2 +- .../Satellites/When_a_message_is_available.cs | 15 +- .../When_configuring_custom_xml_namespace.cs | 2 +- ...efining_serializer_with_no_content_type.cs | 4 +- ...hen_disabling_serializer_type_inference.cs | 22 ++- .../When_dynamic_loading_is_disabled.cs | 6 +- ...When_message_type_header_is_whitespaces.cs | 9 +- ...en_registering_additional_deserializers.cs | 11 +- .../When_registering_custom_serializer.cs | 7 +- ...registering_deserializers_with_settings.cs | 13 +- .../When_serializing_a_message.cs | 26 ++-- .../Serialization/When_skip_wrapping_xml.cs | 9 +- .../When_wrapping_is_not_skipped.cs | 13 +- ...r_processes_message_without_type_header.cs | 2 +- ...l_serializer_used_with_unobtrusive_mode.cs | 2 +- .../When_TimeToBeReceived_has_expired.cs | 2 +- ...TimeToBeReceived_has_expired_convention.cs | 2 +- .../When_TimeToBeReceived_has_not_expired.cs | 7 +- ...ToBeReceived_used_with_unobtrusive_mode.cs | 2 +- .../Tx/ImmediateDispatch/At_least_once.cs | 2 +- .../Tx/ImmediateDispatch/At_most_once.cs | 2 +- .../Tx/ImmediateDispatch/Exactly_once.cs | 2 +- ...hen_receiving_in_transaction_scope_mode.cs | 2 +- ...ing_with_native_multi_queue_transaction.cs | 7 +- ...n_sending_within_an_ambient_transaction.cs | 4 +- ...iple_versions_of_a_message_is_published.cs | 7 +- .../NServiceBus.ContainerTests.csproj | 1 + .../When_building_components.cs | 26 +++- .../When_disposing_the_builder.cs | 7 +- ...When_querying_for_registered_components.cs | 6 +- .../When_registering_components.cs | 25 +-- .../When_using_nested_containers.cs | 22 +-- .../ForwardFromPipelineTests.cs | 12 +- .../Helpers/AnalyzerTestFixture.cs | 3 +- .../Helpers/CodeFixTestFixture.cs | 5 +- ...viceBus.Core.Analyzer.Tests.Roslyn4.csproj | 1 + src/NServiceBus.Core.Tests/API/Types.cs | 2 +- .../AssemblyScanningComponentTests.cs | 2 +- .../When_configuring_assembly_scanning.cs | 2 +- ...ferencing_core_or_interfaces_is_scanned.cs | 4 +- ...ctory_with_no_reference_dlls_is_scanned.cs | 2 +- ...g_assemblies_with_circular_dependencies.cs | 7 +- ...nning_directory_with_nested_directories.cs | 14 +- .../When_using_type_forwarding.cs | 2 +- .../When_validating_assemblies.cs | 21 ++- .../Audit/AuditConfigReaderTests.cs | 16 +- .../AttachCausationHeadersBehaviorTests.cs | 10 +- .../CustomConversationIdStrategyTests.cs | 4 +- .../When_configuring_transport_twice.cs | 7 +- .../Config/When_scanning_assemblies.cs | 12 +- ...endpoint_without_configuring_serializer.cs | 2 +- .../Config/When_using_initialization.cs | 2 +- src/NServiceBus.Core.Tests/ContextBagTests.cs | 11 +- .../ConventionsTests.cs | 34 ++--- .../DataBus/DataBusConfigurationTests.cs | 2 +- .../DataBus/DataBusDeserializerTests.cs | 6 +- .../DataBus/FileShare/AcceptanceTests.cs | 10 +- ...us_message_mutator_to_outgoing_messages.cs | 6 +- .../DateTimeExtensionsTests.cs | 48 +++--- .../DelayedDeliveryOptionExtensionsTests.cs | 8 +- .../TestableMessageHandlerContextTests.cs | 41 +++-- .../Fakes/TestableMessageSessionTests.cs | 18 ++- .../Features/FeatureDefaultsTests.cs | 54 ++++--- .../Features/FeatureDependencyTests.cs | 52 ++++--- .../FeatureDifferingOnlyByNamespaceTests.cs | 7 +- .../Features/FeatureSettingsTests.cs | 20 ++- .../Features/FeatureStartupTests.cs | 37 +++-- .../Features/FeatureTests.cs | 4 +- .../Handlers/MessageHandlerRegistryTests.cs | 20 ++- .../Hosting/HostInfoSettingsTests.cs | 6 +- .../Hosting/HostTests.cs | 2 +- .../Hosting/PathUtilities_Tests.cs | 12 +- .../IdGeneration/IdGenerationTests.cs | 2 +- .../Licensing/LicenseManagerTests.cs | 65 +++++--- .../Logging/DefaultFactoryTests.cs | 2 +- .../Logging/RollingLoggerTests.cs | 144 ++++++++++++------ .../MessageConventionSpecs.cs | 12 +- .../MessageMapper/MessageMapperTests.cs | 28 ++-- ...hen_mapping_ienumerable_implementations.cs | 12 +- .../MessageMapper/When_mapping_interfaces.cs | 23 +-- .../When_mapping_usinggenerics.cs | 20 +-- .../MutateIncomingMessageBehaviorTests.cs | 22 ++- .../MutateOutgoingMessageBehaviorTests.cs | 22 ++- ...teIncomingTransportMessageBehaviorTests.cs | 22 ++- ...teOutgoingTransportMessageBehaviorTests.cs | 22 ++- .../MutatorRegistrationExtensionsTests.cs | 14 +- .../MessageSessionTests.cs | 2 +- .../NServiceBus.Core.Tests.csproj | 1 + .../OpenTelemetry/ActivityDecoratorTests.cs | 9 +- .../OpenTelemetry/ActivityExtensionsTests.cs | 21 ++- .../OpenTelemetry/ActivityFactoryTests.cs | 98 +++++++----- .../OpenTelemetry/ContextPropagationTests.cs | 38 +++-- .../Helpers/TestingMetricListener.cs | 13 +- .../OpenTelemetry/MessageOperationsTests.cs | 107 +++++++------ .../OpenTelemetry/TracingExtensionsTests.cs | 15 +- .../TimeToBeReceivedAttributeTests.cs | 28 +++- .../Persistence/PersistenceStartupTests.cs | 2 +- .../PersistenceStorageMergerTests.cs | 13 +- .../BehaviorRegistrationsCoordinatorTests.cs | 96 +++++++----- .../Pipeline/EnsureNativeBehaviors.cs | 2 +- ...lerTransactionScopeWrapperBehaviorTests.cs | 2 +- .../Pipeline/HeaderOptionExtensionsTests.cs | 6 +- .../Incoming/InvokeHandlerTerminatorTest.cs | 23 +-- .../Incoming/MessageTypeEnricherTest.cs | 16 +- .../SerializeMessageConnectorTests.cs | 2 +- .../IncomingPipelineMetricTagsTests.cs | 8 +- .../Pipeline/MainPipelineExecutorTests.cs | 19 ++- .../AttachSenderRelatedInfoOnMessageTests.cs | 34 +++-- .../ImmediateDispatchOptionExtensionsTests.cs | 4 +- .../Outgoing/MessageIdExtensionsTests.cs | 4 +- .../OutgoingLogicalMessageContextTests.cs | 9 +- .../Outgoing/OutgoingPublishContextTests.cs | 36 +++-- .../Outgoing/OutgoingReplyContextTests.cs | 36 +++-- .../Outgoing/OutgoingSendContextTests.cs | 36 +++-- .../Pipeline/PipelineModelBuilderTests.cs | 18 +-- .../Pipeline/RegisterStepTests.cs | 22 ++- .../DefaultRecoverabilityPolicyTests.cs | 34 +++-- .../DelayedRetryRecoverabilityActionTests.cs | 34 +++-- .../DiscardRecoverabilityActionTests.cs | 4 +- .../Recoverability/ErrorContextTests.cs | 2 +- .../FaultMetadataExtractorTests.cs | 25 +-- .../MoveToErrorsExecutorTests.cs | 16 +- .../RecoverabilityExecutorTests.cs | 4 +- .../RecoverabilitySettingsExtensionsTests.cs | 6 +- .../TransportCapabilityAdjustmentTests.cs | 8 +- ...tReceiveToPhysicalMessageConnectorTests.cs | 52 ++++--- .../ApplyReplyToAddressBehaviorTests.cs | 10 +- .../Routing/AssemblyRouteSourceTests.cs | 2 +- .../BestPracticesOptionExtensionsTests.cs | 4 +- .../DetermineRouteForPublishBehaviorTests.cs | 2 +- .../DetermineRouteForReplyBehaviorTests.cs | 4 +- .../Routing/EndpointInstanceTests.cs | 2 +- .../Routing/EndpointInstancesTests.cs | 15 +- .../MessageDrivenSubscribeTerminatorTests.cs | 36 +++-- .../AssemblyPublisherSourceTests.cs | 7 +- ...rivenSubscriptionsConfigExtensionsTests.cs | 55 ++++--- .../NamespacePublisherSourceTests.cs | 12 +- .../PublishersTests.cs | 22 +-- ...MessageDrivenUnsubscribeTerminatorTests.cs | 16 +- .../Routing/NamespaceRouteSourceTests.cs | 16 +- .../Routing/NativeSubscribeTerminatorTests.cs | 8 +- .../Routers/MulticastPublishConnectorTests.cs | 4 +- .../Routing/Routers/ReplyConnectorTests.cs | 4 +- .../Routing/Routers/SendConnectorTests.cs | 6 +- .../Routers/UnicastPublishConnectorTests.cs | 4 +- .../Routing/Routers/UnicastSendRouterTests.cs | 59 ++++--- .../Routing/RoutingOptionExtensionsTests.cs | 44 +++--- .../Routing/RoutingSettingsTests.cs | 33 ++-- .../RoutingToDispatchConnectorTests.cs | 49 +++--- .../Routing/SubscribeContextTests.cs | 36 +++-- .../Routing/UnicastPublisherRouterTests.cs | 32 ++-- .../Routing/UnicastRoutingTableTests.cs | 4 +- .../Routing/UnsubscribeContextTests.cs | 36 +++-- .../Sagas/InvokeSagaNotFoundBehaviorTests.cs | 2 +- .../Sagas/SagaMetadataCreationTests.cs | 89 ++++++----- .../Sagas/SagaModelTests.cs | 50 +++--- .../Sagas/When_saga_has_no_start_message.cs | 2 +- ...on_a_unsupported_datetime_property_type.cs | 2 +- ...nsupported_datetimeoffset_property_type.cs | 2 +- .../MessageDeserializerResolverTests.cs | 8 +- .../SystemJsonSerializerTests.cs | 92 ++++++----- .../XML/ConcurrencySerializerTests.cs | 7 +- .../Serializers/XML/DictionaryTests.cs | 30 ++-- .../Serializers/XML/Issue_934.cs | 7 +- .../Serializers/XML/ListTests.cs | 30 ++-- .../Serializers/XML/Pull_819.cs | 2 +- .../Serializers/XML/SerializerTests.cs | 125 +++++++++------ .../Serializers/XML/SerializingArrayTests.cs | 44 +++--- .../XML/SerializingEnumerableTests.cs | 4 +- .../XML/SerializingGenericTests.cs | 7 +- .../XML/SerializingNullableTypesTests.cs | 8 +- .../Serializers/XML/UriTests.cs | 2 +- .../Using_Infer_Type_With_Mixed_Namespace.cs | 7 +- .../Using_Infer_Type_With_Non_Nested_Class.cs | 13 +- .../XML/XmlSerializerCacheTests.cs | 20 ++- .../RetryAcknowledgementBehaviorTests.cs | 43 ++++-- .../Settings/SettingsHolderTests.cs | 9 +- src/NServiceBus.Core.Tests/StandardsTests.cs | 24 +-- .../TransactionScopeTests.cs | 6 +- .../Transports/IncomingMessageTests.cs | 23 ++- .../Transports/Learning/AsyncFileTests.cs | 2 +- .../Learning/HeaderSerializerTests.cs | 2 +- .../LearningTransportDispatcherTests.cs | 2 +- .../MulticastTransportOperationTest.cs | 7 +- .../Transports/PushRuntimeSettingsTests.cs | 4 +- .../Transports/QueueAddressTests.cs | 2 +- .../Transports/TransportOperationTest.cs | 9 +- .../Transports/TransportOperationsTests.cs | 33 ++-- .../UnicastTransportOperationTest.cs | 7 +- .../Unicast/Config/ConfigurationSettings.cs | 16 +- .../Unicast/HandlerInvocationCache.cs | 12 +- .../Unicast/LoadHandlersConnectorTests.cs | 4 +- .../Unicast/MessageOperationsTests.cs | 54 ++++--- .../Unicast/MessageTypeTests.cs | 21 ++- .../AssemblyQualifiedNameParserTests.cs | 4 +- .../Messages/DefaultMessageRegistryTests.cs | 32 ++-- .../Unicast/MessagingBestPracticesTests.cs | 6 +- .../Utils/Reflection/ExtensionMethodsTests.cs | 24 +-- .../Utils/Reflection/ReflectTests.cs | 10 +- ...ServiceBus.Learning.AcceptanceTests.csproj | 1 + .../When_disabling_payload_restrictions.cs | 2 +- .../NServiceBus.PersistenceTests.csproj | 1 + .../Outbox/OutboxStorageTests.cs | 15 +- .../When_completing_a_saga_loaded_by_id.cs | 2 +- ...leting_a_saga_with_correlation_property.cs | 2 +- ...en_multiple_sagas_in_outbox_transaction.cs | 44 +++--- ..._saga_with_an_escalated_DTC_transaction.cs | 15 +- ...en_persisting_a_saga_with_complex_types.cs | 4 +- .../When_persisting_a_saga_with_no_mapping.cs | 2 +- ...When_persisting_a_saga_with_record_type.cs | 8 +- ...th_the_same_unique_prop_as_another_saga.cs | 7 +- ...sisting_different_sagas_without_mapping.cs | 7 +- ...with_same_unique_prop_as_completed_saga.cs | 8 +- .../When_retrieving_the_same_saga_twice.cs | 9 +- .../When_rolling_back_storage_session.cs | 8 +- .../Sagas/When_saga_not_found.cs | 4 +- ...hen_updating_saga_in_outbox_transaction.cs | 10 +- .../NServiceBus.TransportTests.csproj | 1 + .../TransportTestLoggerFactory.cs | 2 +- .../TransportTestPolicy.cs | 2 +- .../When_cancelling_stop_on_error.cs | 2 +- .../When_cancelling_stop_on_message.cs | 2 +- .../When_creating_send_only_transport.cs | 4 +- .../When_failure_happens_after_send.cs | 2 +- .../When_message_is_available.cs | 9 +- .../When_modifying_headers_before_on_error.cs | 2 +- .../When_modifying_headers_before_retry.cs | 2 +- .../When_modifying_headers_in_on_error.cs | 2 +- .../When_multiple_messages_are_available.cs | 7 +- ...urrency_is_increased_after_pump_started.cs | 7 +- ...reased_and_decreased_after_pump_started.cs | 7 +- ...ncurrency_is_lowered_after_pump_started.cs | 7 +- .../When_on_error_throws.cs | 11 +- .../When_on_message_throws.cs | 9 +- ...n_on_message_throws_after_delayed_retry.cs | 2 +- ...on_message_throws_after_immediate_retry.cs | 2 +- .../When_receiving_message.cs | 4 +- .../When_scope_complete_throws.cs | 13 +- ...ows_after_successful_message_processing.cs | 7 +- .../When_setting_context_items.cs | 2 +- .../When_stop_canceled_on_error.cs | 2 +- .../When_stop_canceled_on_message.cs | 2 +- .../When_stopping_on_error.cs | 2 +- .../When_stopping_on_message.cs | 2 +- ...When_transaction_level_TransactionScope.cs | 7 +- ...hen_using_unicode_characters_in_headers.cs | 4 +- 544 files changed, 3569 insertions(+), 2230 deletions(-) diff --git a/src/NServiceBus.AcceptanceTesting/ContextAppender.cs b/src/NServiceBus.AcceptanceTesting/ContextAppender.cs index 137aaba85ec..2391f45b8ac 100644 --- a/src/NServiceBus.AcceptanceTesting/ContextAppender.cs +++ b/src/NServiceBus.AcceptanceTesting/ContextAppender.cs @@ -109,7 +109,7 @@ void Log(string message, LogLevel messageSeverity) if (context == null) { // avoid NRE in case something logs outside of a test scenario - TestContext.WriteLine(message); + TestContext.Out.WriteLine(message); return; } diff --git a/src/NServiceBus.AcceptanceTesting/NServiceBus.AcceptanceTesting.csproj b/src/NServiceBus.AcceptanceTesting/NServiceBus.AcceptanceTesting.csproj index 212d3029aa0..821d60a7a7c 100644 --- a/src/NServiceBus.AcceptanceTesting/NServiceBus.AcceptanceTesting.csproj +++ b/src/NServiceBus.AcceptanceTesting/NServiceBus.AcceptanceTesting.csproj @@ -13,6 +13,7 @@ + diff --git a/src/NServiceBus.AcceptanceTesting/ScenarioWithContext.cs b/src/NServiceBus.AcceptanceTesting/ScenarioWithContext.cs index 86dc7f76113..bfd0c5e3102 100644 --- a/src/NServiceBus.AcceptanceTesting/ScenarioWithContext.cs +++ b/src/NServiceBus.AcceptanceTesting/ScenarioWithContext.cs @@ -45,7 +45,7 @@ public async Task Run(RunSettings settings) await runDescriptor.RaiseOnTestCompleted(runSummary).ConfigureAwait(false); - TestContext.WriteLine("Test {0}: Scenario completed in {1:0.0}s", TestContext.CurrentContext.Test.FullName, sw.Elapsed.TotalSeconds); + TestContext.Out.WriteLine("Test {0}: Scenario completed in {1:0.0}s", TestContext.CurrentContext.Test.FullName, sw.Elapsed.TotalSeconds); if (runSummary.Result.Failed) { diff --git a/src/NServiceBus.AcceptanceTesting/Support/EndpointBehavior.cs b/src/NServiceBus.AcceptanceTesting/Support/EndpointBehavior.cs index 8aa2b1e4f14..a49751624be 100644 --- a/src/NServiceBus.AcceptanceTesting/Support/EndpointBehavior.cs +++ b/src/NServiceBus.AcceptanceTesting/Support/EndpointBehavior.cs @@ -46,7 +46,7 @@ public async Task CreateRunner(RunDescriptor run) } catch (Exception) { - TestContext.WriteLine($"Endpoint {runner.Name} failed to initialize"); + await TestContext.Out.WriteLineAsync($"Endpoint {runner.Name} failed to initialize").ConfigureAwait(false); throw; } return runner; diff --git a/src/NServiceBus.AcceptanceTests/Audit/When_a_message_is_audited.cs b/src/NServiceBus.AcceptanceTests/Audit/When_a_message_is_audited.cs index 320829e2d73..4268c3bdae0 100644 --- a/src/NServiceBus.AcceptanceTests/Audit/When_a_message_is_audited.cs +++ b/src/NServiceBus.AcceptanceTests/Audit/When_a_message_is_audited.cs @@ -23,7 +23,7 @@ public async Task Should_preserve_the_original_body() .Done(c => c.Done) .Run(); - Assert.AreEqual(context.OriginalBodyChecksum, context.AuditChecksum, "The body of the message sent to audit should be the same as the original message coming off the queue"); + Assert.That(context.AuditChecksum, Is.EqualTo(context.OriginalBodyChecksum), "The body of the message sent to audit should be the same as the original message coming off the queue"); } public static byte Checksum(byte[] data) diff --git a/src/NServiceBus.AcceptanceTests/Audit/When_a_replymessage_is_audited.cs b/src/NServiceBus.AcceptanceTests/Audit/When_a_replymessage_is_audited.cs index 202599f2110..bcfbfa02e4c 100644 --- a/src/NServiceBus.AcceptanceTests/Audit/When_a_replymessage_is_audited.cs +++ b/src/NServiceBus.AcceptanceTests/Audit/When_a_replymessage_is_audited.cs @@ -21,9 +21,12 @@ public async Task Should_audit_the_message() .Done(c => c.MessageAudited) .Run(); - Assert.True(context.MessageProcessed); - Assert.True(context.MessageAudited); - Assert.AreEqual("SomeValue", context.HeaderValue); + Assert.Multiple(() => + { + Assert.That(context.MessageProcessed, Is.True); + Assert.That(context.MessageAudited, Is.True); + Assert.That(context.HeaderValue, Is.EqualTo("SomeValue")); + }); } public static byte Checksum(byte[] data) diff --git a/src/NServiceBus.AcceptanceTests/Audit/When_audit_is_overridden_in_code.cs b/src/NServiceBus.AcceptanceTests/Audit/When_audit_is_overridden_in_code.cs index cda85bb62d8..690f354e6a5 100644 --- a/src/NServiceBus.AcceptanceTests/Audit/When_audit_is_overridden_in_code.cs +++ b/src/NServiceBus.AcceptanceTests/Audit/When_audit_is_overridden_in_code.cs @@ -16,7 +16,7 @@ public async Task Should_audit_to_target_queue() .Done(c => c.MessageAudited) .Run(); - Assert.True(context.MessageAudited); + Assert.That(context.MessageAudited, Is.True); } public class UserEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Audit/When_auditing.cs b/src/NServiceBus.AcceptanceTests/Audit/When_auditing.cs index b420149d996..0a3caccd675 100644 --- a/src/NServiceBus.AcceptanceTests/Audit/When_auditing.cs +++ b/src/NServiceBus.AcceptanceTests/Audit/When_auditing.cs @@ -18,7 +18,7 @@ public async Task Should_not_be_forwarded_to_auditQueue_when_auditing_is_disable .Done(c => c.IsMessageHandlingComplete) .Run(); - Assert.IsFalse(context.IsMessageHandledByTheAuditEndpoint); + Assert.That(context.IsMessageHandledByTheAuditEndpoint, Is.False); } [Test] @@ -30,7 +30,7 @@ public async Task Should_be_forwarded_to_auditQueue_when_auditing_is_enabled() .Done(c => c.IsMessageHandlingComplete && c.IsMessageHandledByTheAuditEndpoint) .Run(); - Assert.IsTrue(context.IsMessageHandledByTheAuditEndpoint); + Assert.That(context.IsMessageHandledByTheAuditEndpoint, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Audit/When_auditing_message_with_TimeToBeReceived.cs b/src/NServiceBus.AcceptanceTests/Audit/When_auditing_message_with_TimeToBeReceived.cs index 5147862621b..698c12d2153 100644 --- a/src/NServiceBus.AcceptanceTests/Audit/When_auditing_message_with_TimeToBeReceived.cs +++ b/src/NServiceBus.AcceptanceTests/Audit/When_auditing_message_with_TimeToBeReceived.cs @@ -23,7 +23,7 @@ public async Task Should_not_honor_TimeToBeReceived_for_audit_message() .Done(c => c.IsMessageHandlingComplete && c.TTBRHasExpiredAndMessageIsStillInAuditQueue) .Run(); - Assert.IsTrue(context.IsMessageHandlingComplete); + Assert.That(context.IsMessageHandlingComplete, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Audit/When_a_message_is_audited.cs b/src/NServiceBus.AcceptanceTests/Core/Audit/When_a_message_is_audited.cs index 65400d87bb5..c9c393b94f2 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Audit/When_a_message_is_audited.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Audit/When_a_message_is_audited.cs @@ -24,7 +24,7 @@ public async Task Should_allow_audit_action_to_be_replaced() .Done(c => c.AuditMessageReceived) .Run(); - Assert.True(context.BodyWasEmpty); + Assert.That(context.BodyWasEmpty, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_excluding_event_type_from_autosubscribe.cs b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_excluding_event_type_from_autosubscribe.cs index 8d5120c104a..524cee991ec 100644 --- a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_excluding_event_type_from_autosubscribe.cs +++ b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_excluding_event_type_from_autosubscribe.cs @@ -22,10 +22,10 @@ public async Task Should_not_subscribe_excluded_events() .Done(c => c.EndpointsStarted) .Run(); - Assert.AreEqual(1, ctx.EventsSubscribedTo.Count); - Assert.AreEqual(typeof(EventToSubscribeTo), ctx.EventsSubscribedTo[0]); + Assert.That(ctx.EventsSubscribedTo, Has.Count.EqualTo(1)); + Assert.That(ctx.EventsSubscribedTo[0], Is.EqualTo(typeof(EventToSubscribeTo))); - CollectionAssert.IsEmpty(ctx.Logs.Where(l => l.LoggerName == typeof(AutoSubscribe).FullName && l.Level == LogLevel.Error)); + Assert.That(ctx.Logs.Where(l => l.LoggerName == typeof(AutoSubscribe).FullName && l.Level == LogLevel.Error), Is.Empty); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_a_saga.cs b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_a_saga.cs index 67aa9dbfb09..9da97253dde 100644 --- a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_a_saga.cs +++ b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_a_saga.cs @@ -19,8 +19,8 @@ public async Task Should_autoSubscribe_the_saga_messageHandler_by_default() .Done(c => c.EventsSubscribedTo.Count >= 2) .Run(); - Assert.True(context.EventsSubscribedTo.Contains(typeof(MyEvent)), "Events only handled by sagas should be auto subscribed"); - Assert.True(context.EventsSubscribedTo.Contains(typeof(MyEventBase)), "Sagas should be auto subscribed even when handling a base class event"); + Assert.That(context.EventsSubscribedTo, Does.Contain(typeof(MyEvent)), "Events only handled by sagas should be auto subscribed"); + Assert.That(context.EventsSubscribedTo, Does.Contain(typeof(MyEventBase)), "Sagas should be auto subscribed even when handling a base class event"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_a_saga_autosubscribe_disabled.cs b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_a_saga_autosubscribe_disabled.cs index 57b33c16b8f..6049153f245 100644 --- a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_a_saga_autosubscribe_disabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_a_saga_autosubscribe_disabled.cs @@ -19,7 +19,7 @@ public async Task Should_not_autoSubscribe_messages_handled_by_sagas_if_asked_to .Done(c => c.EndpointsStarted) .Run(); - Assert.False(context.EventsSubscribedTo.Count != 0, "Events only handled by sagas should not be auto subscribed"); + Assert.That(context.EventsSubscribedTo.Count, Is.EqualTo(0), "Events only handled by sagas should not be auto subscribed"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_autosubscribe.cs b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_autosubscribe.cs index 31451547916..b9fd8c0c373 100644 --- a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_autosubscribe.cs +++ b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_autosubscribe.cs @@ -20,12 +20,15 @@ public async Task Should_autosubscribe_to_relevant_messagetypes() .Done(c => c.EndpointsStarted && c.EventsSubscribedTo.Count >= 1) .Run(); - Assert.AreEqual(1, context.EventsSubscribedTo.Count); - Assert.True(context.EventsSubscribedTo.Contains(typeof(MyEvent).AssemblyQualifiedName), "Events should be auto subscribed"); - Assert.False(context.EventsSubscribedTo.Contains(typeof(MyEventWithNoRouting).AssemblyQualifiedName), "Events without routing should not be auto subscribed"); - Assert.False(context.EventsSubscribedTo.Contains(typeof(MyEventWithNoHandler).AssemblyQualifiedName), "Events without handlers should not be auto subscribed"); - Assert.False(context.EventsSubscribedTo.Contains(typeof(MyCommand).AssemblyQualifiedName), "Commands should not be auto subscribed"); - Assert.False(context.EventsSubscribedTo.Contains(typeof(MyMessage).AssemblyQualifiedName), "Plain messages should not be auto subscribed by default"); + Assert.That(context.EventsSubscribedTo, Has.Count.EqualTo(1)); + Assert.That(context.EventsSubscribedTo, Does.Contain(typeof(MyEvent).AssemblyQualifiedName), "Events should be auto subscribed"); + Assert.Multiple(() => + { + Assert.That(context.EventsSubscribedTo.Contains(typeof(MyEventWithNoRouting).AssemblyQualifiedName), Is.False, "Events without routing should not be auto subscribed"); + Assert.That(context.EventsSubscribedTo.Contains(typeof(MyEventWithNoHandler).AssemblyQualifiedName), Is.False, "Events without handlers should not be auto subscribed"); + Assert.That(context.EventsSubscribedTo.Contains(typeof(MyCommand).AssemblyQualifiedName), Is.False, "Commands should not be auto subscribed"); + Assert.That(context.EventsSubscribedTo.Contains(typeof(MyMessage).AssemblyQualifiedName), Is.False, "Plain messages should not be auto subscribed by default"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_autosubscribe_disabled.cs b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_autosubscribe_disabled.cs index ee245f673d4..b25d5ab8d8e 100644 --- a/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_autosubscribe_disabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/AutomaticSubscriptions/When_starting_an_endpoint_with_autosubscribe_disabled.cs @@ -20,7 +20,7 @@ public async Task Should_not_autosubscribe_any_events() .Done(ctx => ctx.EndpointsStarted) .Run(); - Assert.IsEmpty(context.SubscribedEvents); + Assert.That(context.SubscribedEvents, Is.Empty); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_injecting_message_session_into_handlers.cs b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_injecting_message_session_into_handlers.cs index 4d935f991b8..553c629b52c 100644 --- a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_injecting_message_session_into_handlers.cs +++ b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_injecting_message_session_into_handlers.cs @@ -16,7 +16,7 @@ public void Should_throw_on_startup() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("IMessageSession", exception.ToString()); + Assert.That(exception.ToString(), Does.Contain("IMessageSession")); } public class StartedEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command.cs b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command.cs index 51c5e51b1d9..3912658394a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command.cs +++ b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command.cs @@ -27,7 +27,7 @@ public async Task Should_throw() .Done(c => c.GotTheException) .Run(); - Assert.IsInstanceOf(context.Exception); + Assert.That(context.Exception, Is.InstanceOf()); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command_bestpractices_disabled.cs b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command_bestpractices_disabled.cs index 25a13d76008..6e5b9f0c31a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command_bestpractices_disabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command_bestpractices_disabled.cs @@ -28,7 +28,7 @@ public async Task Should_allow_publishing_commands() .Done(c => c.EndpointsStarted) .Run(); - Assert.True(context.EndpointsStarted); + Assert.That(context.EndpointsStarted, Is.True); } public class Endpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command_bestpractices_disabled_on_endpoint.cs b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command_bestpractices_disabled_on_endpoint.cs index 12beef59e0f..50566e822f9 100644 --- a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command_bestpractices_disabled_on_endpoint.cs +++ b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_publishing_command_bestpractices_disabled_on_endpoint.cs @@ -22,7 +22,7 @@ public async Task Should_allow_publishing_commands() .Done(c => c.EndpointsStarted) .Run(); - Assert.True(context.EndpointsStarted); + Assert.That(context.EndpointsStarted, Is.True); } diff --git a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_sending_event.cs b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_sending_event.cs index 4047d2d048e..23b6428eaa8 100644 --- a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_sending_event.cs +++ b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_sending_event.cs @@ -27,7 +27,7 @@ public async Task Should_throw() .Done(c => c.GotTheException) .Run(); - Assert.IsInstanceOf(context.Exception); + Assert.That(context.Exception, Is.InstanceOf()); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_sending_events_bestpractices_disabled.cs b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_sending_events_bestpractices_disabled.cs index 95b73058e88..19bf547c1d4 100644 --- a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_sending_events_bestpractices_disabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_sending_events_bestpractices_disabled.cs @@ -22,7 +22,7 @@ public async Task Should_allow_sending_events() .Done(c => c.EndpointsStarted) .Run(); - Assert.True(context.EndpointsStarted); + Assert.That(context.EndpointsStarted, Is.True); } diff --git a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_subscribing_to_command.cs b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_subscribing_to_command.cs index 34858728a09..b7d3efa7057 100644 --- a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_subscribing_to_command.cs +++ b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_subscribing_to_command.cs @@ -27,7 +27,7 @@ public async Task Should_throw() .Done(c => c.GotTheException) .Run(); - Assert.IsInstanceOf(context.Exception); + Assert.That(context.Exception, Is.InstanceOf()); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_unsubscribing_to_command.cs b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_unsubscribing_to_command.cs index f265e217221..c27037db68e 100644 --- a/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_unsubscribing_to_command.cs +++ b/src/NServiceBus.AcceptanceTests/Core/BestPractices/When_unsubscribing_to_command.cs @@ -27,7 +27,7 @@ public async Task Should_throw() .Done(c => c.GotTheException) .Run(); - Assert.IsInstanceOf(context.Exception); + Assert.That(context.Exception, Is.InstanceOf()); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Causation/When_a_message_is_sent.cs b/src/NServiceBus.AcceptanceTests/Core/Causation/When_a_message_is_sent.cs index da4a78ee05b..4328c290cc0 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Causation/When_a_message_is_sent.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Causation/When_a_message_is_sent.cs @@ -15,8 +15,11 @@ public async Task Should_flow_causation_headers() .Done(c => c.Done) .Run(); - Assert.AreEqual(context.FirstConversationId, context.ConversationIdReceived, "Conversation id should flow to outgoing messages"); - Assert.AreEqual(context.MessageIdOfFirstMessage, context.RelatedToReceived, "RelatedToId on outgoing messages should be set to the message id of the message causing it to be sent"); + Assert.Multiple(() => + { + Assert.That(context.ConversationIdReceived, Is.EqualTo(context.FirstConversationId), "Conversation id should flow to outgoing messages"); + Assert.That(context.RelatedToReceived, Is.EqualTo(context.MessageIdOfFirstMessage), "RelatedToId on outgoing messages should be set to the message id of the message causing it to be sent"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Causation/When_overriding_conversation_id_generation.cs b/src/NServiceBus.AcceptanceTests/Core/Causation/When_overriding_conversation_id_generation.cs index 42fa9cc30de..3f8e864bb04 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Causation/When_overriding_conversation_id_generation.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Causation/When_overriding_conversation_id_generation.cs @@ -34,8 +34,11 @@ public async Task Should_use_custom_id() .Done(c => c.MatchingMessageReceived && c.NonMatchingMessageReceived) .Run(); - Assert.AreEqual($"{tennantId}-{myBusinessMessage.MyBusinessId}", context.MatchingConversationIdReceived); - Assert.True(Guid.TryParse(context.NonMatchingConversationIdReceived, out var _)); + Assert.Multiple(() => + { + Assert.That(context.MatchingConversationIdReceived, Is.EqualTo($"{tennantId}-{myBusinessMessage.MyBusinessId}")); + Assert.That(Guid.TryParse(context.NonMatchingConversationIdReceived, out var _), Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Causation/When_starting_new_conversation_inside_message_handler.cs b/src/NServiceBus.AcceptanceTests/Core/Causation/When_starting_new_conversation_inside_message_handler.cs index e8eb34cc69e..7eb9a9759cb 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Causation/When_starting_new_conversation_inside_message_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Causation/When_starting_new_conversation_inside_message_handler.cs @@ -23,8 +23,11 @@ public async Task With_specified_conversation_id() .Done(ctx => ctx.MessageHandled) .Run(); - Assert.That(context.NewConversationId, Is.EqualTo(UserDefinedConverstionId), "ConversationId should be set to the user defined value."); - Assert.That(context.PreviousConversationId, Is.EqualTo(context.OriginalConversationId), "PreviousConversationId header should be set to the original conversation id."); + Assert.Multiple(() => + { + Assert.That(context.NewConversationId, Is.EqualTo(UserDefinedConverstionId), "ConversationId should be set to the user defined value."); + Assert.That(context.PreviousConversationId, Is.EqualTo(context.OriginalConversationId), "PreviousConversationId header should be set to the original conversation id."); + }); } [Test] @@ -40,8 +43,11 @@ public async Task Without_specified_conversation_id() .Run(); Assert.That(context.NewConversationId, Is.EqualTo(GeneratedConversationId), "ConversationId should be generated."); - Assert.That(context.NewConversationId, Is.Not.EqualTo(context.OriginalConversationId), "ConversationId should not be equal to the original conversation id."); - Assert.That(context.PreviousConversationId, Is.EqualTo(context.OriginalConversationId), "PreviousConversationId header should be set to the original conversation id."); + Assert.Multiple(() => + { + Assert.That(context.NewConversationId, Is.Not.EqualTo(context.OriginalConversationId), "ConversationId should not be equal to the original conversation id."); + Assert.That(context.PreviousConversationId, Is.EqualTo(context.OriginalConversationId), "PreviousConversationId header should be set to the original conversation id."); + }); } class NewConversationScenario : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Causation/When_starting_new_conversation_outside_message_handler.cs b/src/NServiceBus.AcceptanceTests/Core/Causation/When_starting_new_conversation_outside_message_handler.cs index a69fe3985ea..de5585783a6 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Causation/When_starting_new_conversation_outside_message_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Causation/When_starting_new_conversation_outside_message_handler.cs @@ -26,8 +26,11 @@ public async Task With_specified_conversation_id() .Done(ctx => ctx.MessageHandled) .Run(); - Assert.That(context.ConversationId, Is.EqualTo(NewConversionId), "ConversationId should be set to configured user defined value."); - Assert.That(context.PreviousConversationId, Is.Null, "Previous ConversationId should not be set when handling a message outside of a message handler."); + Assert.Multiple(() => + { + Assert.That(context.ConversationId, Is.EqualTo(NewConversionId), "ConversationId should be set to configured user defined value."); + Assert.That(context.PreviousConversationId, Is.Null, "Previous ConversationId should not be set when handling a message outside of a message handler."); + }); } [Test] @@ -46,8 +49,11 @@ public async Task Without_specified_conversation_id() .Run(); Assert.That(context.ConversationId, Is.EqualTo(GeneratedConversationId), "ConversationId should be generated."); - Assert.That(context.ConversationId, Is.Not.EqualTo(context.PreviousConversationId), "ConversationId should not match the previous conversationId."); - Assert.That(context.PreviousConversationId, Is.Null, "Previous ConversationId should not be set when handling a message outside of a message handler."); + Assert.Multiple(() => + { + Assert.That(context.ConversationId, Is.Not.EqualTo(context.PreviousConversationId), "ConversationId should not match the previous conversationId."); + Assert.That(context.PreviousConversationId, Is.Null, "Previous ConversationId should not be set when handling a message outside of a message handler."); + }); } [Test] @@ -77,8 +83,11 @@ public async Task Cannot_set_value_for_header_directly() .Run(); var expectedExceptionMessage = $"Cannot set the NServiceBus.ConversationId header to '{overrideConversationId}' as StartNewConversation() was called."; - Assert.That(context.ExceptionThrown, Is.True, "Exception should be thrown when trying to directly set conversationId"); - Assert.That(context.ExceptionMessage, Is.EqualTo(expectedExceptionMessage)); + Assert.Multiple(() => + { + Assert.That(context.ExceptionThrown, Is.True, "Exception should be thrown when trying to directly set conversationId"); + Assert.That(context.ExceptionMessage, Is.EqualTo(expectedExceptionMessage)); + }); } public class AnyMessage : IMessage diff --git a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_receiving_non_matching_message_with_handler.cs b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_receiving_non_matching_message_with_handler.cs index 223dba5cfab..6f3f19887fc 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_receiving_non_matching_message_with_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_receiving_non_matching_message_with_handler.cs @@ -17,7 +17,7 @@ public async Task Should_process_message() .Done(c => c.GotTheMessage) .Run(); - Assert.True(context.GotTheMessage); + Assert.That(context.GotTheMessage, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_receiving_unobtrusive_message_without_handler.cs b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_receiving_unobtrusive_message_without_handler.cs index e24a12ecc14..b6f83b7163f 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_receiving_unobtrusive_message_without_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_receiving_unobtrusive_message_without_handler.cs @@ -19,9 +19,12 @@ public async Task Message_should_be_moved_to_error_because_handler_not_found() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.True(context.Logs.Any(l => l.Level == LogLevel.Error && l.Message.Contains($"No handlers could be found for message type: {typeof(MyCommand).FullName}")), "No handlers could be found was not logged."); - Assert.False(context.Logs.Any(l => l.Level == LogLevel.Warn && l.Message.Contains($"Message header '{typeof(MyCommand).FullName}' was mapped to type '{typeof(MyCommand).FullName}' but that type was not found in the message registry, ensure the same message registration conventions are used in all endpoints, especially if using unobtrusive mode.")), "Message type could not be mapped."); - Assert.False(context.Logs.Any(l => l.Level == LogLevel.Warn && l.Message.Contains($"Could not determine message type from message header '{typeof(MyCommand).FullName}'")), "Message type could not be mapped."); + Assert.Multiple(() => + { + Assert.That(context.Logs.Any(l => l.Level == LogLevel.Error && l.Message.Contains($"No handlers could be found for message type: {typeof(MyCommand).FullName}")), Is.True, "No handlers could be found was not logged."); + Assert.That(context.Logs.Any(l => l.Level == LogLevel.Warn && l.Message.Contains($"Message header '{typeof(MyCommand).FullName}' was mapped to type '{typeof(MyCommand).FullName}' but that type was not found in the message registry, ensure the same message registration conventions are used in all endpoints, especially if using unobtrusive mode.")), Is.False, "Message type could not be mapped."); + Assert.That(context.Logs.Any(l => l.Level == LogLevel.Warn && l.Message.Contains($"Could not determine message type from message header '{typeof(MyCommand).FullName}'")), Is.False, "Message type could not be mapped."); + }); } public class Context : ScenarioContext { } diff --git a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_sending_interface_message_with_conventions.cs b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_sending_interface_message_with_conventions.cs index 67708b8a656..5f1ab6540d4 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_sending_interface_message_with_conventions.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_sending_interface_message_with_conventions.cs @@ -21,7 +21,7 @@ public async Task Should_receive_the_message() .Done(c => c.MessageInterfaceReceived) .Run(); - Assert.True(context.MessageInterfaceReceived); + Assert.That(context.MessageInterfaceReceived, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_sending_with_conventions.cs b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_sending_with_conventions.cs index c9537140158..a8fea618996 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_sending_with_conventions.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_sending_with_conventions.cs @@ -20,8 +20,11 @@ public async Task Should_receive_the_message() .Done(c => c.MessageClassReceived && c.MessageInterfaceReceived) .Run(); - Assert.True(context.MessageClassReceived); - Assert.True(context.MessageInterfaceReceived); + Assert.Multiple(() => + { + Assert.That(context.MessageClassReceived, Is.True); + Assert.That(context.MessageInterfaceReceived, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_using_a_greedy_convention.cs b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_using_a_greedy_convention.cs index 304bf36a220..7fbba4a0bb9 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Conventions/When_using_a_greedy_convention.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Conventions/When_using_a_greedy_convention.cs @@ -20,7 +20,7 @@ public async Task Should_receive_the_message() .Done(c => c.WasCalled) .Run(); - Assert.True(context.WasCalled, "The message handler should be called"); + Assert.That(context.WasCalled, Is.True, "The message handler should be called"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/CriticalError/When_raising_critical_error_at_startup.cs b/src/NServiceBus.AcceptanceTests/Core/CriticalError/When_raising_critical_error_at_startup.cs index 76e17ab6ec9..94da2e1694e 100644 --- a/src/NServiceBus.AcceptanceTests/Core/CriticalError/When_raising_critical_error_at_startup.cs +++ b/src/NServiceBus.AcceptanceTests/Core/CriticalError/When_raising_critical_error_at_startup.cs @@ -29,8 +29,11 @@ public async Task Should_call_critical_error_action_for_every_error_that_occurre .Done(c => c.CriticalErrorsRaised >= 2 && exceptions.Count >= 2) .Run(); - Assert.AreEqual(2, context.CriticalErrorsRaised); - Assert.AreEqual(context.CriticalErrorsRaised, exceptions.Count); + Assert.Multiple(() => + { + Assert.That(context.CriticalErrorsRaised, Is.EqualTo(2)); + Assert.That(exceptions, Has.Count.EqualTo(context.CriticalErrorsRaised)); + }); } public class TestContext : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/CriticalError/When_raising_critical_error_from_a_handler.cs b/src/NServiceBus.AcceptanceTests/Core/CriticalError/When_raising_critical_error_from_a_handler.cs index db2838e1ed3..b0ed14047ae 100644 --- a/src/NServiceBus.AcceptanceTests/Core/CriticalError/When_raising_critical_error_from_a_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Core/CriticalError/When_raising_critical_error_from_a_handler.cs @@ -41,7 +41,7 @@ await Scenario.Define() .Done(c => c.CriticalErrorsRaised > 0 && exceptions.Keys.Count > 0) .Run(); - Assert.AreEqual(1, exceptions.Keys.Count); + Assert.That(exceptions.Keys, Has.Count.EqualTo(1)); } public class TestContext : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/DelayedDelivery/When_delayed_delivery_is_not_supported.cs b/src/NServiceBus.AcceptanceTests/Core/DelayedDelivery/When_delayed_delivery_is_not_supported.cs index 7fb3640b557..532aea47f0a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/DelayedDelivery/When_delayed_delivery_is_not_supported.cs +++ b/src/NServiceBus.AcceptanceTests/Core/DelayedDelivery/When_delayed_delivery_is_not_supported.cs @@ -28,8 +28,11 @@ public async Task Trying_to_delay_should_throw() .Done(c => c.ExceptionThrown || c.SecondMessageReceived) .Run(); - Assert.AreEqual(true, context.ExceptionThrown); - Assert.AreEqual(false, context.SecondMessageReceived); + Assert.Multiple(() => + { + Assert.That(context.ExceptionThrown, Is.EqualTo(true)); + Assert.That(context.SecondMessageReceived, Is.EqualTo(false)); + }); } diff --git a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_overriding_services_in_registercomponents.cs b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_overriding_services_in_registercomponents.cs index 3dc84f089dd..40da2b842fa 100644 --- a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_overriding_services_in_registercomponents.cs +++ b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_overriding_services_in_registercomponents.cs @@ -31,11 +31,14 @@ public async Task RegisterComponents_calls_override_registrations() .Done(c => c.EndpointsStarted) .Run(); - Assert.IsInstanceOf(context.DependencyFromFeature); - Assert.IsInstanceOf(context.DependencyBeforeEndpointConfiguration); + Assert.Multiple(() => + { + Assert.That(context.DependencyFromFeature, Is.InstanceOf()); + Assert.That(context.DependencyBeforeEndpointConfiguration, Is.InstanceOf()); - // Registrations after the startable endpoint has been created can't be overriden by the RegisterComponents API - Assert.IsInstanceOf(context.DependencyBeforeEndpointStart); + // Registrations after the startable endpoint has been created can't be overriden by the RegisterComponents API + Assert.That(context.DependencyBeforeEndpointStart, Is.InstanceOf()); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_registering_async_disposables_externally_managed.cs b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_registering_async_disposables_externally_managed.cs index 2eb4268d736..0a922f7955c 100644 --- a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_registering_async_disposables_externally_managed.cs +++ b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_registering_async_disposables_externally_managed.cs @@ -35,8 +35,11 @@ public async Task Should_dispose() await serviceProvider.DisposeAsync(); - Assert.That(context.ScopedAsyncDisposableDisposed, Is.True, "Scoped AsyncDisposable wasn't disposed as it should have been."); - Assert.That(context.SingletonAsyncDisposableDisposed, Is.True, "Singleton AsyncDisposable wasn't disposed as it should have been."); + Assert.Multiple(() => + { + Assert.That(context.ScopedAsyncDisposableDisposed, Is.True, "Scoped AsyncDisposable wasn't disposed as it should have been."); + Assert.That(context.SingletonAsyncDisposableDisposed, Is.True, "Singleton AsyncDisposable wasn't disposed as it should have been."); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_registering_async_disposables_internally_managed.cs b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_registering_async_disposables_internally_managed.cs index 4f35619282e..826621a3612 100644 --- a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_registering_async_disposables_internally_managed.cs +++ b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_registering_async_disposables_internally_managed.cs @@ -21,8 +21,11 @@ public async Task Should_dispose() .Done(c => c.ScopedAsyncDisposableDisposed) .Run(TimeSpan.FromSeconds(10)); - Assert.That(context.ScopedAsyncDisposableDisposed, Is.True, "Scoped AsyncDisposable wasn't disposed as it should have been."); - Assert.That(context.SingletonAsyncDisposableDisposed, Is.True, "Singleton AsyncDisposable wasn't disposed as it should have been."); + Assert.Multiple(() => + { + Assert.That(context.ScopedAsyncDisposableDisposed, Is.True, "Scoped AsyncDisposable wasn't disposed as it should have been."); + Assert.That(context.SingletonAsyncDisposableDisposed, Is.True, "Singleton AsyncDisposable wasn't disposed as it should have been."); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_resolving_address_translator.cs b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_resolving_address_translator.cs index ba70520d610..9c99ac67dd7 100644 --- a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_resolving_address_translator.cs +++ b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_resolving_address_translator.cs @@ -64,7 +64,7 @@ await Scenario.Define() .Done(ctx => thrownException != null) .Run(); - StringAssert.Contains("Transport address resolution is not supported before the NServiceBus transport has been started.", thrownException.Message); + Assert.That(thrownException.Message, Does.Contain("Transport address resolution is not supported before the NServiceBus transport has been started.")); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_using_externally_managed_container.cs b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_using_externally_managed_container.cs index 14860387f47..12fb678c6e0 100644 --- a/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_using_externally_managed_container.cs +++ b/src/NServiceBus.AcceptanceTests/Core/DependencyInjection/When_using_externally_managed_container.cs @@ -29,8 +29,11 @@ public async Task Should_use_it_for_component_resolution() .Done(c => c.MessageReceived) .Run(); - Assert.NotNull(result.ServiceProvider, "IServiceProvider should be injectable"); - Assert.AreSame(myComponent, result.CustomService, "Should inject custom services"); + Assert.Multiple(() => + { + Assert.That(result.ServiceProvider, Is.Not.Null, "IServiceProvider should be injectable"); + Assert.That(result.CustomService, Is.SameAs(myComponent), "Should inject custom services"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_a_message_is_audited.cs b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_a_message_is_audited.cs index f72e883d5c3..f8cf80596cd 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_a_message_is_audited.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_a_message_is_audited.cs @@ -17,10 +17,13 @@ public async Task Should_add_host_related_headers() .Done(c => c.Done) .Run(); - Assert.IsNotNull(context.HostId); - Assert.IsNotNull(context.HostName); - Assert.IsNotNull(context.Endpoint); - Assert.IsNotNull(context.Machine); + Assert.Multiple(() => + { + Assert.That(context.HostId, Is.Not.Null); + Assert.That(context.HostName, Is.Not.Null); + Assert.That(context.Endpoint, Is.Not.Null); + Assert.That(context.Machine, Is.Not.Null); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_a_message_is_faulted.cs b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_a_message_is_faulted.cs index bcced65568a..c2b375fe4c3 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_a_message_is_faulted.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_a_message_is_faulted.cs @@ -17,10 +17,13 @@ public async Task Should_add_host_related_headers() .Done(c => c.Done) .Run(); - Assert.IsNotNull(context.HostId, "Host Id should be included in fault message headers"); - Assert.IsNotNull(context.HostName, "Host Name should be included in fault message headers"); - Assert.IsNotNull(context.Endpoint, "Endpoint name should be included in fault message headers."); - Assert.IsNotNull(context.Machine, "Machine should be included in fault message headers."); + Assert.Multiple(() => + { + Assert.That(context.HostId, Is.Not.Null, "Host Id should be included in fault message headers"); + Assert.That(context.HostName, Is.Not.Null, "Host Name should be included in fault message headers"); + Assert.That(context.Endpoint, Is.Not.Null, "Endpoint name should be included in fault message headers."); + Assert.That(context.Machine, Is.Not.Null, "Machine should be included in fault message headers."); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_endpoint_is_started.cs b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_endpoint_is_started.cs index f580e9e9a47..b6b15d29277 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_endpoint_is_started.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_endpoint_is_started.cs @@ -31,10 +31,10 @@ await Scenario.Define() var startupDiagnosticsFileName = $"{endpointName}-configuration.txt"; var pathToFile = Path.Combine(basePath, startupDiagnosticsFileName); - Assert.True(File.Exists(pathToFile)); + Assert.That(File.Exists(pathToFile), Is.True); var diagnosticContent = File.ReadAllText(pathToFile); - Assert.True(diagnosticContent.Contains("\"Licensing\"")); + Assert.That(diagnosticContent, Does.Contain("\"Licensing\"")); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_license_expired.cs b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_license_expired.cs index 590e168fbe1..98bb27763b5 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_license_expired.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_license_expired.cs @@ -20,11 +20,11 @@ public async Task Should_add_the_license_diagnostic_headers_to_audited_messages( .Done(c => c.Done) .Run(); - Assert.IsTrue(context.HasDiagnosticLicensingHeaders); + Assert.That(context.HasDiagnosticLicensingHeaders, Is.True); if (Debugger.IsAttached) { - Assert.True(context.Logs.Any(m => m.Level == LogLevel.Error && m.Message.StartsWith("Your license has expired")), "Error should be logged"); + Assert.That(context.Logs.Any(m => m.Level == LogLevel.Error && m.Message.StartsWith("Your license has expired")), Is.True, "Error should be logged"); } } diff --git a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_message_is_audited.cs b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_message_is_audited.cs index f586d7697d1..1c7cefba5c1 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_message_is_audited.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_message_is_audited.cs @@ -26,12 +26,15 @@ public async Task Should_contain_processing_stats_headers() var processingEnded = DateTimeOffsetHelper.ToDateTimeOffset(context.Headers[Headers.ProcessingEnded]); var timeSent = DateTimeOffsetHelper.ToDateTimeOffset(context.Headers[Headers.TimeSent]); - Assert.That(processingStarted, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(processingStarted)); - Assert.That(processingEnded, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(processingEnded)); - Assert.That(timeSent, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(timeSent)); + Assert.Multiple(() => + { + Assert.That(processingStarted, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(processingStarted)); + Assert.That(processingEnded, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(processingEnded)); + Assert.That(timeSent, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(timeSent)); + }); Assert.That(processingStarted, Is.LessThanOrEqualTo(processingEnded), nameof(processingStarted)); Assert.That(timeSent, Is.LessThanOrEqualTo(processingEnded), nameof(timeSent)); - Assert.IsTrue(context.IsMessageHandledByTheAuditEndpoint, nameof(context.IsMessageHandledByTheAuditEndpoint)); + Assert.That(context.IsMessageHandledByTheAuditEndpoint, Is.True, nameof(context.IsMessageHandledByTheAuditEndpoint)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_message_is_faulted.cs b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_message_is_faulted.cs index d1a59919098..6149dfa60fc 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_message_is_faulted.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_message_is_faulted.cs @@ -28,16 +28,22 @@ public async Task Should_contain_processing_stats_headers() var timeSent = DateTimeOffsetHelper.ToDateTimeOffset(context.Headers[Headers.TimeSent]); var timeSentWhenFailedMessageWasSentToTheErrorQueue = DateTimeOffsetHelper.ToDateTimeOffset(context.FaultHeaders[Headers.TimeSent]); - Assert.That(processingStarted, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(processingStarted)); - Assert.That(processingEnded, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(processingEnded)); - Assert.That(timeSent, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(timeSent)); - Assert.That(timeSentWhenFailedMessageWasSentToTheErrorQueue, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(timeSentWhenFailedMessageWasSentToTheErrorQueue)); + Assert.Multiple(() => + { + Assert.That(processingStarted, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(processingStarted)); + Assert.That(processingEnded, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(processingEnded)); + Assert.That(timeSent, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(timeSent)); + Assert.That(timeSentWhenFailedMessageWasSentToTheErrorQueue, Is.EqualTo(now).Within(TimeSpan.FromSeconds(30)), nameof(timeSentWhenFailedMessageWasSentToTheErrorQueue)); + }); Assert.That(timeSent, Is.LessThanOrEqualTo(processingEnded), nameof(processingEnded)); - Assert.That(timeSent, Is.LessThanOrEqualTo(timeSentWhenFailedMessageWasSentToTheErrorQueue), nameof(timeSentWhenFailedMessageWasSentToTheErrorQueue)); + Assert.Multiple(() => + { + Assert.That(timeSent, Is.LessThanOrEqualTo(timeSentWhenFailedMessageWasSentToTheErrorQueue), nameof(timeSentWhenFailedMessageWasSentToTheErrorQueue)); - Assert.That(timeSentWhenFailedMessageWasSentToTheErrorQueue, Is.EqualTo(context.TimeSentOnTheFailingMessageWhenItWasHandled), nameof(timeSentWhenFailedMessageWasSentToTheErrorQueue)); - Assert.That(processingStarted, Is.LessThanOrEqualTo(processingEnded), nameof(processingStarted)); - Assert.IsTrue(context.IsMessageHandledByTheFaultEndpoint, nameof(context.IsMessageHandledByTheFaultEndpoint)); + Assert.That(timeSentWhenFailedMessageWasSentToTheErrorQueue, Is.EqualTo(context.TimeSentOnTheFailingMessageWhenItWasHandled), nameof(timeSentWhenFailedMessageWasSentToTheErrorQueue)); + Assert.That(processingStarted, Is.LessThanOrEqualTo(processingEnded), nameof(processingStarted)); + Assert.That(context.IsMessageHandledByTheFaultEndpoint, Is.True, nameof(context.IsMessageHandledByTheFaultEndpoint)); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_overriding_input_queue_name.cs b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_overriding_input_queue_name.cs index c7d66112441..8037f5b7a3f 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_overriding_input_queue_name.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_overriding_input_queue_name.cs @@ -15,8 +15,11 @@ public async Task Should_use_custom_queue_names() .Done(c => c.Done) .Run(); - Assert.IsTrue(context.Done); - Assert.IsTrue(context.InputQueue.StartsWith("OverriddenInputQueue")); + Assert.Multiple(() => + { + Assert.That(context.Done, Is.True); + Assert.That(context.InputQueue, Does.StartWith("OverriddenInputQueue")); + }); } public class MyEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_sending_ensure_proper_headers.cs b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_sending_ensure_proper_headers.cs index a5da4d49d6d..a8f58f4ef0e 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_sending_ensure_proper_headers.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Diagnostics/When_sending_ensure_proper_headers.cs @@ -20,10 +20,13 @@ public async Task Should_have_proper_headers_for_the_originating_endpoint() .Done(c => c.WasCalled) .Run(); - Assert.True(context.WasCalled, "The message handler should be called"); - Assert.AreEqual("SenderForEnsureProperHeadersTest", context.ReceivedHeaders[Headers.OriginatingEndpoint], "Message should contain the Originating endpoint"); - Assert.That(context.ReceivedHeaders[Headers.OriginatingHostId], Is.Not.Null.Or.Empty, "OriginatingHostId cannot be null or empty"); - Assert.That(context.ReceivedHeaders[Headers.OriginatingMachine], Is.Not.Null.Or.Empty, "Endpoint machine name cannot be null or empty"); + Assert.Multiple(() => + { + Assert.That(context.WasCalled, Is.True, "The message handler should be called"); + Assert.That(context.ReceivedHeaders[Headers.OriginatingEndpoint], Is.EqualTo("SenderForEnsureProperHeadersTest"), "Message should contain the Originating endpoint"); + Assert.That(context.ReceivedHeaders[Headers.OriginatingHostId], Is.Not.Null.Or.Empty, "OriginatingHostId cannot be null or empty"); + Assert.That(context.ReceivedHeaders[Headers.OriginatingMachine], Is.Not.Null.Or.Empty, "Endpoint machine name cannot be null or empty"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/FakeTransport/CriticalError/When_registering_custom_critical_error_handler.cs b/src/NServiceBus.AcceptanceTests/Core/FakeTransport/CriticalError/When_registering_custom_critical_error_handler.cs index b60bd387ae1..291c70d53dd 100644 --- a/src/NServiceBus.AcceptanceTests/Core/FakeTransport/CriticalError/When_registering_custom_critical_error_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Core/FakeTransport/CriticalError/When_registering_custom_critical_error_handler.cs @@ -19,8 +19,11 @@ public async Task Critical_error_should_be_raised_inside_delegate() .Done(c => c.ExceptionReceived) .Run(); - Assert.True(context.Message.StartsWith("Startup task failed to complete.")); - Assert.AreEqual("ExceptionInBusStarts", context.Exception.Message); + Assert.Multiple(() => + { + Assert.That(context.Message, Does.StartWith("Startup task failed to complete.")); + Assert.That(context.Exception.Message, Is.EqualTo("ExceptionInBusStarts")); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/FakeTransport/ProcessingOptimizations/When_using_concurrency_limit.cs b/src/NServiceBus.AcceptanceTests/Core/FakeTransport/ProcessingOptimizations/When_using_concurrency_limit.cs index 585e8764a70..63ce4e65da2 100644 --- a/src/NServiceBus.AcceptanceTests/Core/FakeTransport/ProcessingOptimizations/When_using_concurrency_limit.cs +++ b/src/NServiceBus.AcceptanceTests/Core/FakeTransport/ProcessingOptimizations/When_using_concurrency_limit.cs @@ -54,7 +54,7 @@ public Task Initialize(PushRuntimeSettings limitations, OnMessage onMessage, OnE public Task StartReceive(CancellationToken cancellationToken = default) { - Assert.AreEqual(10, pushSettings.MaxConcurrency); + Assert.That(pushSettings.MaxConcurrency, Is.EqualTo(10)); return Task.CompletedTask; } diff --git a/src/NServiceBus.AcceptanceTests/Core/Feature/When_depending_on_feature.cs b/src/NServiceBus.AcceptanceTests/Core/Feature/When_depending_on_feature.cs index e29fd07c30d..3a2d79cff4d 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Feature/When_depending_on_feature.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Feature/When_depending_on_feature.cs @@ -23,8 +23,11 @@ public async Task Should_start_startup_tasks_in_order_of_dependency() .Done(c => c.EndpointsStarted) .Run(); - Assert.That(context.StartCalled, Is.True); - Assert.That(context.StopCalled, Is.True); + Assert.Multiple(() => + { + Assert.That(context.StartCalled, Is.True); + Assert.That(context.StopCalled, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Feature/When_registering_a_startup_task.cs b/src/NServiceBus.AcceptanceTests/Core/Feature/When_registering_a_startup_task.cs index 20821450201..880557cb217 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Feature/When_registering_a_startup_task.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Feature/When_registering_a_startup_task.cs @@ -19,7 +19,7 @@ public async Task The_endpoint_should_start() .Done(c => c.SendOnlyEndpointWasStarted) .Run(); - Assert.True(context.SendOnlyEndpointWasStarted, "The endpoint should have started without any errors"); + Assert.That(context.SendOnlyEndpointWasStarted, Is.True, "The endpoint should have started without any errors"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Hosting/When_custom_host_id_is_configured.cs b/src/NServiceBus.AcceptanceTests/Core/Hosting/When_custom_host_id_is_configured.cs index 532ba952d46..921fd5b5778 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Hosting/When_custom_host_id_is_configured.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Hosting/When_custom_host_id_is_configured.cs @@ -22,8 +22,11 @@ public async Task Should_not_apply_default_to_be_FIPS_compliant() .Done(c => c.EndpointsStarted) .Run(); - Assert.False(context.HostIdDefaultApplied); - Assert.AreEqual(context.CustomHostId, context.HostIdObserved); + Assert.Multiple(() => + { + Assert.That(context.HostIdDefaultApplied, Is.False); + Assert.That(context.HostIdObserved, Is.EqualTo(context.CustomHostId)); + }); } public class MyEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Hosting/When_disabling_assembly_scanning.cs b/src/NServiceBus.AcceptanceTests/Core/Hosting/When_disabling_assembly_scanning.cs index 57dcec52280..4f757e6db3a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Hosting/When_disabling_assembly_scanning.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Hosting/When_disabling_assembly_scanning.cs @@ -15,7 +15,7 @@ public void Should_not_start_endpoint() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains($"Assembly scanning has been disabled. This prevents messages, message handlers, features and other functionality from loading correctly. Enable {nameof(AssemblyScannerConfiguration.ScanAppDomainAssemblies)} or {nameof(AssemblyScannerConfiguration.ScanFileSystemAssemblies)}", exception.Message); + Assert.That(exception.Message, Does.Contain($"Assembly scanning has been disabled. This prevents messages, message handlers, features and other functionality from loading correctly. Enable {nameof(AssemblyScannerConfiguration.ScanAppDomainAssemblies)} or {nameof(AssemblyScannerConfiguration.ScanFileSystemAssemblies)}")); } public class EndpointWithDisabledAssemblyScanning : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Hosting/When_endpoint_starts.cs b/src/NServiceBus.AcceptanceTests/Core/Hosting/When_endpoint_starts.cs index b4f2ffc475c..b2850d3b92f 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Hosting/When_endpoint_starts.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Hosting/When_endpoint_starts.cs @@ -30,9 +30,9 @@ await Scenario.Define() var startupDiagnoticsFileName = $"{endpointName}-configuration.txt"; var pathToFile = Path.Combine(basePath, startupDiagnoticsFileName); - Assert.True(File.Exists(pathToFile)); + Assert.That(File.Exists(pathToFile), Is.True); - TestContext.WriteLine(File.ReadAllText(pathToFile)); + await TestContext.Out.WriteLineAsync(await File.ReadAllTextAsync(pathToFile)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Hosting/When_failing_write_startup_diagnostics.cs b/src/NServiceBus.AcceptanceTests/Core/Hosting/When_failing_write_startup_diagnostics.cs index 27201b38d62..9af1eb13b1a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Hosting/When_failing_write_startup_diagnostics.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Hosting/When_failing_write_startup_diagnostics.cs @@ -17,7 +17,7 @@ public async Task Should_still_start_endpoint() .Done(c => c.EndpointsStarted) .Run(); - Assert.True(context.Logs.Any(l => l.Message.Contains("Diagnostics write failed"))); + Assert.That(context.Logs.Any(l => l.Message.Contains("Diagnostics write failed")), Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Installers/When_creating_queues.cs b/src/NServiceBus.AcceptanceTests/Core/Installers/When_creating_queues.cs index 8d62a1094d2..6a6fd1f26eb 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Installers/When_creating_queues.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Installers/When_creating_queues.cs @@ -25,7 +25,7 @@ public async Task Should_not_create_queues_when_installers_disabled() .Done(c => c.EndpointsStarted) .Run(); - Assert.IsFalse(context.SetupInfrastructure); + Assert.That(context.SetupInfrastructure, Is.False); } [Test] @@ -39,7 +39,7 @@ public async Task Should_create_queues_when_installers_enabled() .Done(c => c.EndpointsStarted) .Run(); - Assert.IsTrue(context.SetupInfrastructure); + Assert.That(context.SetupInfrastructure, Is.True); } [Test] @@ -62,10 +62,10 @@ public async Task Should_not_create_when_sendonly() .Done(c => c.EndpointsStarted) .Run(); - Assert.IsTrue(context.SetupInfrastructure); + Assert.That(context.SetupInfrastructure, Is.True); - CollectionAssert.DoesNotContain(context.SendingAddresses, errorQueueName); - CollectionAssert.DoesNotContain(context.SendingAddresses, auditQueueName); + Assert.That(context.SendingAddresses, Has.No.Member(errorQueueName)); + Assert.That(context.SendingAddresses, Has.No.Member(auditQueueName)); } [Test] @@ -84,22 +84,22 @@ public async Task Should_pass_receive_and_send_queue_addresses() .Done(c => c.EndpointsStarted) .Run(); - Assert.IsTrue(context.SetupInfrastructure); + Assert.That(context.SetupInfrastructure, Is.True); - CollectionAssert.AreEqual(new List + Assert.That(context.SendingAddresses, Is.EqualTo(new List { "myAudit", "error" - }, context.SendingAddresses); + }).AsCollection); var endpointName = AcceptanceTesting.Customization.Conventions.EndpointNamingConvention(typeof(Endpoint)); - CollectionAssert.AreEquivalent(new List<(string basename, string discriminator)> + Assert.That(context.ReceivingAddresses.Select(a => (a.BaseAddress, a.Discriminator)), Is.EquivalentTo(new List<(string basename, string discriminator)> { (endpointName, null), //main input queue (endpointName, instanceDiscriminator), // instance-specific queue ("MySatelliteAddress", null) - }, context.ReceivingAddresses.Select(a => (a.BaseAddress, a.Discriminator))); + })); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Installers/When_installers_enabled.cs b/src/NServiceBus.AcceptanceTests/Core/Installers/When_installers_enabled.cs index 86bc45eea49..45a83fef16f 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Installers/When_installers_enabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Installers/When_installers_enabled.cs @@ -17,7 +17,7 @@ public async Task Should_run_installers() .Done(c => c.EndpointsStarted) .Run(); - Assert.IsTrue(context.InstallerCalled); + Assert.That(context.InstallerCalled, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Installers/When_installers_not_enabled.cs b/src/NServiceBus.AcceptanceTests/Core/Installers/When_installers_not_enabled.cs index 13295687d96..882f4675b18 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Installers/When_installers_not_enabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Installers/When_installers_not_enabled.cs @@ -18,7 +18,7 @@ public async Task Should_not_run_installers() .Done(c => c.EndpointsStarted) .Run(); - Assert.IsFalse(context.InstallerCalled); + Assert.That(context.InstallerCalled, Is.False); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Installers/When_installing_endpoint.cs b/src/NServiceBus.AcceptanceTests/Core/Installers/When_installing_endpoint.cs index 47e4055bbe1..fc050e05a48 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Installers/When_installing_endpoint.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Installers/When_installing_endpoint.cs @@ -20,14 +20,17 @@ public async Task Should_only_execute_setup_and_complete() .WithComponent(new InstallationOnlyComponent()) .Run(); - Assert.IsTrue(context.InstallerCalled, "Should run installers"); - Assert.IsTrue(context.FeatureSetupCalled, "Should initialize Features"); - Assert.IsFalse(context.FeatureStartupTaskCalled, "Should not start FeatureStartupTasks"); - CollectionAssert.AreEqual(context.TransportStartupSequence, new string[] + Assert.Multiple(() => + { + Assert.That(context.InstallerCalled, Is.True, "Should run installers"); + Assert.That(context.FeatureSetupCalled, Is.True, "Should initialize Features"); + Assert.That(context.FeatureStartupTaskCalled, Is.False, "Should not start FeatureStartupTasks"); + }); + Assert.That(new string[] { $"{nameof(TransportDefinition)}.{nameof(TransportDefinition.Initialize)}", $"{nameof(IMessageReceiver)}.{nameof(IMessageReceiver.Initialize)} for receiver Main", - }, "Should not start the receivers"); + }, Is.EqualTo(context.TransportStartupSequence).AsCollection, "Should not start the receivers"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/JsonSerializer/When_deserializing_interface_message.cs b/src/NServiceBus.AcceptanceTests/Core/JsonSerializer/When_deserializing_interface_message.cs index a57e7704dfe..6b114e954d9 100644 --- a/src/NServiceBus.AcceptanceTests/Core/JsonSerializer/When_deserializing_interface_message.cs +++ b/src/NServiceBus.AcceptanceTests/Core/JsonSerializer/When_deserializing_interface_message.cs @@ -16,7 +16,7 @@ public async Task Should_work() .Done(c => c.GotTheMessage) .Run(); - Assert.True(context.GotTheMessage); + Assert.That(context.GotTheMessage, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/JsonSerializer/When_using_system_json_serializer.cs b/src/NServiceBus.AcceptanceTests/Core/JsonSerializer/When_using_system_json_serializer.cs index 44f180db61e..297af854c59 100644 --- a/src/NServiceBus.AcceptanceTests/Core/JsonSerializer/When_using_system_json_serializer.cs +++ b/src/NServiceBus.AcceptanceTests/Core/JsonSerializer/When_using_system_json_serializer.cs @@ -16,7 +16,7 @@ public async Task Should_work() .Done(c => c.GotTheMessage) .Run(); - Assert.True(context.GotTheMessage); + Assert.That(context.GotTheMessage, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_defining_outgoing_message_mutators.cs b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_defining_outgoing_message_mutators.cs index 74ec8dd76da..63d66852247 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_defining_outgoing_message_mutators.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_defining_outgoing_message_mutators.cs @@ -16,9 +16,12 @@ public async Task Should_be_applied_to_outgoing_messages() .Done(c => c.MessageProcessed) .Run(); - Assert.True(context.TransportMutatorCalled); - Assert.True(context.OtherTransportMutatorCalled); - Assert.True(context.MessageMutatorCalled); + Assert.Multiple(() => + { + Assert.That(context.TransportMutatorCalled, Is.True); + Assert.That(context.OtherTransportMutatorCalled, Is.True); + Assert.That(context.MessageMutatorCalled, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_incoming_mutator_changes_message_type.cs b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_incoming_mutator_changes_message_type.cs index 9a7c0f6386a..1526c71ef1f 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_incoming_mutator_changes_message_type.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_incoming_mutator_changes_message_type.cs @@ -17,10 +17,13 @@ public async Task Should_invoke_handlers_for_new_message_type() .Done(c => c.NewMessageHandlerCalled || c.OriginalMessageHandlerCalled) .Run(); - Assert.IsTrue(context.NewMessageHandlerCalled); - Assert.IsTrue(context.NewMessageSagaHandlerCalled); - Assert.IsFalse(context.OriginalMessageHandlerCalled); - Assert.IsFalse(context.OriginalMessageSagaHandlerCalled); + Assert.Multiple(() => + { + Assert.That(context.NewMessageHandlerCalled, Is.True); + Assert.That(context.NewMessageSagaHandlerCalled, Is.True); + Assert.That(context.OriginalMessageHandlerCalled, Is.False); + Assert.That(context.OriginalMessageSagaHandlerCalled, Is.False); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_mutating.cs b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_mutating.cs index 8b77d721265..0bd1a43c026 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_mutating.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_mutating.cs @@ -19,7 +19,7 @@ public async Task Context_should_be_populated() .Done(c => c.WasCalled) .Run(TimeSpan.FromHours(1)); - Assert.True(context.WasCalled, "The message handler should be called"); + Assert.That(context.WasCalled, Is.True, "The message handler should be called"); } public class Context : ScenarioContext @@ -77,37 +77,55 @@ public class Mutator : { public Task MutateIncoming(MutateIncomingMessageContext context) { - Assert.IsNotEmpty(context.Headers); - Assert.IsNotNull(context.Message); + Assert.Multiple(() => + { + Assert.That(context.Headers, Is.Not.Empty); + Assert.That(context.Message, Is.Not.Null); + }); return Task.CompletedTask; } public Task MutateIncoming(MutateIncomingTransportMessageContext context) { - Assert.IsNotEmpty(context.Headers); - Assert.IsNotNull(context.Body); + Assert.Multiple(() => + { + Assert.That(context.Headers, Is.Not.Empty); + Assert.That(context.Body, Is.Not.EqualTo(default(ReadOnlyMemory))); + }); return Task.CompletedTask; } public Task MutateOutgoing(MutateOutgoingMessageContext context) { - Assert.IsNotEmpty(context.OutgoingHeaders); - Assert.IsNotNull(context.OutgoingMessage); + Assert.Multiple(() => + { + Assert.That(context.OutgoingHeaders, Is.Not.Empty); + Assert.That(context.OutgoingMessage, Is.Not.Null); + }); context.TryGetIncomingHeaders(out var incomingHeaders); context.TryGetIncomingMessage(out var incomingMessage); - Assert.IsNotEmpty(incomingHeaders); - Assert.IsNotNull(incomingMessage); + Assert.Multiple(() => + { + Assert.That(incomingHeaders, Is.Not.Empty); + Assert.That(incomingMessage, Is.Not.Null); + }); return Task.CompletedTask; } public Task MutateOutgoing(MutateOutgoingTransportMessageContext context) { - Assert.IsNotEmpty(context.OutgoingHeaders); - Assert.IsNotNull(context.OutgoingBody); + Assert.Multiple(() => + { + Assert.That(context.OutgoingHeaders, Is.Not.Empty); + Assert.That(context.OutgoingBody, Is.Not.EqualTo(default(ReadOnlyMemory))); + }); context.TryGetIncomingHeaders(out var incomingHeaders); context.TryGetIncomingMessage(out var incomingMessage); - Assert.IsNotEmpty(incomingHeaders); - Assert.IsNotNull(incomingMessage); + Assert.Multiple(() => + { + Assert.That(incomingHeaders, Is.Not.Empty); + Assert.That(incomingMessage, Is.Not.Null); + }); return Task.CompletedTask; } } diff --git a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_outgoing_mutator_replaces_instance.cs b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_outgoing_mutator_replaces_instance.cs index ef5b39607af..2274a606e89 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_outgoing_mutator_replaces_instance.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_outgoing_mutator_replaces_instance.cs @@ -16,8 +16,11 @@ public async Task Message_sent_should_be_new_instance() .Done(c => c.V2MessageReceived) .Run(); - Assert.IsTrue(context.V2MessageReceived); - Assert.IsFalse(context.V1MessageReceived); + Assert.Multiple(() => + { + Assert.That(context.V2MessageReceived, Is.True); + Assert.That(context.V1MessageReceived, Is.False); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_using_outgoing_tm_mutator.cs b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_using_outgoing_tm_mutator.cs index 76f9afadb45..a69f88f1176 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Mutators/When_using_outgoing_tm_mutator.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Mutators/When_using_outgoing_tm_mutator.cs @@ -17,8 +17,11 @@ public async Task Should_be_able_to_update_message() .Done(c => c.MessageProcessed) .Run(); - Assert.True(context.CanAddHeaders); - Assert.AreEqual("SomeValue", context.MutatedPropertyValue, "Mutator should be able to mutate body."); + Assert.Multiple(() => + { + Assert.That(context.CanAddHeaders, Is.True); + Assert.That(context.MutatedPropertyValue, Is.EqualTo("SomeValue"), "Mutator should be able to mutate body."); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/ActivityTestingExtensions.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/ActivityTestingExtensions.cs index 801a79d9577..2df05a22e0a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/ActivityTestingExtensions.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/ActivityTestingExtensions.cs @@ -9,8 +9,11 @@ public static class ActivityTestingExtensions { public static void VerifyTag(this ImmutableDictionary tags, string tagName, string expectedValue) { - Assert.IsTrue(tags.TryGetValue(tagName, out var tagValue), $"Tags should contain key '{tagName}'"); - Assert.AreEqual(expectedValue, tagValue, $"Tag value with key '{tagName}' is incorrect"); + Assert.Multiple(() => + { + Assert.That(tags.TryGetValue(tagName, out var tagValue), Is.True, $"Tags should contain key '{tagName}'"); + Assert.That(tagValue, Is.EqualTo(expectedValue), $"Tag value with key '{tagName}' is incorrect"); + }); } /// diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Metrics/TestingMetricListener.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Metrics/TestingMetricListener.cs index 01cce8da1dd..4940c0f472d 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Metrics/TestingMetricListener.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Metrics/TestingMetricListener.cs @@ -19,7 +19,7 @@ public TestingMetricListener(string sourceName) { if (instrument.Meter.Name == sourceName) { - TestContext.WriteLine($"Subscribing to {instrument.Meter.Name}\\{instrument.Name}"); + TestContext.Out.WriteLine($"Subscribing to {instrument.Meter.Name}\\{instrument.Name}"); listener.EnableMeasurementEvents(instrument); } } @@ -30,7 +30,7 @@ public TestingMetricListener(string sourceName) ReadOnlySpan> t, object _) => { - TestContext.WriteLine($"{instrument.Meter.Name}\\{instrument.Name}:{measurement}"); + TestContext.Out.WriteLine($"{instrument.Meter.Name}\\{instrument.Name}:{measurement}"); var tags = t.ToArray(); ReportedMeters.AddOrUpdate(instrument.Name, measurement, (_, val) => val + measurement); @@ -41,7 +41,7 @@ public TestingMetricListener(string sourceName) ReadOnlySpan> t, object _) => { - TestContext.WriteLine($"{instrument.Meter.Name}\\{instrument.Name}:{measurement}"); + TestContext.Out.WriteLine($"{instrument.Meter.Name}\\{instrument.Name}:{measurement}"); var tags = t.ToArray(); ReportedMeters.AddOrUpdate(instrument.Name, 1, (_, val) => val + 1); Tags.AddOrUpdate(instrument.Name, _ => tags, (_, _) => tags); @@ -67,12 +67,15 @@ public void AssertMetric(string metricName, long expected) { if (expected == 0) { - Assert.False(ReportedMeters.ContainsKey(metricName), $"Should not have '{metricName}' metric reported."); + Assert.That(ReportedMeters.ContainsKey(metricName), Is.False, $"Should not have '{metricName}' metric reported."); } else { - Assert.True(ReportedMeters.ContainsKey(metricName), $"'{metricName}' metric was not reported."); - Assert.AreEqual(expected, ReportedMeters[metricName]); + Assert.Multiple(() => + { + Assert.That(ReportedMeters.ContainsKey(metricName), Is.True, $"'{metricName}' metric was not reported."); + Assert.That(ReportedMeters[metricName], Is.EqualTo(expected)); + }); } } @@ -98,7 +101,7 @@ public void AssertTags(string metricName, Dictionary expectedTag foreach (var kvp in expectedTags) { var actualTagValue = AssertTagKeyExists(metricName, kvp.Key); - Assert.AreEqual(kvp.Value, actualTagValue); + Assert.That(actualTagValue, Is.EqualTo(kvp.Value)); } } } \ No newline at end of file diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Metrics/When_message_is_processed_successfully.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Metrics/When_message_is_processed_successfully.cs index 03418a84f8c..c0892442028 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Metrics/When_message_is_processed_successfully.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Metrics/When_message_is_processed_successfully.cs @@ -107,10 +107,13 @@ public async Task Should_only_tag_most_concrete_type_on_metric() var fetchedEndpoint = metricsListener.AssertTagKeyExists("nservicebus.messaging.fetches", "nservicebus.queue"); - Assert.AreEqual(Conventions.EndpointNamingConvention(typeof(EndpointWithMetrics)), successEndpoint); - Assert.AreEqual(Conventions.EndpointNamingConvention(typeof(EndpointWithMetrics)), fetchedEndpoint); - Assert.AreEqual(typeof(OutgoingWithComplexHierarchyMessage).FullName, successType); - Assert.AreEqual(typeof(EndpointWithMetrics.ComplexMessageHandler).FullName, successHandlerType); + Assert.Multiple(() => + { + Assert.That(successEndpoint, Is.EqualTo(Conventions.EndpointNamingConvention(typeof(EndpointWithMetrics)))); + Assert.That(fetchedEndpoint, Is.EqualTo(Conventions.EndpointNamingConvention(typeof(EndpointWithMetrics)))); + Assert.That(successType, Is.EqualTo(typeof(OutgoingWithComplexHierarchyMessage).FullName)); + Assert.That(successHandlerType, Is.EqualTo(typeof(EndpointWithMetrics.ComplexMessageHandler).FullName)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/TestingActivityListener.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/TestingActivityListener.cs index 74725568e3c..a5fdb5ce06a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/TestingActivityListener.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/TestingActivityListener.cs @@ -48,7 +48,7 @@ public void Dispose() public void VerifyAllActivitiesCompleted() { - Assert.AreEqual(StartedActivities.Count, CompletedActivities.Count, "all started activities should be completed"); + Assert.That(CompletedActivities, Has.Count.EqualTo(StartedActivities.Count), "all started activities should be completed"); } } diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_ambient_trace_in_message_session.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_ambient_trace_in_message_session.cs index 10263f4a09b..324d18a7a68 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_ambient_trace_in_message_session.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_ambient_trace_in_message_session.cs @@ -37,12 +37,15 @@ public async Task Should_attach_to_ambient_trace() var outgoingMessageActivity = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities().Single(); var incomingMessageActivity = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities().Single(); - Assert.AreEqual(context.WrapperActivityId, outgoingMessageActivity.ParentId, "outgoing message should be connected to the ambient span"); - Assert.AreEqual(context.WrapperActivityRootId, outgoingMessageActivity.RootId, "outgoing message should be connected to the ambient trace"); - Assert.AreEqual(wrapperActivityTraceState, outgoingMessageActivity.TraceStateString, "ambient trace state should be floated to outgoing message span"); - Assert.AreEqual(outgoingMessageActivity.Id, incomingMessageActivity.ParentId, "received message should be connected to send operation span"); - Assert.AreEqual(context.WrapperActivityRootId, incomingMessageActivity.RootId, "received message should be connected to the ambient trace"); - Assert.AreEqual(wrapperActivityTraceState, incomingMessageActivity.TraceStateString, "ambient trace state should be floated to incoming message span"); + Assert.Multiple(() => + { + Assert.That(outgoingMessageActivity.ParentId, Is.EqualTo(context.WrapperActivityId), "outgoing message should be connected to the ambient span"); + Assert.That(outgoingMessageActivity.RootId, Is.EqualTo(context.WrapperActivityRootId), "outgoing message should be connected to the ambient trace"); + Assert.That(outgoingMessageActivity.TraceStateString, Is.EqualTo(wrapperActivityTraceState), "ambient trace state should be floated to outgoing message span"); + Assert.That(incomingMessageActivity.ParentId, Is.EqualTo(outgoingMessageActivity.Id), "received message should be connected to send operation span"); + Assert.That(incomingMessageActivity.RootId, Is.EqualTo(context.WrapperActivityRootId), "received message should be connected to the ambient trace"); + Assert.That(incomingMessageActivity.TraceStateString, Is.EqualTo(wrapperActivityTraceState), "ambient trace state should be floated to incoming message span"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_ambient_trace_in_pipeline.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_ambient_trace_in_pipeline.cs index ae739f339f3..e06d25a1f60 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_ambient_trace_in_pipeline.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_ambient_trace_in_pipeline.cs @@ -24,11 +24,14 @@ public async Task Should_attach_to_ambient_trace() var handlerActivity = NServicebusActivityListener.CompletedActivities.GetInvokedHandlerActivities().First(); var sendFromHandlerActivity = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities().Last(); - Assert.AreEqual(context.AmbientActivityId, sendFromHandlerActivity.ParentId, "the outgoing message should be connected to the ambient span"); - Assert.AreEqual(context.AmbientActivityRootId, sendFromHandlerActivity.RootId, "outgoing and ambient activity should belong to same trace"); - Assert.AreEqual(ExpectedTraceState, sendFromHandlerActivity.TraceStateString, "outgoing activity should capture ambient trace state"); - Assert.AreEqual(handlerActivity.Id, context.AmbientActivityParentId, "the ambient activity should be connected to the handler span"); - Assert.AreEqual(handlerActivity.RootId, context.AmbientActivityRootId, "handler and ambient activity should belong to same trace"); + Assert.Multiple(() => + { + Assert.That(sendFromHandlerActivity.ParentId, Is.EqualTo(context.AmbientActivityId), "the outgoing message should be connected to the ambient span"); + Assert.That(sendFromHandlerActivity.RootId, Is.EqualTo(context.AmbientActivityRootId), "outgoing and ambient activity should belong to same trace"); + Assert.That(sendFromHandlerActivity.TraceStateString, Is.EqualTo(ExpectedTraceState), "outgoing activity should capture ambient trace state"); + Assert.That(context.AmbientActivityParentId, Is.EqualTo(handlerActivity.Id), "the ambient activity should be connected to the handler span"); + Assert.That(context.AmbientActivityRootId, Is.EqualTo(handlerActivity.RootId), "handler and ambient activity should belong to same trace"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_event_has_trace.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_event_has_trace.cs index d9b81ef612b..655d1cfd538 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_event_has_trace.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_event_has_trace.cs @@ -30,12 +30,15 @@ public async Task Should_correlate_trace_from_publish() var incomingActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); var outgoingActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(2, incomingActivities.Count, "2 messages are received as part of this test (event + reply)"); - Assert.AreEqual(1, outgoingActivities.Count, "1 message is sent as part of this test (reply)"); - Assert.AreEqual(1, NServicebusActivityListener.CompletedActivities.GetPublishEventActivities().Count, "1 event is published as part of this test"); + Assert.Multiple(() => + { + Assert.That(incomingActivities, Has.Count.EqualTo(2), "2 messages are received as part of this test (event + reply)"); + Assert.That(outgoingActivities, Has.Count.EqualTo(1), "1 message is sent as part of this test (reply)"); + Assert.That(NServicebusActivityListener.CompletedActivities.GetPublishEventActivities(), Has.Count.EqualTo(1), "1 event is published as part of this test"); - Assert.IsTrue(incomingActivities.Concat(outgoingActivities) - .All(a => a.RootId == incomingActivities[0].RootId), "all activities should belong to the same trace"); + Assert.That(incomingActivities.Concat(outgoingActivities) + .All(a => a.RootId == incomingActivities[0].RootId), Is.True, "all activities should belong to the same trace"); + }); } public class Context : ScenarioContext { diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_baggage_header.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_baggage_header.cs index 5a44e3fe769..0e028ad265c 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_baggage_header.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_baggage_header.cs @@ -24,7 +24,7 @@ public async Task Should_propagate_baggage_to_activity() .Run(); var incomingMessageTraces = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); - Assert.AreEqual(1, incomingMessageTraces.Count, "There should be 1 message received"); + Assert.That(incomingMessageTraces, Has.Count.EqualTo(1), "There should be 1 message received"); var incomingMessageTrace = incomingMessageTraces.Single(); VerifyBaggageItem("key1", "value1"); @@ -33,8 +33,8 @@ public async Task Should_propagate_baggage_to_activity() void VerifyBaggageItem(string key, string expectedValue) { var baggageItemValue = incomingMessageTrace.GetBaggageItem(key); - Assert.IsNotNull(baggageItemValue, $"Baggage item {key} should be populated"); - Assert.AreEqual(expectedValue, baggageItemValue, $"Baggage item {key} is not set correctly"); + Assert.That(baggageItemValue, Is.Not.Null, $"Baggage item {key} should be populated"); + Assert.That(baggageItemValue, Is.EqualTo(expectedValue), $"Baggage item {key} is not set correctly"); } } diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_no_trace.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_no_trace.cs index 96a1e71572c..f1068f77b18 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_no_trace.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_no_trace.cs @@ -20,7 +20,7 @@ public async Task Should_start_new_trace() .Run(); var incomingMessageActivity = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities().Single(); - Assert.AreEqual(null, incomingMessageActivity.ParentId, "should start a trace when incoming message isn't part of a trace already"); + Assert.That(incomingMessageActivity.ParentId, Is.EqualTo(null), "should start a trace when incoming message isn't part of a trace already"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_trace.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_trace.cs index 71761c7f7f1..4446131102d 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_trace.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_has_trace.cs @@ -22,24 +22,30 @@ public async Task Should_correlate_trace_from_send() var incomingMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); var outgoingMessageActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(2, incomingMessageActivities.Count, "2 messages are received as part of this test"); - Assert.AreEqual(2, outgoingMessageActivities.Count, "2 messages are sent as part of this test"); + Assert.Multiple(() => + { + Assert.That(incomingMessageActivities, Has.Count.EqualTo(2), "2 messages are received as part of this test"); + Assert.That(outgoingMessageActivities, Has.Count.EqualTo(2), "2 messages are sent as part of this test"); + }); var sendRequest = outgoingMessageActivities[0]; var receiveRequest = incomingMessageActivities[0]; var sendReply = outgoingMessageActivities[1]; var receiveReply = incomingMessageActivities[1]; - Assert.AreEqual(sendRequest.RootId, receiveRequest.RootId, "first send operation is the root activity"); - Assert.AreEqual(sendRequest.Id, receiveRequest.ParentId, "first incoming message is correlated to the first send operation"); - Assert.AreEqual(sendRequest.RootId, sendReply.RootId, "first send operation is the root activity"); - Assert.AreEqual(sendReply.Id, receiveReply.ParentId, "second incoming message is correlated to the second send operation"); - Assert.AreEqual(sendRequest.RootId, receiveReply.RootId, "first send operation is the root activity"); - - Assert.AreEqual(context.IncomingMessageId, sendRequest.Tags.ToImmutableDictionary()["nservicebus.message_id"]); - Assert.AreEqual(context.IncomingMessageId, receiveRequest.Tags.ToImmutableDictionary()["nservicebus.message_id"]); - Assert.AreEqual(context.ReplyMessageId, sendReply.Tags.ToImmutableDictionary()["nservicebus.message_id"]); - Assert.AreEqual(context.ReplyMessageId, receiveReply.Tags.ToImmutableDictionary()["nservicebus.message_id"]); + Assert.Multiple(() => + { + Assert.That(receiveRequest.RootId, Is.EqualTo(sendRequest.RootId), "first send operation is the root activity"); + Assert.That(receiveRequest.ParentId, Is.EqualTo(sendRequest.Id), "first incoming message is correlated to the first send operation"); + Assert.That(sendReply.RootId, Is.EqualTo(sendRequest.RootId), "first send operation is the root activity"); + Assert.That(receiveReply.ParentId, Is.EqualTo(sendReply.Id), "second incoming message is correlated to the second send operation"); + Assert.That(receiveReply.RootId, Is.EqualTo(sendRequest.RootId), "first send operation is the root activity"); + + Assert.That(sendRequest.Tags.ToImmutableDictionary()["nservicebus.message_id"], Is.EqualTo(context.IncomingMessageId)); + Assert.That(receiveRequest.Tags.ToImmutableDictionary()["nservicebus.message_id"], Is.EqualTo(context.IncomingMessageId)); + Assert.That(sendReply.Tags.ToImmutableDictionary()["nservicebus.message_id"], Is.EqualTo(context.ReplyMessageId)); + Assert.That(receiveReply.Tags.ToImmutableDictionary()["nservicebus.message_id"], Is.EqualTo(context.ReplyMessageId)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_moved_to_error_queue.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_moved_to_error_queue.cs index ac24c594685..f7b04ca90ff 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_moved_to_error_queue.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_moved_to_error_queue.cs @@ -19,8 +19,11 @@ public async Task Should_add_start_new_trace_header() .Run(); var failedMessage = context.FailedMessages.First().Value.First(); - Assert.IsTrue(failedMessage.Headers.ContainsKey(Headers.StartNewTrace)); - Assert.AreEqual(bool.TrueString, failedMessage.Headers[Headers.StartNewTrace]); + Assert.Multiple(() => + { + Assert.That(failedMessage.Headers.ContainsKey(Headers.StartNewTrace), Is.True); + Assert.That(failedMessage.Headers[Headers.StartNewTrace], Is.EqualTo(bool.TrueString)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_was_delayed.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_was_delayed.cs index 5b2c0c65c6d..6fa69c676f0 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_was_delayed.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_incoming_message_was_delayed.cs @@ -29,23 +29,29 @@ public async Task By_sendoptions_Should_create_new_trace_and_link_to_send() var incomingMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); var outgoingMessageActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(2, incomingMessageActivities.Count, "2 messages are received as part of this test"); - Assert.AreEqual(2, outgoingMessageActivities.Count, "2 messages are sent as part of this test"); + Assert.Multiple(() => + { + Assert.That(incomingMessageActivities, Has.Count.EqualTo(2), "2 messages are received as part of this test"); + Assert.That(outgoingMessageActivities, Has.Count.EqualTo(2), "2 messages are sent as part of this test"); + }); var sendRequest = outgoingMessageActivities[0]; var receiveRequest = incomingMessageActivities[0]; var sendReply = outgoingMessageActivities[1]; var receiveReply = incomingMessageActivities[1]; - Assert.AreNotEqual(sendRequest.RootId, receiveRequest.RootId, "send and receive operations are part of different root activities"); - Assert.IsNull(receiveRequest.ParentId, "first incoming message does not have a parent, it's a root"); - Assert.AreNotEqual(sendRequest.RootId, sendReply.RootId, "first send operation is different than the root activity of the reply"); - Assert.AreEqual(sendReply.Id, receiveReply.ParentId, "second incoming message is correlated to the second send operation"); - Assert.AreEqual(sendReply.RootId, receiveReply.RootId, "second incoming message is the root activity"); + Assert.Multiple(() => + { + Assert.That(receiveRequest.RootId, Is.Not.EqualTo(sendRequest.RootId), "send and receive operations are part of different root activities"); + Assert.That(receiveRequest.ParentId, Is.Null, "first incoming message does not have a parent, it's a root"); + Assert.That(sendReply.RootId, Is.Not.EqualTo(sendRequest.RootId), "first send operation is different than the root activity of the reply"); + Assert.That(receiveReply.ParentId, Is.EqualTo(sendReply.Id), "second incoming message is correlated to the second send operation"); + Assert.That(receiveReply.RootId, Is.EqualTo(sendReply.RootId), "second incoming message is the root activity"); + }); ActivityLink link = receiveRequest.Links.FirstOrDefault(); - Assert.IsNotNull(link, "second receive has a link"); - Assert.AreEqual(sendRequest.TraceId, link.Context.TraceId, "second receive is linked to send operation"); + Assert.That(link, Is.Not.EqualTo(default(ActivityLink)), "second receive has a link"); + Assert.That(link.Context.TraceId, Is.EqualTo(sendRequest.TraceId), "second receive is linked to send operation"); } [Test] @@ -61,21 +67,27 @@ public async Task By_retry_Should_create_new_trace_and_link_to_send() var incomingMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); var outgoingMessageActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(2, incomingMessageActivities.Count, "2 messages are received as part of this test (2 attempts)"); - Assert.AreEqual(1, outgoingMessageActivities.Count, "1 message sent as part of this test"); + Assert.Multiple(() => + { + Assert.That(incomingMessageActivities, Has.Count.EqualTo(2), "2 messages are received as part of this test (2 attempts)"); + Assert.That(outgoingMessageActivities, Has.Count.EqualTo(1), "1 message sent as part of this test"); + }); var sendRequest = outgoingMessageActivities[0]; var firstAttemptReceiveRequest = incomingMessageActivities[0]; var secondAttemptReceiveRequest = incomingMessageActivities[1]; - Assert.AreEqual(sendRequest.RootId, firstAttemptReceiveRequest.RootId, "first send operation is the root activity"); - Assert.AreEqual(sendRequest.Id, firstAttemptReceiveRequest.ParentId, "first incoming message is correlated to the first send operation"); + Assert.Multiple(() => + { + Assert.That(firstAttemptReceiveRequest.RootId, Is.EqualTo(sendRequest.RootId), "first send operation is the root activity"); + Assert.That(firstAttemptReceiveRequest.ParentId, Is.EqualTo(sendRequest.Id), "first incoming message is correlated to the first send operation"); - Assert.AreNotEqual(sendRequest.RootId, secondAttemptReceiveRequest.RootId, "send and 2nd receive operations are part of different root activities"); - Assert.IsNull(secondAttemptReceiveRequest.ParentId, "first incoming message does not have a parent, it's a root"); + Assert.That(secondAttemptReceiveRequest.RootId, Is.Not.EqualTo(sendRequest.RootId), "send and 2nd receive operations are part of different root activities"); + Assert.That(secondAttemptReceiveRequest.ParentId, Is.Null, "first incoming message does not have a parent, it's a root"); + }); ActivityLink link = secondAttemptReceiveRequest.Links.FirstOrDefault(); - Assert.IsNotNull(link, "second receive has a link"); - Assert.AreEqual(sendRequest.TraceId, link.Context.TraceId, "second receive is linked to send operation"); + Assert.That(link, Is.Not.EqualTo(default(ActivityLink)), "second receive has a link"); + Assert.That(link.Context.TraceId, Is.EqualTo(sendRequest.TraceId), "second receive is linked to send operation"); } [Test] @@ -89,8 +101,11 @@ public async Task By_saga_timeout_Should_create_new_trace_and_link_to_send() var incomingMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); var outgoingMessageActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(3, incomingMessageActivities.Count, "3 messages are received as part of this test"); - Assert.AreEqual(3, outgoingMessageActivities.Count, "3 messages are sent as part of this test"); + Assert.Multiple(() => + { + Assert.That(incomingMessageActivities, Has.Count.EqualTo(3), "3 messages are received as part of this test"); + Assert.That(outgoingMessageActivities, Has.Count.EqualTo(3), "3 messages are sent as part of this test"); + }); var startSagaSend = outgoingMessageActivities[0]; var startSagaReceive = incomingMessageActivities[0]; @@ -99,19 +114,25 @@ public async Task By_saga_timeout_Should_create_new_trace_and_link_to_send() var completeSagaSend = outgoingMessageActivities[2]; var completeSagaReceive = incomingMessageActivities[2]; - Assert.AreEqual(startSagaSend.RootId, startSagaReceive.RootId, "send start saga operation is the root activity of the receive start saga operation"); - Assert.AreEqual(startSagaSend.Id, startSagaReceive.ParentId, "start saga receive operation is child of the start saga send operation"); - Assert.AreEqual(startSagaSend.RootId, timeoutSend.RootId, "timeout send operation is part of the start saga operation root"); + Assert.Multiple(() => + { + Assert.That(startSagaReceive.RootId, Is.EqualTo(startSagaSend.RootId), "send start saga operation is the root activity of the receive start saga operation"); + Assert.That(startSagaReceive.ParentId, Is.EqualTo(startSagaSend.Id), "start saga receive operation is child of the start saga send operation"); + Assert.That(timeoutSend.RootId, Is.EqualTo(startSagaSend.RootId), "timeout send operation is part of the start saga operation root"); - Assert.AreNotEqual(timeoutSend.RootId, timeoutReceive.RootId, "timeout send and receive operations are part of different root activities"); - Assert.IsNull(timeoutReceive.ParentId, "timeout receive operation does not have a parent, it's a root"); + Assert.That(timeoutReceive.RootId, Is.Not.EqualTo(timeoutSend.RootId), "timeout send and receive operations are part of different root activities"); + Assert.That(timeoutReceive.ParentId, Is.Null, "timeout receive operation does not have a parent, it's a root"); + }); ActivityLink timeoutReceiveLink = timeoutReceive.Links.FirstOrDefault(); - Assert.IsNotNull(timeoutReceiveLink, "timeout receive operation is linked"); - Assert.AreEqual(timeoutSend.TraceId, timeoutReceiveLink.Context.TraceId, "imeout receive operation links to the timeout send operation"); + Assert.That(timeoutReceiveLink, Is.Not.EqualTo(default(ActivityLink)), "timeout receive operation is linked"); + Assert.Multiple(() => + { + Assert.That(timeoutReceiveLink.Context.TraceId, Is.EqualTo(timeoutSend.TraceId), "imeout receive operation links to the timeout send operation"); - Assert.AreEqual(timeoutReceive.RootId, completeSagaSend.RootId, "timeout receive operation is the root of the complete saga send operation"); - Assert.AreEqual(timeoutReceive.RootId, completeSagaReceive.RootId, "timeout receive operation is the root of the complete saga receive operation"); - Assert.AreEqual(completeSagaSend.Id, completeSagaReceive.ParentId, "complete saga send operation is the parent of the complete saga receive operation"); + Assert.That(completeSagaSend.RootId, Is.EqualTo(timeoutReceive.RootId), "timeout receive operation is the root of the complete saga send operation"); + Assert.That(completeSagaReceive.RootId, Is.EqualTo(timeoutReceive.RootId), "timeout receive operation is the root of the complete saga receive operation"); + Assert.That(completeSagaReceive.ParentId, Is.EqualTo(completeSagaSend.Id), "complete saga send operation is the parent of the complete saga receive operation"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_outgoing_activity_has_baggage.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_outgoing_activity_has_baggage.cs index 11ad106ad96..ddd458b8bef 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_outgoing_activity_has_baggage.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_outgoing_activity_has_baggage.cs @@ -34,7 +34,7 @@ public async Task Should_propagate_baggage_to_headers() .Done(ctx => ctx.MessageReceived) .Run(); - Assert.AreEqual("key2=value2,key1=value1", context.BaggageHeader); + Assert.That(context.BaggageHeader, Is.EqualTo("key2=value2,key1=value1")); } class TestEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_fails.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_fails.cs index 0412972693e..ec404ad1262 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_fails.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_fails.cs @@ -19,19 +19,25 @@ public async Task Should_mark_span_as_failed() .When(s => s.SendLocal(new FailingMessage()))) .Done(c => c.HandlerInvoked).Run(); - Assert.AreEqual(1, context.FailedMessages.Count, "the message should have failed"); + Assert.That(context.FailedMessages, Has.Count.EqualTo(1), "the message should have failed"); Activity failedPipelineActivity = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities().Single(); - Assert.AreEqual(ActivityStatusCode.Error, failedPipelineActivity.Status); - Assert.AreEqual(ErrorMessage, failedPipelineActivity.StatusDescription); + Assert.Multiple(() => + { + Assert.That(failedPipelineActivity.Status, Is.EqualTo(ActivityStatusCode.Error)); + Assert.That(failedPipelineActivity.StatusDescription, Is.EqualTo(ErrorMessage)); + }); var pipelineActivityTags = failedPipelineActivity.Tags.ToImmutableDictionary(); pipelineActivityTags.VerifyTag("otel.status_code", "ERROR"); pipelineActivityTags.VerifyTag("otel.status_description", ErrorMessage); Activity failedHandlerActivity = NServicebusActivityListener.CompletedActivities.GetInvokedHandlerActivities().Single(); - Assert.AreEqual(ActivityStatusCode.Error, failedHandlerActivity.Status); - Assert.AreEqual(ErrorMessage, failedHandlerActivity.StatusDescription); + Assert.Multiple(() => + { + Assert.That(failedHandlerActivity.Status, Is.EqualTo(ActivityStatusCode.Error)); + Assert.That(failedHandlerActivity.StatusDescription, Is.EqualTo(ErrorMessage)); + }); var handlerActivityTags = failedHandlerActivity.Tags.ToImmutableDictionary(); handlerActivityTags.VerifyTag("otel.status_code", "ERROR"); diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_incoming_message.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_incoming_message.cs index 1396b17c391..66109ed6187 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_incoming_message.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_incoming_message.cs @@ -20,14 +20,17 @@ public async Task Should_create_incoming_message_span() .Run(); var incomingMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); - Assert.AreEqual(1, incomingMessageActivities.Count, "1 message is being processed"); + Assert.That(incomingMessageActivities, Has.Count.EqualTo(1), "1 message is being processed"); var incomingActivity = incomingMessageActivities.Single(); - Assert.AreEqual(ActivityKind.Consumer, incomingActivity.Kind, "asynchronous receivers should use 'Consumer'"); + Assert.Multiple(() => + { + Assert.That(incomingActivity.Kind, Is.EqualTo(ActivityKind.Consumer), "asynchronous receivers should use 'Consumer'"); - Assert.AreEqual(ActivityStatusCode.Ok, incomingActivity.Status); + Assert.That(incomingActivity.Status, Is.EqualTo(ActivityStatusCode.Ok)); + }); var destination = AcceptanceTesting.Customization.Conventions.EndpointNamingConvention(typeof(ReceivingEndpoint)); - Assert.AreEqual("process message", incomingActivity.DisplayName); + Assert.That(incomingActivity.DisplayName, Is.EqualTo("process message")); var incomingActivityTags = incomingActivity.Tags.ToImmutableDictionary(); diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_message_with_multiple_handlers.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_message_with_multiple_handlers.cs index 800526ccc2e..2bbffa0dab5 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_message_with_multiple_handlers.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_message_with_multiple_handlers.cs @@ -21,22 +21,28 @@ public async Task Should_create_message_handler_spans() var invokedHandlerActivities = NServicebusActivityListener.CompletedActivities.GetInvokedHandlerActivities(); var receivePipelineActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); - Assert.AreEqual(2, invokedHandlerActivities.Count, "a dedicated span for each handler should be created"); - Assert.AreEqual(1, receivePipelineActivities.Count, "the receive pipeline should be invoked once"); + Assert.Multiple(() => + { + Assert.That(invokedHandlerActivities, Has.Count.EqualTo(2), "a dedicated span for each handler should be created"); + Assert.That(receivePipelineActivities, Has.Count.EqualTo(1), "the receive pipeline should be invoked once"); + }); var recordedHandlerTypes = new HashSet(); foreach (var invokedHandlerActivity in invokedHandlerActivities) { var handlerTypeTag = invokedHandlerActivity.GetTagItem("nservicebus.handler.handler_type") as string; - Assert.NotNull(handlerTypeTag, "Handler type tag should be set"); + Assert.That(handlerTypeTag, Is.Not.Null, "Handler type tag should be set"); recordedHandlerTypes.Add(handlerTypeTag); - Assert.AreEqual(receivePipelineActivities[0].Id, invokedHandlerActivity.ParentId); - Assert.AreEqual(ActivityStatusCode.Ok, invokedHandlerActivity.Status); + Assert.Multiple(() => + { + Assert.That(invokedHandlerActivity.ParentId, Is.EqualTo(receivePipelineActivities[0].Id)); + Assert.That(invokedHandlerActivity.Status, Is.EqualTo(ActivityStatusCode.Ok)); + }); } - Assert.True(recordedHandlerTypes.Contains(typeof(ReceivingEndpoint.HandlerOne).FullName), "invocation of handler one should be traced"); - Assert.True(recordedHandlerTypes.Contains(typeof(ReceivingEndpoint.HandlerTwo).FullName), "invocation of handler two should be traced"); + Assert.That(recordedHandlerTypes, Does.Contain(typeof(ReceivingEndpoint.HandlerOne).FullName), "invocation of handler one should be traced"); + Assert.That(recordedHandlerTypes, Does.Contain(typeof(ReceivingEndpoint.HandlerTwo).FullName), "invocation of handler two should be traced"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_message_with_saga_handler.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_message_with_saga_handler.cs index 450bee830c7..4d9c94a6e1a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_message_with_saga_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_processing_message_with_saga_handler.cs @@ -23,7 +23,7 @@ public async Task Should_trace_saga_id() var invokedHandlerActivities = NServicebusActivityListener.CompletedActivities.GetInvokedHandlerActivities(); - Assert.AreEqual(1, invokedHandlerActivities.Count, "One handlers should be invoked"); + Assert.That(invokedHandlerActivities, Has.Count.EqualTo(1), "One handlers should be invoked"); var handlerActivityTags = invokedHandlerActivities.Single().Tags.ToImmutableDictionary(); handlerActivityTags.VerifyTag("nservicebus.handler.handler_type", typeof(TestEndpoint.TracedSaga).FullName); diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_publishing_messages.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_publishing_messages.cs index 17a353e5c3c..921afaffdd8 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_publishing_messages.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_publishing_messages.cs @@ -29,17 +29,20 @@ public async Task Should_create_outgoing_event_span() .Run(); var outgoingEventActivities = NServicebusActivityListener.CompletedActivities.GetPublishEventActivities(); - Assert.AreEqual(1, outgoingEventActivities.Count, "1 event is being published"); + Assert.That(outgoingEventActivities, Has.Count.EqualTo(1), "1 event is being published"); var publishedMessage = outgoingEventActivities.Single(); publishedMessage.VerifyUniqueTags(); - Assert.AreEqual("publish event", publishedMessage.DisplayName); - Assert.IsNull(publishedMessage.ParentId, "publishes without ambient span should start a new trace"); + Assert.Multiple(() => + { + Assert.That(publishedMessage.DisplayName, Is.EqualTo("publish event")); + Assert.That(publishedMessage.ParentId, Is.Null, "publishes without ambient span should start a new trace"); + }); var sentMessageTags = publishedMessage.Tags.ToImmutableDictionary(); sentMessageTags.VerifyTag("nservicebus.message_id", context.PublishedMessageId); - Assert.IsNotNull(context.TraceParentHeader, "tracing header should be set on the published event"); + Assert.That(context.TraceParentHeader, Is.Not.Null, "tracing header should be set on the published event"); } [Test] @@ -67,16 +70,22 @@ public async Task Should_create_child_on_receive_when_requested_via_options() var publishMessageActivities = NServicebusActivityListener.CompletedActivities.GetPublishEventActivities(); var receiveMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); - Assert.AreEqual(1, publishMessageActivities.Count, "1 message is published as part of this test"); - Assert.AreEqual(1, receiveMessageActivities.Count, "1 message is received as part of this test"); + Assert.Multiple(() => + { + Assert.That(publishMessageActivities, Has.Count.EqualTo(1), "1 message is published as part of this test"); + Assert.That(receiveMessageActivities, Has.Count.EqualTo(1), "1 message is received as part of this test"); + }); var publishRequest = publishMessageActivities[0]; var receiveRequest = receiveMessageActivities[0]; - Assert.AreEqual(publishRequest.RootId, receiveRequest.RootId, "publish and receive operations are part the same root activity"); - Assert.IsNotNull(receiveRequest.ParentId, "incoming message does have a parent"); + Assert.Multiple(() => + { + Assert.That(receiveRequest.RootId, Is.EqualTo(publishRequest.RootId), "publish and receive operations are part the same root activity"); + Assert.That(receiveRequest.ParentId, Is.Not.Null, "incoming message does have a parent"); + }); - CollectionAssert.IsEmpty(receiveRequest.Links, "receive does not have links"); + Assert.That(receiveRequest.Links, Is.Empty, "receive does not have links"); } [Test] @@ -102,18 +111,24 @@ public async Task Should_create_new_linked_trace_on_receive_by_default() var publishMessageActivities = NServicebusActivityListener.CompletedActivities.GetPublishEventActivities(); var receiveMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); - Assert.AreEqual(1, publishMessageActivities.Count, "1 message is published as part of this test"); - Assert.AreEqual(1, receiveMessageActivities.Count, "1 message is received as part of this test"); + Assert.Multiple(() => + { + Assert.That(publishMessageActivities, Has.Count.EqualTo(1), "1 message is published as part of this test"); + Assert.That(receiveMessageActivities, Has.Count.EqualTo(1), "1 message is received as part of this test"); + }); var publishRequest = publishMessageActivities[0]; var receiveRequest = receiveMessageActivities[0]; - Assert.AreNotEqual(publishRequest.RootId, receiveRequest.RootId, "publish and receive operations are part of different root activities"); - Assert.IsNull(receiveRequest.ParentId, "incoming message does not have a parent, it's a root"); + Assert.Multiple(() => + { + Assert.That(receiveRequest.RootId, Is.Not.EqualTo(publishRequest.RootId), "publish and receive operations are part of different root activities"); + Assert.That(receiveRequest.ParentId, Is.Null, "incoming message does not have a parent, it's a root"); + }); ActivityLink link = receiveRequest.Links.FirstOrDefault(); - Assert.IsNotNull(link, "Receive has a link"); - Assert.AreEqual(publishRequest.TraceId, link.Context.TraceId, "receive is linked to publish operation"); + Assert.That(link, Is.Not.EqualTo(default(ActivityLink)), "Receive has a link"); + Assert.That(link.Context.TraceId, Is.EqualTo(publishRequest.TraceId), "receive is linked to publish operation"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_retrying_messages.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_retrying_messages.cs index cd42887ea2d..3a3feee3722 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_retrying_messages.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_retrying_messages.cs @@ -22,12 +22,18 @@ await Scenario.Define() var receiveActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); var sendActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(1, sendActivities.Count); - Assert.AreEqual(2, receiveActivities.Count, "the message should be processed twice due to one immediate retry"); - Assert.AreEqual(sendActivities[0].Id, receiveActivities[0].ParentId, "should not change parent span"); - Assert.AreEqual(sendActivities[0].Id, receiveActivities[1].ParentId, "should not change parent span"); + Assert.Multiple(() => + { + Assert.That(sendActivities, Has.Count.EqualTo(1)); + Assert.That(receiveActivities, Has.Count.EqualTo(2), "the message should be processed twice due to one immediate retry"); + }); + Assert.Multiple(() => + { + Assert.That(receiveActivities[0].ParentId, Is.EqualTo(sendActivities[0].Id), "should not change parent span"); + Assert.That(receiveActivities[1].ParentId, Is.EqualTo(sendActivities[0].Id), "should not change parent span"); - Assert.IsTrue(sendActivities.Concat(receiveActivities).All(a => a.TraceId == sendActivities[0].TraceId), "all activities should be part of the same trace"); + Assert.That(sendActivities.Concat(receiveActivities).All(a => a.TraceId == sendActivities[0].TraceId), Is.True, "all activities should be part of the same trace"); + }); } [Test] @@ -46,12 +52,18 @@ await Scenario.Define() var receiveActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); var sendActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(1, sendActivities.Count); - Assert.AreEqual(2, receiveActivities.Count, "the message should be processed twice due to one immediate retry"); - Assert.AreEqual(sendActivities[0].Id, receiveActivities[0].ParentId, "should not change parent span"); - Assert.AreEqual(sendActivities[0].Id, receiveActivities[1].ParentId, "should not change parent span"); + Assert.Multiple(() => + { + Assert.That(sendActivities, Has.Count.EqualTo(1)); + Assert.That(receiveActivities, Has.Count.EqualTo(2), "the message should be processed twice due to one immediate retry"); + }); + Assert.Multiple(() => + { + Assert.That(receiveActivities[0].ParentId, Is.EqualTo(sendActivities[0].Id), "should not change parent span"); + Assert.That(receiveActivities[1].ParentId, Is.EqualTo(sendActivities[0].Id), "should not change parent span"); - Assert.IsTrue(sendActivities.Concat(receiveActivities).All(a => a.TraceId == sendActivities[0].TraceId), "all activities should be part of the same trace"); + Assert.That(sendActivities.Concat(receiveActivities).All(a => a.TraceId == sendActivities[0].TraceId), Is.True, "all activities should be part of the same trace"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_messages.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_messages.cs index fd8a8bfccf8..c7641d28cc4 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_messages.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_messages.cs @@ -21,11 +21,14 @@ public async Task Should_create_outgoing_message_span() .Run(); var outgoingMessageActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(1, outgoingMessageActivities.Count, "1 message is being sent"); + Assert.That(outgoingMessageActivities, Has.Count.EqualTo(1), "1 message is being sent"); var sentMessage = outgoingMessageActivities.Single(); - Assert.IsNull(sentMessage.ParentId, "sends without ambient span should start a new trace"); - Assert.AreEqual("send message", sentMessage.DisplayName); + Assert.Multiple(() => + { + Assert.That(sentMessage.ParentId, Is.Null, "sends without ambient span should start a new trace"); + Assert.That(sentMessage.DisplayName, Is.EqualTo("send message")); + }); var sentMessageTags = sentMessage.Tags.ToImmutableDictionary(); sentMessageTags.VerifyTag("nservicebus.message_id", context.SentMessageId); @@ -54,16 +57,22 @@ public async Task Should_create_new_child_on_receive_by_default() var sendMessageActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); var receiveMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); - Assert.AreEqual(1, sendMessageActivities.Count, "1 message is sent as part of this test"); - Assert.AreEqual(1, receiveMessageActivities.Count, "1 message is received as part of this test"); + Assert.Multiple(() => + { + Assert.That(sendMessageActivities, Has.Count.EqualTo(1), "1 message is sent as part of this test"); + Assert.That(receiveMessageActivities, Has.Count.EqualTo(1), "1 message is received as part of this test"); + }); var sendRequest = sendMessageActivities[0]; var receiveRequest = receiveMessageActivities[0]; - Assert.AreEqual(sendRequest.RootId, receiveRequest.RootId, "send and receive operations are part of the same root activity"); - Assert.IsNotNull(receiveRequest.ParentId, "incoming message does have a parent"); + Assert.Multiple(() => + { + Assert.That(receiveRequest.RootId, Is.EqualTo(sendRequest.RootId), "send and receive operations are part of the same root activity"); + Assert.That(receiveRequest.ParentId, Is.Not.Null, "incoming message does have a parent"); + }); - CollectionAssert.IsEmpty(receiveRequest.Links, "receive does not have links"); + Assert.That(receiveRequest.Links, Is.Empty, "receive does not have links"); } [Test] @@ -83,18 +92,24 @@ public async Task Should_create_new_linked_trace_on_receive_when_requested_via_o var sendMessageActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); var receiveMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); - Assert.AreEqual(1, sendMessageActivities.Count, "1 message is sent as part of this test"); - Assert.AreEqual(1, receiveMessageActivities.Count, "1 message is received as part of this test"); + Assert.Multiple(() => + { + Assert.That(sendMessageActivities, Has.Count.EqualTo(1), "1 message is sent as part of this test"); + Assert.That(receiveMessageActivities, Has.Count.EqualTo(1), "1 message is received as part of this test"); + }); var sendRequest = sendMessageActivities[0]; var receiveRequest = receiveMessageActivities[0]; - Assert.AreNotEqual(sendRequest.RootId, receiveRequest.RootId, "send and receive operations are part of different root activities"); - Assert.IsNull(receiveRequest.ParentId, "incoming message does not have a parent, it's a root"); + Assert.Multiple(() => + { + Assert.That(receiveRequest.RootId, Is.Not.EqualTo(sendRequest.RootId), "send and receive operations are part of different root activities"); + Assert.That(receiveRequest.ParentId, Is.Null, "incoming message does not have a parent, it's a root"); + }); ActivityLink link = receiveRequest.Links.FirstOrDefault(); - Assert.IsNotNull(link, "Receive has a link"); - Assert.AreEqual(sendRequest.TraceId, link.Context.TraceId, "receive is linked to send operation"); + Assert.That(link, Is.Not.EqualTo(default(ActivityLink)), "Receive has a link"); + Assert.That(link.Context.TraceId, Is.EqualTo(sendRequest.TraceId), "receive is linked to send operation"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_messages_from_pipeline.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_messages_from_pipeline.cs index 0fee98c8c34..743d3480c0d 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_messages_from_pipeline.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_messages_from_pipeline.cs @@ -20,11 +20,11 @@ public async Task Should_add_batch_dispatch_events() var outgoingMessageActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(); var sentMessage = outgoingMessageActivities.First(); - Assert.IsNotEmpty(sentMessage.Events); + Assert.That(sentMessage.Events, Is.Not.Empty); var startDispatchingEvents = sentMessage.Events.Where(e => e.Name == "Start dispatching").ToArray(); - Assert.AreEqual(1, startDispatchingEvents.Length, "should raise dispatch start event"); - Assert.AreEqual(1, startDispatchingEvents.Single().Tags.ToImmutableDictionary()["message-count"]); - Assert.AreEqual(1, sentMessage.Events.Count(e => e.Name == "Finished dispatching"), "should raise dispatch completed event"); + Assert.That(startDispatchingEvents.Length, Is.EqualTo(1), "should raise dispatch start event"); + Assert.That(startDispatchingEvents.Single().Tags.ToImmutableDictionary()["message-count"], Is.EqualTo(1)); + Assert.That(sentMessage.Events.Count(e => e.Name == "Finished dispatching"), Is.EqualTo(1), "should raise dispatch completed event"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_replies.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_replies.cs index fd53c0b2381..9c4e114a3e6 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_replies.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_sending_replies.cs @@ -16,12 +16,15 @@ public async Task Should_create_outgoing_message_span() .Run(); var outgoingMessageActivities = NServicebusActivityListener.CompletedActivities.GetSendMessageActivities(); - Assert.AreEqual(2, outgoingMessageActivities.Count, "2 messages are being sent"); + Assert.That(outgoingMessageActivities, Has.Count.EqualTo(2), "2 messages are being sent"); var replyMessage = outgoingMessageActivities[1]; - Assert.AreEqual("reply", replyMessage.DisplayName); - Assert.AreEqual(outgoingMessageActivities[0].RootId, replyMessage.RootId, "reply should belong to same trace as the triggering message"); - Assert.IsNotNull(replyMessage.ParentId, "reply should have ambient span"); + Assert.Multiple(() => + { + Assert.That(replyMessage.DisplayName, Is.EqualTo("reply")); + Assert.That(replyMessage.RootId, Is.EqualTo(outgoingMessageActivities[0].RootId), "reply should belong to same trace as the triggering message"); + Assert.That(replyMessage.ParentId, Is.Not.Null, "reply should have ambient span"); + }); replyMessage.VerifyUniqueTags(); } diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_subscribing.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_subscribing.cs index 9b1772f2676..85a426deb73 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_subscribing.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_subscribing.cs @@ -24,17 +24,17 @@ public async Task Should_create_subscription_span_when_mdps() var subscribeActivities = NServicebusActivityListener.CompletedActivities.Where(a => a.OperationName == "NServiceBus.Diagnostics.Subscribe") .ToArray(); - Assert.AreEqual(1, subscribeActivities.Length, "the subscriber should subscribe to the event"); + Assert.That(subscribeActivities.Length, Is.EqualTo(1), "the subscriber should subscribe to the event"); var subscribeActivity = subscribeActivities.Single(); subscribeActivity.VerifyUniqueTags(); - Assert.AreEqual("subscribe event", subscribeActivity.DisplayName); + Assert.That(subscribeActivity.DisplayName, Is.EqualTo("subscribe event")); var subscribeActivityTags = subscribeActivity.Tags.ToImmutableDictionary(); subscribeActivityTags.VerifyTag("nservicebus.event_types", typeof(DemoEvent).FullName); var receiveActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(includeControlMessages: true).ToArray(); - Assert.AreEqual(1, receiveActivities.Length, "the subscription message should be received by the publisher"); - Assert.AreEqual(subscribeActivities[0].Id, receiveActivities[0].ParentId, "the received subscription message should connect to the subscribe operation"); + Assert.That(receiveActivities.Length, Is.EqualTo(1), "the subscription message should be received by the publisher"); + Assert.That(receiveActivities[0].ParentId, Is.EqualTo(subscribeActivities[0].Id), "the received subscription message should connect to the subscribe operation"); } [Test] @@ -52,16 +52,16 @@ public async Task Should_create_subscription_span_when_native_pubsub() var subscribeActivities = NServicebusActivityListener.CompletedActivities.Where(a => a.OperationName == "NServiceBus.Diagnostics.Subscribe") .ToArray(); - Assert.AreEqual(1, subscribeActivities.Length, "the subscriber should subscribe to the event"); + Assert.That(subscribeActivities.Length, Is.EqualTo(1), "the subscriber should subscribe to the event"); var subscribeActivity = subscribeActivities.Single(); subscribeActivity.VerifyUniqueTags(); - Assert.AreEqual("subscribe event", subscribeActivity.DisplayName); + Assert.That(subscribeActivity.DisplayName, Is.EqualTo("subscribe event")); var subscribeActivityTags = subscribeActivity.Tags.ToImmutableDictionary(); subscribeActivityTags.VerifyTag("nservicebus.event_types", typeof(DemoEvent).FullName); var subscriptionReceiveActivity = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(includeControlMessages: true); - Assert.IsEmpty(subscriptionReceiveActivity, "native pubsub should not produce a message"); + Assert.That(subscriptionReceiveActivity, Is.Empty, "native pubsub should not produce a message"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_unsubscribing.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_unsubscribing.cs index 5e4734155f1..2529a91bc9b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_unsubscribing.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/Traces/When_unsubscribing.cs @@ -23,18 +23,18 @@ public async Task Should_create_unsubscribe_span_when_mdps() var unsubscribeActivities = NServicebusActivityListener.CompletedActivities.Where(a => a.OperationName == "NServiceBus.Diagnostics.Unsubscribe") .ToArray(); - Assert.AreEqual(1, unsubscribeActivities.Length, "the subscriber should unsubscribe to the event"); + Assert.That(unsubscribeActivities.Length, Is.EqualTo(1), "the subscriber should unsubscribe to the event"); var unsubscribeActivity = unsubscribeActivities.Single(); unsubscribeActivity.VerifyUniqueTags(); - Assert.AreEqual("unsubscribe event", unsubscribeActivity.DisplayName); + Assert.That(unsubscribeActivity.DisplayName, Is.EqualTo("unsubscribe event")); var unsubscribeActivityTags = unsubscribeActivity.Tags.ToImmutableDictionary(); unsubscribeActivityTags.VerifyTag("nservicebus.event_types", typeof(DemoEvent).FullName); var receiveActivities = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(includeControlMessages: true).ToArray(); - Assert.AreEqual(1, receiveActivities.Length, "the unsubscribe message should be received by the publisher"); - Assert.AreEqual(unsubscribeActivities[0].Id, receiveActivities[0].ParentId, "the received unsubscribe message should connect to the subscribe operation"); + Assert.That(receiveActivities.Length, Is.EqualTo(1), "the unsubscribe message should be received by the publisher"); + Assert.That(receiveActivities[0].ParentId, Is.EqualTo(unsubscribeActivities[0].Id), "the received unsubscribe message should connect to the subscribe operation"); } [Test] @@ -50,17 +50,17 @@ public async Task Should_create_unsubscribe_span_when_native_pubsub() .Run(); var unsubscribeActivities = NServicebusActivityListener.CompletedActivities.Where(a => a.OperationName == "NServiceBus.Diagnostics.Unsubscribe").ToArray(); - Assert.AreEqual(1, unsubscribeActivities.Length, "the subscriber should unsubscribe to the event"); + Assert.That(unsubscribeActivities.Length, Is.EqualTo(1), "the subscriber should unsubscribe to the event"); var unsubscribeActivity = unsubscribeActivities.Single(); unsubscribeActivity.VerifyUniqueTags(); - Assert.AreEqual("unsubscribe event", unsubscribeActivity.DisplayName); + Assert.That(unsubscribeActivity.DisplayName, Is.EqualTo("unsubscribe event")); var unsubscribeActivityTags = unsubscribeActivity.Tags.ToImmutableDictionary(); unsubscribeActivityTags.VerifyTag("nservicebus.event_types", typeof(DemoEvent).FullName); var subscriptionReceiveActivity = NServicebusActivityListener.CompletedActivities.GetReceiveMessageActivities(includeControlMessages: true); - Assert.IsEmpty(subscriptionReceiveActivity, "native pubsub should not produce a message"); + Assert.That(subscriptionReceiveActivity, Is.Empty, "native pubsub should not produce a message"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/When_incoming_message_handled.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/When_incoming_message_handled.cs index a6ed79faec3..e9b43ef3de2 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/When_incoming_message_handled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/When_incoming_message_handled.cs @@ -28,9 +28,9 @@ public async Task Should_record_success_handling_time() metricsListener.AssertMetric(HandlerTimeMetricName, 5); AssertMandatoryTags(metricsListener, HandlerTimeMetricName, typeof(MyMessage)); var handlerType = metricsListener.AssertTagKeyExists(HandlerTimeMetricName, "nservicebus.message_handler_type"); - Assert.AreEqual(typeof(MyMessageHandler).FullName, handlerType); + Assert.That(handlerType, Is.EqualTo(typeof(MyMessageHandler).FullName)); var result = metricsListener.AssertTagKeyExists(HandlerTimeMetricName, "execution.result"); - Assert.AreEqual("success", result); + Assert.That(result, Is.EqualTo("success")); } [Test] @@ -40,11 +40,11 @@ public async Task Should_record_failure_handling_time() metricsListener.AssertMetric(HandlerTimeMetricName, 5); AssertMandatoryTags(metricsListener, HandlerTimeMetricName, typeof(MyExceptionalMessage)); var handlerType = metricsListener.AssertTagKeyExists(HandlerTimeMetricName, "nservicebus.message_handler_type"); - Assert.AreEqual(typeof(MyExceptionalHandler).FullName, handlerType); + Assert.That(handlerType, Is.EqualTo(typeof(MyExceptionalHandler).FullName)); var error = metricsListener.AssertTagKeyExists(HandlerTimeMetricName, "error.type"); - Assert.AreEqual(typeof(Exception).FullName, error); + Assert.That(error, Is.EqualTo(typeof(Exception).FullName)); var result = metricsListener.AssertTagKeyExists(HandlerTimeMetricName, "execution.result"); - Assert.AreEqual("failure", result); + Assert.That(result, Is.EqualTo("failure")); } [Test] @@ -97,11 +97,11 @@ static void AssertMandatoryTags( Type expectedMessageType) { var messageType = metricsListener.AssertTagKeyExists(metricName, "nservicebus.message_type"); - Assert.AreEqual(expectedMessageType.FullName, messageType); + Assert.That(messageType, Is.EqualTo(expectedMessageType.FullName)); var endpoint = metricsListener.AssertTagKeyExists(metricName, "nservicebus.queue"); - Assert.AreEqual(Conventions.EndpointNamingConvention(typeof(EndpointWithMetrics)), endpoint); + Assert.That(endpoint, Is.EqualTo(Conventions.EndpointNamingConvention(typeof(EndpointWithMetrics)))); var discriminator = metricsListener.AssertTagKeyExists(metricName, "nservicebus.discriminator"); - Assert.AreEqual("discriminator", discriminator); + Assert.That(discriminator, Is.EqualTo("discriminator")); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/When_incoming_message_handled_successfully.cs b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/When_incoming_message_handled_successfully.cs index cd5fd6e9e1f..e8beb4e0afe 100644 --- a/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/When_incoming_message_handled_successfully.cs +++ b/src/NServiceBus.AcceptanceTests/Core/OpenTelemetry/When_incoming_message_handled_successfully.cs @@ -30,11 +30,11 @@ public async Task Should_record_handling_time() string handlingTime = "nservicebus.messaging.handler_time"; metricsListener.AssertMetric(handlingTime, 5); var messageType = metricsListener.AssertTagKeyExists(handlingTime, "nservicebus.message_type"); - Assert.AreEqual(typeof(MyMessage).FullName, messageType); + Assert.That(messageType, Is.EqualTo(typeof(MyMessage).FullName)); var handlerType = metricsListener.AssertTagKeyExists(handlingTime, "nservicebus.message_handler_type"); - Assert.AreEqual(typeof(MyMessageHandler).FullName, handlerType); + Assert.That(handlerType, Is.EqualTo(typeof(MyMessageHandler).FullName)); var endpoint = metricsListener.AssertTagKeyExists(handlingTime, "nservicebus.queue"); - Assert.AreEqual(Conventions.EndpointNamingConvention(typeof(EndpointWithMetrics)), endpoint); + Assert.That(endpoint, Is.EqualTo(Conventions.EndpointNamingConvention(typeof(EndpointWithMetrics)))); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_for_send_only.cs b/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_for_send_only.cs index 4469a79a36e..0775aa5fe53 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_for_send_only.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_for_send_only.cs @@ -16,7 +16,7 @@ public async Task Should_fail_prerequisites_check() .Done(c => c.EndpointsStarted) .Run(); - StringAssert.Contains("Outbox is only relevant for endpoints receiving messages.", startupDiagnostics); + Assert.That(startupDiagnostics, Does.Contain("Outbox is only relevant for endpoints receiving messages.")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_with_transaction_mode_above_receive_only.cs b/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_with_transaction_mode_above_receive_only.cs index 04739a5c9a3..dbb44190ea6 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_with_transaction_mode_above_receive_only.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_with_transaction_mode_above_receive_only.cs @@ -15,7 +15,7 @@ public void Should_fail_to_start() .Done(_ => false) .Run()); - StringAssert.Contains($"Outbox requires transport to be running in `{nameof(TransportTransactionMode.ReceiveOnly)}` mode", exception.Message); + Assert.That(exception.Message, Does.Contain($"Outbox requires transport to be running in `{nameof(TransportTransactionMode.ReceiveOnly)}` mode")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_with_transactions_off.cs b/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_with_transactions_off.cs index 042b1c22ec3..3154e900b65 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_with_transactions_off.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_with_transactions_off.cs @@ -27,8 +27,11 @@ public async Task Should_fail_prerequisites_check() var satisfied = outboxFeature["PrerequisiteStatus"]["IsSatisfied"].GetValue(); var reason = (outboxFeature["PrerequisiteStatus"]["Reasons"] as JsonArray).Single().GetValue(); - Assert.IsFalse(satisfied); - Assert.AreEqual("Outbox isn't needed since the receive transactions have been turned off", reason); + Assert.Multiple(() => + { + Assert.That(satisfied, Is.False); + Assert.That(reason, Is.EqualTo("Outbox isn't needed since the receive transactions have been turned off")); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_without_persister_supporting_it.cs b/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_without_persister_supporting_it.cs index 2d8635b1dd5..a8dadf92f58 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_without_persister_supporting_it.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Outbox/When_outbox_enabled_without_persister_supporting_it.cs @@ -16,7 +16,7 @@ public void Should_fail_to_start() .Done(_ => false) .Run()); - StringAssert.Contains("The selected persistence doesn't have support for outbox storage", exception.Message); + Assert.That(exception.Message, Does.Contain("The selected persistence doesn't have support for outbox storage")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Persistence/When_a_persistence_provides_synchronized_session.cs b/src/NServiceBus.AcceptanceTests/Core/Persistence/When_a_persistence_provides_synchronized_session.cs index 4f645185c1f..34c2099c833 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Persistence/When_a_persistence_provides_synchronized_session.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Persistence/When_a_persistence_provides_synchronized_session.cs @@ -16,9 +16,12 @@ public async Task Synchronized_session_should_be_of_exact_type_provided_by_persi .Done(c => c.MessageReceived) .Run(); - Assert.IsNotNull(result.SynchronizedStorageSessionInstanceInContainer); - Assert.IsNotNull(result.SynchronizedStorageSessionInstanceInHandlingContext); - Assert.AreSame(result.SynchronizedStorageSessionInstanceInContainer, result.SynchronizedStorageSessionInstanceInHandlingContext); + Assert.Multiple(() => + { + Assert.That(result.SynchronizedStorageSessionInstanceInContainer, Is.Not.Null); + Assert.That(result.SynchronizedStorageSessionInstanceInHandlingContext, Is.Not.Null); + }); + Assert.That(result.SynchronizedStorageSessionInstanceInHandlingContext, Is.SameAs(result.SynchronizedStorageSessionInstanceInContainer)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_aborting_the_behavior_chain.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_aborting_the_behavior_chain.cs index 798c50ed79e..08eb6b18bbd 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_aborting_the_behavior_chain.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_aborting_the_behavior_chain.cs @@ -15,8 +15,11 @@ public async Task Subsequent_handlers_will_not_be_invoked() .Done(c => c.FirstHandlerInvoked) .Run(); - Assert.That(context.FirstHandlerInvoked, Is.True); - Assert.That(context.SecondHandlerInvoked, Is.False); + Assert.Multiple(() => + { + Assert.That(context.FirstHandlerInvoked, Is.True); + Assert.That(context.SecondHandlerInvoked, Is.False); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_discontinuing_message_dispatch.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_discontinuing_message_dispatch.cs index 290db127af9..d3a4bb66719 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_discontinuing_message_dispatch.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_discontinuing_message_dispatch.cs @@ -19,8 +19,11 @@ public async Task Should_not_continue_to_dispatch_the_message() .Done(c => c.InterceptingHandlerCalled) .Run(); - Assert.True(context.InterceptingHandlerCalled, "The intercepting handler should be called"); - Assert.False(context.SagaStarted, "The saga should not have been started since the intercepting handler stops the pipeline"); + Assert.Multiple(() => + { + Assert.That(context.InterceptingHandlerCalled, Is.True, "The intercepting handler should be called"); + Assert.That(context.SagaStarted, Is.False, "The saga should not have been started since the intercepting handler stops the pipeline"); + }); } public class SagaEndpointContext : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_behavior_context.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_behavior_context.cs index 1d8962e22aa..bb05abb326b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_behavior_context.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_behavior_context.cs @@ -20,8 +20,11 @@ public async Task Should_be_available_in_handler_context() .Done(c => c.HandlerAExtensionValue != null && c.HandlerBExtensionValue != null) .Run(); - Assert.AreEqual(ExtensionValue, context.HandlerAExtensionValue); - Assert.AreEqual(ExtensionValue, context.HandlerBExtensionValue); + Assert.Multiple(() => + { + Assert.That(context.HandlerAExtensionValue, Is.EqualTo(ExtensionValue)); + Assert.That(context.HandlerBExtensionValue, Is.EqualTo(ExtensionValue)); + }); } static string ExtensionValue; diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_sendoptions.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_sendoptions.cs index 41f09f4b4c5..13b8fd46395 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_sendoptions.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_sendoptions.cs @@ -29,7 +29,7 @@ public async Task Should_be_able_to_set_context_items_and_retrieve_it_via_a_beha .Done(c => c.WasCalled) .Run(); - Assert.AreEqual("I did it", context.Secret); + Assert.That(context.Secret, Is.EqualTo("I did it")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_the_publish_api.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_the_publish_api.cs index 342605a0975..a66098438f1 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_the_publish_api.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_extending_the_publish_api.cs @@ -40,7 +40,7 @@ public async Task Should_make_the_context_available_to_behaviors() .Done(c => c.Subscriber1GotTheEvent) .Run(); - Assert.True(context.Subscriber1GotTheEvent); + Assert.That(context.Subscriber1GotTheEvent, Is.True); } public class Context : ScenarioContext @@ -67,7 +67,7 @@ public Task Invoke(IOutgoingLogicalMessageContext context, Func c.FirstHandlerWasCalled) .Run(); - Assert.True(context.FirstHandlerWasCalled); - Assert.True(context.SecondHandlerWasCalled); + Assert.Multiple(() => + { + Assert.That(context.FirstHandlerWasCalled, Is.True); + Assert.That(context.SecondHandlerWasCalled, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_overwriting_conversation_id.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_overwriting_conversation_id.cs index 6a482588a2a..e314eaba923 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_overwriting_conversation_id.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_overwriting_conversation_id.cs @@ -26,8 +26,8 @@ public void Should_throw_when_incoming_conversation_id_available() .Done(c => c.ReceivedMessage) .Run()); - StringAssert.Contains($"Cannot set the {Headers.ConversationId} header to 'intermediate message header' as it cannot override the incoming header value ('{initialConversationId}').", exception.InnerException.Message); - Assert.IsFalse(((Context)exception.ScenarioContext).SentOutgoingMessage, "because send should fail"); + Assert.That(exception.InnerException.Message, Does.Contain($"Cannot set the {Headers.ConversationId} header to 'intermediate message header' as it cannot override the incoming header value ('{initialConversationId}').")); + Assert.That(((Context)exception.ScenarioContext).SentOutgoingMessage, Is.False, "because send should fail"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_providing_custom_handler_registry.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_providing_custom_handler_registry.cs index f2430dd5ba1..317f8644bc2 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_providing_custom_handler_registry.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_providing_custom_handler_registry.cs @@ -26,10 +26,13 @@ public async Task Should_invoke_manually_registered_handlers() && c.ManuallyRegisteredEventHandlerInvoked) .Run(TimeSpan.FromSeconds(10)); - Assert.IsTrue(context.RegularCommandHandlerInvoked); - Assert.IsTrue(context.ManuallyRegisteredCommandHandlerInvoked); - Assert.IsTrue(context.RegularEventHandlerInvoked); - Assert.IsTrue(context.ManuallyRegisteredEventHandlerInvoked); + Assert.Multiple(() => + { + Assert.That(context.RegularCommandHandlerInvoked, Is.True); + Assert.That(context.ManuallyRegisteredCommandHandlerInvoked, Is.True); + Assert.That(context.RegularEventHandlerInvoked, Is.True); + Assert.That(context.ManuallyRegisteredEventHandlerInvoked, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_receiving_with_catch_all_handlers_registered.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_receiving_with_catch_all_handlers_registered.cs index dc835c43966..a52d000f4af 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_receiving_with_catch_all_handlers_registered.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_receiving_with_catch_all_handlers_registered.cs @@ -19,9 +19,12 @@ public async Task Should_call_catch_all_handlers() .Done(c => c.ObjectHandlerWasCalled && c.DynamicHandlerWasCalled && c.IMessageHandlerWasCalled) .Run(); - Assert.True(context.ObjectHandlerWasCalled); - Assert.True(context.DynamicHandlerWasCalled); - Assert.True(context.IMessageHandlerWasCalled); + Assert.Multiple(() => + { + Assert.That(context.ObjectHandlerWasCalled, Is.True); + Assert.That(context.DynamicHandlerWasCalled, Is.True); + Assert.That(context.IMessageHandlerWasCalled, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_registering_handlers_explicitly.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_registering_handlers_explicitly.cs index 0fbd8d9253a..cb7f24ed585 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_registering_handlers_explicitly.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_registering_handlers_explicitly.cs @@ -17,7 +17,7 @@ public async Task Should_enable_properties_to_be_set() .Done(c => c.WasCalled) .Run(); - Assert.AreEqual(simpleValue, context.PropertyValue); + Assert.That(context.PropertyValue, Is.EqualTo(simpleValue)); } static string simpleValue = "SomeValue"; diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_replacing_behavior.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_replacing_behavior.cs index 09b3157c208..4b99e48178c 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_replacing_behavior.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_replacing_behavior.cs @@ -18,8 +18,11 @@ public async Task Should_invoke_replacement_in_pipeline() .Done(c => c.MessageHandled) .Run(); - Assert.IsFalse(context.OriginalBehaviorInvoked); - Assert.IsTrue(context.ReplacementBehaviorInvoked); + Assert.Multiple(() => + { + Assert.That(context.OriginalBehaviorInvoked, Is.False); + Assert.That(context.ReplacementBehaviorInvoked, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_reusing_sendoptions.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_reusing_sendoptions.cs index 083521816be..1b44817712c 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_reusing_sendoptions.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_reusing_sendoptions.cs @@ -25,8 +25,8 @@ public async Task Should_generate_new_message_id_for_every_message() .Done(c => c.ReceivedMessageIds.Count >= 3) .Run(); - Assert.AreEqual(3, context.ReceivedMessageIds.Count); - Assert.AreEqual(3, context.ReceivedMessageIds.Distinct().Count(), "the message ids should be distinct"); + Assert.That(context.ReceivedMessageIds, Has.Count.EqualTo(3)); + Assert.That(context.ReceivedMessageIds.Distinct().Count(), Is.EqualTo(3), "the message ids should be distinct"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_sending_from_a_send_only.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_sending_from_a_send_only.cs index 134684e5571..31a5c12b917 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_sending_from_a_send_only.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_sending_from_a_send_only.cs @@ -21,7 +21,7 @@ public async Task Should_send_the_message() .Done(c => c.WasCalled) .Run(); - Assert.True(context.WasCalled, "The message handler should be called"); + Assert.That(context.WasCalled, Is.True, "The message handler should be called"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_setting_handler_execution_order.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_setting_handler_execution_order.cs index 74e2fa479b8..41f7a88cff6 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_setting_handler_execution_order.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_setting_handler_execution_order.cs @@ -19,7 +19,7 @@ public async Task Should_call_designated_handler_first() .Done(c => c.InterceptingHandlerCalled && c.SagaStarted) .Run(); - Assert.True(context.InterceptingHandlerCalledFirst, "The intercepting message handler should be called first"); + Assert.That(context.InterceptingHandlerCalledFirst, Is.True, "The intercepting message handler should be called first"); } public class SagaEndpointContext : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_setting_ttbr_in_outer_publish.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_setting_ttbr_in_outer_publish.cs index cc83c7e8404..9b4dfb545b1 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_setting_ttbr_in_outer_publish.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_setting_ttbr_in_outer_publish.cs @@ -23,8 +23,11 @@ public async Task Should_not_apply_ttbr_to_inner_publish() .Done(c => c.OuterEventReceived && c.InnerEventReceived) .Run(); - Assert.IsNotNull(context.OuterEventTtbr, "Outer event should have TTBR settings applied"); - Assert.IsNull(context.InnerEventTtbr, "Inner event should not have TTBR settings applied"); + Assert.Multiple(() => + { + Assert.That(context.OuterEventTtbr, Is.Not.Null, "Outer event should have TTBR settings applied"); + Assert.That(context.InnerEventTtbr, Is.Null, "Inner event should not have TTBR settings applied"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_skipping_serialization_with_nested_send.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_skipping_serialization_with_nested_send.cs index e104d9886ae..49d9a39c0fa 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_skipping_serialization_with_nested_send.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_skipping_serialization_with_nested_send.cs @@ -20,9 +20,12 @@ public async Task Should_not_skip_serialization_for_nested_send() .Done(c => c.NestedMessageReceived) .Run(TimeSpan.FromSeconds(15)); - Assert.IsTrue(context.NestedMessageReceived, "the serialization should the nested message should not be skipped"); - Assert.AreEqual("Some property value for NestedMessage", context.NestedMessagePropertyValue, "the message sould be correctly serialized"); - Assert.IsFalse(context.MessageWithSkippedSerializationReceived, "NServiceBus should discard messages without a body"); + Assert.Multiple(() => + { + Assert.That(context.NestedMessageReceived, Is.True, "the serialization should the nested message should not be skipped"); + Assert.That(context.NestedMessagePropertyValue, Is.EqualTo("Some property value for NestedMessage"), "the message sould be correctly serialized"); + Assert.That(context.MessageWithSkippedSerializationReceived, Is.False, "NServiceBus should discard messages without a body"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_subscribed_to_ReceivePipelineCompleted.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_subscribed_to_ReceivePipelineCompleted.cs index 265b5323743..9395b62af81 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_subscribed_to_ReceivePipelineCompleted.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_subscribed_to_ReceivePipelineCompleted.cs @@ -17,10 +17,13 @@ public async Task Should_receive_notifications() .Done(c => c.NotificationEventFired) .Run(); - Assert.True(context.NotificationEventFired, "ReceivePipelineCompleted was not raised"); - Assert.AreEqual(context.MessageId, context.ReceivePipelineCompletedMessage.ProcessedMessage.MessageId, "MessageId mismatch"); - Assert.AreNotEqual(DateTime.MinValue, context.ReceivePipelineCompletedMessage.StartedAt, "StartedAt was not set"); - Assert.AreNotEqual(DateTime.MinValue, context.ReceivePipelineCompletedMessage.CompletedAt, "CompletedAt was not set"); + Assert.Multiple(() => + { + Assert.That(context.NotificationEventFired, Is.True, "ReceivePipelineCompleted was not raised"); + Assert.That(context.ReceivePipelineCompletedMessage.ProcessedMessage.MessageId, Is.EqualTo(context.MessageId), "MessageId mismatch"); + Assert.That(context.ReceivePipelineCompletedMessage.StartedAt, Is.Not.EqualTo(DateTimeOffset.MinValue), "StartedAt was not set"); + Assert.That(context.ReceivePipelineCompletedMessage.CompletedAt, Is.Not.EqualTo(DateTimeOffset.MinValue), "CompletedAt was not set"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_transport_transaction_provided.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_transport_transaction_provided.cs index 43623381c0e..a60bbc19f1a 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_transport_transaction_provided.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_transport_transaction_provided.cs @@ -20,7 +20,7 @@ public async Task Should_be_available_during_dispatch() .Done(c => c.AnotherMessageReceived) .Run(); - Assert.AreSame(context.IncomingPipelineTransportTransaction, context.DispatchPipelineTransportTransaction, "Transport Transaction was not the same"); + Assert.That(context.DispatchPipelineTransportTransaction, Is.SameAs(context.IncomingPipelineTransportTransaction), "Transport Transaction was not the same"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_custom_conversation_id.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_custom_conversation_id.cs index 4b0837fbdba..7f8bc13d2b8 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_custom_conversation_id.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_custom_conversation_id.cs @@ -25,7 +25,7 @@ public async Task Should_apply_custom_conversation_id_when_no_incoming_message() .Done(c => !string.IsNullOrEmpty(c.ReceivedConversationId)) .Run(); - Assert.AreEqual(customConversationId, context.ReceivedConversationId); + Assert.That(context.ReceivedConversationId, Is.EqualTo(customConversationId)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_per_uow_component_in_the_pipeline.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_per_uow_component_in_the_pipeline.cs index bca9713531b..6c66eb3591b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_per_uow_component_in_the_pipeline.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_per_uow_component_in_the_pipeline.cs @@ -24,8 +24,11 @@ public async Task It_should_be_scoped_to_uow_both_in_behavior_and_in_the_handler .Done(c => c.MessagesProcessed >= 2) .Run(); - Assert.IsFalse(context.ValueEmpty, "Empty value in the UoW component meaning the UoW component has been registered as per-call"); - Assert.IsFalse(context.ValueAlreadyInitialized, "Value in the UoW has already been initialized when it was resolved for the first time in a given pipeline meaning the UoW component has been registered as a singleton."); + Assert.Multiple(() => + { + Assert.That(context.ValueEmpty, Is.False, "Empty value in the UoW component meaning the UoW component has been registered as per-call"); + Assert.That(context.ValueAlreadyInitialized, Is.False, "Value in the UoW has already been initialized when it was resolved for the first time in a given pipeline meaning the UoW component has been registered as a singleton."); + }); } static Task SendMessage(IMessageSession s) diff --git a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_polymorphic_message_handlers.cs b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_polymorphic_message_handlers.cs index 37b1d53a0c4..ef0480eefc1 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_polymorphic_message_handlers.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Pipeline/When_using_polymorphic_message_handlers.cs @@ -18,8 +18,11 @@ public async Task Should_invoke_all_compatible_handlers() .Done(c => c.SpecificHandlerInvoked && c.CatchAllHandlerInvoked) .Run(); - Assert.True(context.SpecificHandlerInvoked); - Assert.True(context.CatchAllHandlerInvoked); + Assert.Multiple(() => + { + Assert.That(context.SpecificHandlerInvoked, Is.True); + Assert.That(context.CatchAllHandlerInvoked, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_configuring_subscription_authorizer.cs b/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_configuring_subscription_authorizer.cs index e24c895ce7a..bba302659f7 100644 --- a/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_configuring_subscription_authorizer.cs +++ b/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_configuring_subscription_authorizer.cs @@ -33,8 +33,8 @@ public async Task Should_apply_authorizer_on_subscriptions() .Done(c => c.ReceivedAllowedEventSubscriptionMessage && c.ReceivedForbiddenEventSubscriptionMessage) .Run(); - Assert.AreEqual(1, context.SubscriptionStorage.SubscribedEvents.Count); - Assert.AreEqual(typeof(AllowedEvent).FullName, context.SubscriptionStorage.SubscribedEvents.Single()); + Assert.That(context.SubscriptionStorage.SubscribedEvents, Has.Count.EqualTo(1)); + Assert.That(context.SubscriptionStorage.SubscribedEvents.Single(), Is.EqualTo(typeof(AllowedEvent).FullName)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_disabling_publishing.cs b/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_disabling_publishing.cs index 80e3eccc5d2..249fab79035 100644 --- a/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_disabling_publishing.cs +++ b/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_disabling_publishing.cs @@ -37,7 +37,7 @@ public void Should_throw_when_publishing() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Publishing has been explicitly disabled on this endpoint", exception.Message); + Assert.That(exception.Message, Does.Contain("Publishing has been explicitly disabled on this endpoint")); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_subscribing_on_send_only_endpoint.cs b/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_subscribing_on_send_only_endpoint.cs index 803af016e8f..958d0350073 100644 --- a/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_subscribing_on_send_only_endpoint.cs +++ b/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_subscribing_on_send_only_endpoint.cs @@ -16,7 +16,7 @@ public void Should_throw_InvalidOperationException_on_native_pubsub() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Send-only endpoints cannot subscribe to events", exception.Message); + Assert.That(exception.Message, Does.Contain("Send-only endpoints cannot subscribe to events")); } [Test] @@ -28,7 +28,7 @@ public void Should_throw_InvalidOperationException_on_message_driven_pubsub() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Send-only endpoints cannot subscribe to events", exception.Message); + Assert.That(exception.Message, Does.Contain("Send-only endpoints cannot subscribe to events")); } class NativePubSubSendOnlyEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_unsubscribing_on_send_only_endpoint.cs b/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_unsubscribing_on_send_only_endpoint.cs index 2e425631748..b2c6909b3e0 100644 --- a/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_unsubscribing_on_send_only_endpoint.cs +++ b/src/NServiceBus.AcceptanceTests/Core/PublishSubscribe/When_unsubscribing_on_send_only_endpoint.cs @@ -16,7 +16,7 @@ public void Should_throw_InvalidOperationException_on_native_pubsub() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Send-only endpoints cannot unsubscribe to events", exception.Message); + Assert.That(exception.Message, Does.Contain("Send-only endpoints cannot unsubscribe to events")); } [Test] @@ -28,7 +28,7 @@ public void Should_throw_InvalidOperationException_on_message_driven_pubsub() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Send-only endpoints cannot unsubscribe to events", exception.Message); + Assert.That(exception.Message, Does.Contain("Send-only endpoints cannot unsubscribe to events")); } class NativePubSubSendOnlyEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_applying_message_recoverability.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_applying_message_recoverability.cs index 597496bcb2d..479f1279a4b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_applying_message_recoverability.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_applying_message_recoverability.cs @@ -33,8 +33,11 @@ public async Task Should_allow_for_alternate_move_to_error_action() .Done(c => c.MessageMovedToErrorQueue) .Run(); - Assert.True(context.MessageBodyWasEmpty); - Assert.True(onMessageSentToErrorQueueTriggered); + Assert.Multiple(() => + { + Assert.That(context.MessageBodyWasEmpty, Is.True); + Assert.That(onMessageSentToErrorQueueTriggered, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_configuring_unrecoverable_exception.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_configuring_unrecoverable_exception.cs index 7fc6f4a1ec1..cb48d8160b3 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_configuring_unrecoverable_exception.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_configuring_unrecoverable_exception.cs @@ -30,9 +30,12 @@ await Scenario.Define(ctx => context = ctx) .Run(); }); - Assert.That(exception.FailedMessage.Exception, Is.TypeOf()); - Assert.That(exception.ScenarioContext.FailedMessages, Has.Count.EqualTo(1)); - Assert.AreEqual(1, context.HandlerInvoked); + Assert.Multiple(() => + { + Assert.That(exception.FailedMessage.Exception, Is.TypeOf()); + Assert.That(exception.ScenarioContext.FailedMessages, Has.Count.EqualTo(1)); + Assert.That(context.HandlerInvoked, Is.EqualTo(1)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_custom_policy_executed.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_custom_policy_executed.cs index 9d7a6f6b024..bdb5c7b5af7 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_custom_policy_executed.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_custom_policy_executed.cs @@ -23,13 +23,16 @@ public async Task Should_provide_error_context_to_policy() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.That(context.ErrorContexts.Count, Is.EqualTo(2), "because the custom policy should have been invoked twice"); - Assert.That(context.ErrorContexts[0].Message, Is.Not.Null); - Assert.That(context.ErrorContexts[0].Exception, Is.TypeOf()); - Assert.That(context.ErrorContexts[0].DelayedDeliveriesPerformed, Is.EqualTo(0)); - Assert.That(context.ErrorContexts[1].Message, Is.Not.Null); - Assert.That(context.ErrorContexts[1].Exception, Is.TypeOf()); - Assert.That(context.ErrorContexts[1].DelayedDeliveriesPerformed, Is.EqualTo(1)); + Assert.That(context.ErrorContexts, Has.Count.EqualTo(2), "because the custom policy should have been invoked twice"); + Assert.Multiple(() => + { + Assert.That(context.ErrorContexts[0].Message, Is.Not.Null); + Assert.That(context.ErrorContexts[0].Exception, Is.TypeOf()); + Assert.That(context.ErrorContexts[0].DelayedDeliveriesPerformed, Is.EqualTo(0)); + Assert.That(context.ErrorContexts[1].Message, Is.Not.Null); + Assert.That(context.ErrorContexts[1].Exception, Is.TypeOf()); + Assert.That(context.ErrorContexts[1].DelayedDeliveriesPerformed, Is.EqualTo(1)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_custom_policy_provided.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_custom_policy_provided.cs index a26575ddd74..921070cddd1 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_custom_policy_provided.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_custom_policy_provided.cs @@ -21,9 +21,12 @@ public async Task Should_pass_recoverability_configuration() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.That(context.Configuration.Immediate.MaxNumberOfRetries, Is.EqualTo(MaxImmediateRetries)); - Assert.That(context.Configuration.Delayed.MaxNumberOfRetries, Is.EqualTo(MaxDelayedRetries)); - Assert.That(context.Configuration.Delayed.TimeIncrease, Is.EqualTo(DelayedRetryDelayIncrease)); + Assert.Multiple(() => + { + Assert.That(context.Configuration.Immediate.MaxNumberOfRetries, Is.EqualTo(MaxImmediateRetries)); + Assert.That(context.Configuration.Delayed.MaxNumberOfRetries, Is.EqualTo(MaxDelayedRetries)); + Assert.That(context.Configuration.Delayed.TimeIncrease, Is.EqualTo(DelayedRetryDelayIncrease)); + }); } static TimeSpan DelayedRetryDelayIncrease = TimeSpan.FromMinutes(1); diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_delayed_retries_enabled_with_no_support.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_delayed_retries_enabled_with_no_support.cs index 5e7c26aa94d..3c64b26bfbe 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_delayed_retries_enabled_with_no_support.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_delayed_retries_enabled_with_no_support.cs @@ -20,7 +20,7 @@ public void Should_throw_on_startup() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Delayed retries are not supported when the transport does not support delayed delivery. Disable delayed retries using 'endpointConfiguration.Recoverability().Delayed(settings => settings.NumberOfRetries(0))'.", exception.ToString()); + Assert.That(exception.ToString(), Does.Contain("Delayed retries are not supported when the transport does not support delayed delivery. Disable delayed retries using 'endpointConfiguration.Recoverability().Delayed(settings => settings.NumberOfRetries(0))'.")); } public class StartedEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_delayed_retries_with_regular_exception.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_delayed_retries_with_regular_exception.cs index 0ebeffb7430..c40990c594d 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_delayed_retries_with_regular_exception.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_delayed_retries_with_regular_exception.cs @@ -24,7 +24,7 @@ public async Task Should_preserve_the_original_body_for_regular_exceptions() var delayedRetryBody = context.FailedMessages.Single().Value.Single().Body; - CollectionAssert.AreEqual(context.OriginalBody.ToArray(), delayedRetryBody.ToArray(), "The body of the message sent to Delayed Retry should be the same as the original message coming off the queue"); + Assert.That(delayedRetryBody.ToArray(), Is.EqualTo(context.OriginalBody.ToArray()).AsCollection, "The body of the message sent to Delayed Retry should be the same as the original message coming off the queue"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_failing_mutated_message.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_failing_mutated_message.cs index 3140543f55f..ff4874f05a5 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_failing_mutated_message.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_failing_mutated_message.cs @@ -24,7 +24,7 @@ public async Task Should_preserve_the_original_body() var errorBody = context.FailedMessages.Single().Value.Single().Body; - CollectionAssert.AreEqual(context.OriginalBody, errorBody.ToArray(), "The body of the message sent to delayed retry should be the same as the original message coming off the queue"); + Assert.That(errorBody.ToArray(), Is.EqualTo(context.OriginalBody).AsCollection, "The body of the message sent to delayed retry should be the same as the original message coming off the queue"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_message_is_dispatched_to_error_queue.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_message_is_dispatched_to_error_queue.cs index 5fa716b954e..ef50c9c823c 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_message_is_dispatched_to_error_queue.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_message_is_dispatched_to_error_queue.cs @@ -23,7 +23,7 @@ public async Task Should_allow_body_to_be_manipulated() .Done(c => c.MessageMovedToErrorQueue) .Run(); - Assert.True(context.MessageBodyWasEmpty); + Assert.That(context.MessageBodyWasEmpty, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_message_is_moved_to_error_queue_with_header_customizations.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_message_is_moved_to_error_queue_with_header_customizations.cs index c5853bc5285..c29839bddbc 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_message_is_moved_to_error_queue_with_header_customizations.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_message_is_moved_to_error_queue_with_header_customizations.cs @@ -26,9 +26,12 @@ public async Task Should_apply_header_customizations() .Done(c => c.MessageMovedToErrorQueue) .Run(); - Assert.IsFalse(context.Headers.ContainsKey("NServiceBus.ExceptionInfo.ExceptionType")); - Assert.AreEqual("this is a large message", context.Headers["NServiceBus.ExceptionInfo.Message"]); - Assert.AreEqual("NotInventedHere", context.Headers["NServiceBus.ExceptionInfo.NotInventedHere"]); + Assert.Multiple(() => + { + Assert.That(context.Headers.ContainsKey("NServiceBus.ExceptionInfo.ExceptionType"), Is.False); + Assert.That(context.Headers["NServiceBus.ExceptionInfo.Message"], Is.EqualTo("this is a large message")); + Assert.That(context.Headers["NServiceBus.ExceptionInfo.NotInventedHere"], Is.EqualTo("NotInventedHere")); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_delayed_retries_notifications.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_delayed_retries_notifications.cs index 9ebcc94619c..34ba5c5e995 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_delayed_retries_notifications.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_delayed_retries_notifications.cs @@ -26,11 +26,14 @@ public async Task Should_trigger_notification_on_delayed_retry() .Done(c => c.MessageSentToError) .Run(); - Assert.IsInstanceOf(context.LastDelayedRetryInfo?.Exception); - // Immediate Retries max retries = 3 means we will be processing 4 times. Delayed Retries max retries = 2 means we will do 3 * Immediate Retries - Assert.AreEqual(4 * 3, context.TotalNumberOfHandlerInvocations); - Assert.AreEqual(2, context.NumberOfDelayedRetriesPerformed); - Assert.AreEqual(2, context.LastDelayedRetryInfo.RetryAttempt); + Assert.Multiple(() => + { + Assert.That(context.LastDelayedRetryInfo?.Exception, Is.InstanceOf()); + // Immediate Retries max retries = 3 means we will be processing 4 times. Delayed Retries max retries = 2 means we will do 3 * Immediate Retries + Assert.That(context.TotalNumberOfHandlerInvocations, Is.EqualTo(4 * 3)); + Assert.That(context.NumberOfDelayedRetriesPerformed, Is.EqualTo(2)); + Assert.That(context.LastDelayedRetryInfo.RetryAttempt, Is.EqualTo(2)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_error_notifications.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_error_notifications.cs index 71ac06d999c..fb27e829fde 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_error_notifications.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_error_notifications.cs @@ -27,13 +27,16 @@ public async Task Should_retain_exception_details_over_immediate_and_delayed_ret .Done(c => c.MessageSentToError) .Run(); - Assert.IsInstanceOf(context.MessageSentToErrorException); - Assert.True(context.Logs.Any(l => l.Level == LogLevel.Error && l.Message.Contains("Simulated exception message")), "The last exception should be logged as `error` before sending it to the error queue"); + Assert.Multiple(() => + { + Assert.That(context.MessageSentToErrorException, Is.InstanceOf()); + Assert.That(context.Logs.Any(l => l.Level == LogLevel.Error && l.Message.Contains("Simulated exception message")), Is.True, "The last exception should be logged as `error` before sending it to the error queue"); - // Immediate Retries max retries = 3 means we will be processing 4 times. Delayed Retries max retries = 2 means we will do 3 * Immediate Retries - Assert.AreEqual(4 * 3, context.TotalNumberOfHandlerInvocations); - Assert.AreEqual(3 * 3, context.TotalNumberOfImmediateRetriesEventInvocations); - Assert.AreEqual(2, context.NumberOfDelayedRetriesPerformed); + // Immediate Retries max retries = 3 means we will be processing 4 times. Delayed Retries max retries = 2 means we will do 3 * Immediate Retries + Assert.That(context.TotalNumberOfHandlerInvocations, Is.EqualTo(4 * 3)); + Assert.That(context.TotalNumberOfImmediateRetriesEventInvocations, Is.EqualTo(3 * 3)); + Assert.That(context.NumberOfDelayedRetriesPerformed, Is.EqualTo(2)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_immediate_retries_notifications.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_immediate_retries_notifications.cs index 04d2bd7ffb4..9abc9401bb4 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_immediate_retries_notifications.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_subscribing_to_immediate_retries_notifications.cs @@ -21,11 +21,14 @@ public async Task Should_trigger_notification_on_immediate_retry() .Done(c => c.MessageSentToError) .Run(); - Assert.IsInstanceOf(context.LastImmediateRetryInfo.Exception); - // Immediate Retries max retries = 3 means we will be processing 4 times. Delayed Retries max retries = 2 means we will do 3 * Immediate Retries - Assert.AreEqual(4, context.TotalNumberOfHandlerInvocations); - Assert.AreEqual(3, context.TotalNumberOfImmediateRetriesEventInvocations); - Assert.AreEqual(2, context.LastImmediateRetryInfo.RetryAttempt); + Assert.Multiple(() => + { + Assert.That(context.LastImmediateRetryInfo.Exception, Is.InstanceOf()); + // Immediate Retries max retries = 3 means we will be processing 4 times. Delayed Retries max retries = 2 means we will do 3 * Immediate Retries + Assert.That(context.TotalNumberOfHandlerInvocations, Is.EqualTo(4)); + Assert.That(context.TotalNumberOfImmediateRetriesEventInvocations, Is.EqualTo(3)); + Assert.That(context.LastImmediateRetryInfo.RetryAttempt, Is.EqualTo(2)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transactions_off_and_delayed_retries_enabled.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transactions_off_and_delayed_retries_enabled.cs index 680b77d00f6..7d3b2578882 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transactions_off_and_delayed_retries_enabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transactions_off_and_delayed_retries_enabled.cs @@ -17,7 +17,7 @@ public void Should_throw_on_startup() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Delayed retries are not supported when running with TransportTransactionMode.None. Disable delayed retries using 'endpointConfiguration.Recoverability().Delayed(settings => settings.NumberOfRetries(0))' or select a different TransportTransactionMode.", exception.ToString()); + Assert.That(exception.ToString(), Does.Contain("Delayed retries are not supported when running with TransportTransactionMode.None. Disable delayed retries using 'endpointConfiguration.Recoverability().Delayed(settings => settings.NumberOfRetries(0))' or select a different TransportTransactionMode.")); } public class StartedEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transactions_off_and_immediate_retries_enabled.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transactions_off_and_immediate_retries_enabled.cs index 8ae6772af0f..aefdd5b44ae 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transactions_off_and_immediate_retries_enabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transactions_off_and_immediate_retries_enabled.cs @@ -15,7 +15,7 @@ public void Should_throw_on_startup() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Immediate retries are not supported", exception.ToString()); + Assert.That(exception.ToString(), Does.Contain("Immediate retries are not supported")); } public class StartedEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transport_transaction_provided.cs b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transport_transaction_provided.cs index 91c143da690..6ced1014585 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transport_transaction_provided.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Recoverability/When_transport_transaction_provided.cs @@ -26,7 +26,7 @@ public async Task Should_be_available_in_pipeline() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.AreSame(context.IncomingPipelineTransportTransaction, context.DispatchPipelineTransportTransaction, "Transport Transaction was not the same"); + Assert.That(context.DispatchPipelineTransportTransaction, Is.SameAs(context.IncomingPipelineTransportTransaction), "Transport Transaction was not the same"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Reliability/SynchronizedStorage/When_opening_storage_session_outside_pipeline.cs b/src/NServiceBus.AcceptanceTests/Core/Reliability/SynchronizedStorage/When_opening_storage_session_outside_pipeline.cs index dd531da9386..ec1c9ded72d 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Reliability/SynchronizedStorage/When_opening_storage_session_outside_pipeline.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Reliability/SynchronizedStorage/When_opening_storage_session_outside_pipeline.cs @@ -35,12 +35,15 @@ public async Task Should_provide_adapted_session_with_same_scope([Values(true, f .Done(c => c.Done) .Run(); - Assert.True(context.SessionNotNullAfterOpening, "The adapted session was null after opening the session."); - Assert.True(context.StorageSessionEqual, "The scoped storage session should be equal."); + Assert.Multiple(() => + { + Assert.That(context.SessionNotNullAfterOpening, Is.True, "The adapted session was null after opening the session."); + Assert.That(context.StorageSessionEqual, Is.True, "The scoped storage session should be equal."); + }); if (useOutbox) { - Assert.True(context.OutboxNotNullAfterOpening, "The scoped storage session should be equal."); + Assert.That(context.OutboxNotNullAfterOpening, Is.True, "The scoped storage session should be equal."); } } diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/AutomaticSubscriptions/When_handling_local_event.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/AutomaticSubscriptions/When_handling_local_event.cs index 373aa24b400..38fde3ce95d 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/AutomaticSubscriptions/When_handling_local_event.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/AutomaticSubscriptions/When_handling_local_event.cs @@ -25,7 +25,7 @@ public async Task Should_autosubscribe_to_event() .Done(c => c.GotEvent) .Run().ConfigureAwait(false); - Assert.True(ctx.GotEvent); + Assert.That(ctx.GotEvent, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_callbacks_are_used_to_reply_with_int_or_enum.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_callbacks_are_used_to_reply_with_int_or_enum.cs index 8ad630b0001..3ce8556704e 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_callbacks_are_used_to_reply_with_int_or_enum.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_callbacks_are_used_to_reply_with_int_or_enum.cs @@ -17,11 +17,14 @@ public async Task Should_throw_late_enough_to_allow_intercept() .Done(c => c.GotTheRequest) .Run(); - Assert.True(context.GotExceptionFromReply); + Assert.Multiple(() => + { + Assert.That(context.GotExceptionFromReply, Is.True); - //this verifies a callbacks assumption that core won't throw until after the `IOutgoingLogicalMessageContext` stage - // See https://github.com/Particular/NServiceBus.Callbacks/blob/develop/src/NServiceBus.Callbacks/Reply/SetCallbackResponseReturnCodeBehavior.cs#L7 - Assert.True(context.WasAbleToInterceptBeforeCoreThrows, "Callbacks needs to be able to intercept the pipeline before core throws"); + //this verifies a callbacks assumption that core won't throw until after the `IOutgoingLogicalMessageContext` stage + // See https://github.com/Particular/NServiceBus.Callbacks/blob/develop/src/NServiceBus.Callbacks/Reply/SetCallbackResponseReturnCodeBehavior.cs#L7 + Assert.That(context.WasAbleToInterceptBeforeCoreThrows, Is.True, "Callbacks needs to be able to intercept the pipeline before core throws"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_extending_command_routing_with_thisinstance.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_extending_command_routing_with_thisinstance.cs index 03118f48af7..2419283e51f 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_extending_command_routing_with_thisinstance.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_extending_command_routing_with_thisinstance.cs @@ -30,8 +30,11 @@ public async Task Should_route_according_to_distribution_strategy() .Done(c => c.MessageDelivered >= 1) .Run(); - Assert.AreEqual(1, ctx.MessageDelivered); - Assert.IsTrue(ctx.StrategyCalled); + Assert.Multiple(() => + { + Assert.That(ctx.MessageDelivered, Is.EqualTo(1)); + Assert.That(ctx.StrategyCalled, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_inner_send_with_outer_immediate_dispatch.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_inner_send_with_outer_immediate_dispatch.cs index 16f67881be1..5910f155122 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_inner_send_with_outer_immediate_dispatch.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_inner_send_with_outer_immediate_dispatch.cs @@ -22,8 +22,11 @@ public async Task Should_not_apply_immediate_dispatch_to_inner_send() .Done(c => c.MessageBReceived) .Run(TimeSpan.FromSeconds(15)); - Assert.IsTrue(context.MessageBReceived); - Assert.IsFalse(context.MessageCReceived); + Assert.Multiple(() => + { + Assert.That(context.MessageBReceived, Is.True); + Assert.That(context.MessageCReceived, Is.False); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_nested_send_with_outer_replyTo_routing.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_nested_send_with_outer_replyTo_routing.cs index bd986f06265..ca76f3d20d8 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_nested_send_with_outer_replyTo_routing.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_nested_send_with_outer_replyTo_routing.cs @@ -28,8 +28,11 @@ public async Task Should_apply_default_reply_in_inner_send() .Done(c => c.OuterMessageReceived && c.InnerMessageReceived) .Run(); - Assert.AreEqual(customReplyAddress, context.OuterMessageReplyAddress); - Assert.AreEqual(Conventions.EndpointNamingConvention(typeof(SenderEndpoint)), context.InnerMessageReplyAddress); + Assert.Multiple(() => + { + Assert.That(context.OuterMessageReplyAddress, Is.EqualTo(customReplyAddress)); + Assert.That(context.InnerMessageReplyAddress, Is.EqualTo(Conventions.EndpointNamingConvention(typeof(SenderEndpoint)))); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_replying_with_pre_created_interface.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_replying_with_pre_created_interface.cs index 64fa37a455d..16582328b63 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_replying_with_pre_created_interface.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_replying_with_pre_created_interface.cs @@ -17,8 +17,11 @@ public async Task Should_route_to_sender() .Done(c => c.GotTheReply) .Run(); - Assert.True(context.GotTheReply); - Assert.AreEqual(typeof(IMyReply), context.MessageTypeInPipeline); + Assert.Multiple(() => + { + Assert.That(context.GotTheReply, Is.True); + Assert.That(context.MessageTypeInPipeline, Is.EqualTo(typeof(IMyReply))); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_routing_interface_message.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_routing_interface_message.cs index b7409f2cc14..54ac411f3ca 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_routing_interface_message.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_routing_interface_message.cs @@ -16,7 +16,7 @@ public async Task Should_use_interface_types_route() .Done(c => c.GotTheMessage) .Run(); - Assert.True(context.GotTheMessage); + Assert.That(context.GotTheMessage, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_from_outgoing_pipeline.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_from_outgoing_pipeline.cs index ce47f64a432..d85049a720b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_from_outgoing_pipeline.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_from_outgoing_pipeline.cs @@ -25,8 +25,11 @@ public async Task Should_use_default_routing_when_empty_send_options() .Done(c => c.LocalMessageReceived && c.BehaviorMessageReceived) .Run(TimeSpan.FromSeconds(15)); - Assert.True(context.LocalMessageReceived); - Assert.True(context.BehaviorMessageReceived); + Assert.Multiple(() => + { + Assert.That(context.LocalMessageReceived, Is.True); + Assert.That(context.BehaviorMessageReceived, Is.True); + }); } [Test] @@ -43,8 +46,11 @@ public async Task Should_apply_send_options_routing() .Done(c => c.LocalMessageReceived && c.BehaviorMessageReceived) .Run(TimeSpan.FromSeconds(15)); - Assert.True(context.LocalMessageReceived); - Assert.True(context.BehaviorMessageReceived); + Assert.Multiple(() => + { + Assert.That(context.LocalMessageReceived, Is.True); + Assert.That(context.BehaviorMessageReceived, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_non_message_with_routing_configured_by_assembly.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_non_message_with_routing_configured_by_assembly.cs index e8c7800a9da..fb197d34da9 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_non_message_with_routing_configured_by_assembly.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_non_message_with_routing_configured_by_assembly.cs @@ -27,7 +27,7 @@ public async Task Should_throw_when_sending() .Done(c => c.GotTheException) .Run(); - StringAssert.Contains("No destination specified for message", context.Exception.ToString()); + Assert.That(context.Exception.ToString(), Does.Contain("No destination specified for message")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_non_message_with_routing_configured_by_type.cs b/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_non_message_with_routing_configured_by_type.cs index 75e4c4f465f..6e204454d42 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_non_message_with_routing_configured_by_type.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Routing/When_sending_non_message_with_routing_configured_by_type.cs @@ -17,7 +17,7 @@ public void Should_throw_when_configuring_routing() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Cannot configure routing for type", exception.ToString()); + Assert.That(exception.ToString(), Does.Contain("Cannot configure routing for type")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_a_saga_is_completed.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_a_saga_is_completed.cs index 27e42340ed5..9db727f674e 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_a_saga_is_completed.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_a_saga_is_completed.cs @@ -30,8 +30,11 @@ public async Task Saga_should_not_handle_subsequent_messages_for_that_sagadata() .Done(c => c.AnotherMessageReceived) .Run(); - Assert.True(context.AnotherMessageReceived, "AnotherMessage should have been delivered to the handler outside the saga"); - Assert.False(context.SagaReceivedAnotherMessage, "AnotherMessage should not be delivered to the saga after completion"); + Assert.Multiple(() => + { + Assert.That(context.AnotherMessageReceived, Is.True, "AnotherMessage should have been delivered to the handler outside the saga"); + Assert.That(context.SagaReceivedAnotherMessage, Is.False, "AnotherMessage should not be delivered to the saga after completion"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_adding_state_to_context.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_adding_state_to_context.cs index 55ada3de3d4..039d944d271 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_adding_state_to_context.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_adding_state_to_context.cs @@ -24,8 +24,11 @@ public async Task Should_make_state_available_to_finder_context() .Done(c => c.FinderUsed) .Run(); - Assert.True(context.FinderUsed); - Assert.AreEqual("SomeData", context.ContextBag.Get().SomeData); + Assert.Multiple(() => + { + Assert.That(context.FinderUsed, Is.True); + Assert.That(context.ContextBag.Get().SomeData, Is.EqualTo("SomeData")); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_completing_a_saga.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_completing_a_saga.cs index 62de9b130ed..9ab4bafc4c6 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_completing_a_saga.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_completing_a_saga.cs @@ -26,7 +26,7 @@ public async Task Should_hydrate_and_complete_the_existing_instance() .Done(c => c.SagaCompleted) .Run(); - Assert.True(context.SagaCompleted); + Assert.That(context.SagaCompleted, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_finder_cant_find_saga_instance.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_finder_cant_find_saga_instance.cs index 64713bfe4fe..8828c02b18b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_finder_cant_find_saga_instance.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_finder_cant_find_saga_instance.cs @@ -21,8 +21,11 @@ public async Task Should_start_new_saga() .Done(c => c.SagaStarted) .Run(); - Assert.True(context.FinderUsed); - Assert.True(context.SagaStarted); + Assert.Multiple(() => + { + Assert.That(context.FinderUsed, Is.True); + Assert.That(context.SagaStarted, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_finder_returns_existing_saga.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_finder_returns_existing_saga.cs index f8f0cd4c4d1..be2569b0e50 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_finder_returns_existing_saga.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_finder_returns_existing_saga.cs @@ -26,7 +26,7 @@ public async Task Should_use_existing_saga() .Done(c => c.HandledOtherMessage) .Run(); - Assert.True(context.FinderUsed); + Assert.That(context.FinderUsed, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_handling_message_with_handler_and_timeout_handler.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_handling_message_with_handler_and_timeout_handler.cs index 41fa5764de7..22955e63ac1 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_handling_message_with_handler_and_timeout_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_handling_message_with_handler_and_timeout_handler.cs @@ -19,8 +19,11 @@ public async Task Should_not_invoke_timeout_handler() .Done(c => c.HandlerInvoked || c.TimeoutHandlerInvoked) .Run(); - Assert.True(context.HandlerInvoked, "Regular handler should be invoked"); - Assert.False(context.TimeoutHandlerInvoked, "Timeout handler should not be invoked"); + Assert.Multiple(() => + { + Assert.That(context.HandlerInvoked, Is.True, "Regular handler should be invoked"); + Assert.That(context.TimeoutHandlerInvoked, Is.False, "Timeout handler should not be invoked"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_mapping_saga_messages_using_base_classes.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_mapping_saga_messages_using_base_classes.cs index 5a01f48ba5d..a0b6c8bd339 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_mapping_saga_messages_using_base_classes.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_mapping_saga_messages_using_base_classes.cs @@ -25,7 +25,7 @@ public async Task Should_apply_base_class_mapping_to_sub_classes() .Done(c => c.SecondMessageFoundExistingSaga) .Run(TimeSpan.FromSeconds(20)); - Assert.True(context.SecondMessageFoundExistingSaga); + Assert.That(context.SecondMessageFoundExistingSaga, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_overriding_saga_id_creation.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_overriding_saga_id_creation.cs index a54a2d2a8fd..89a5b38a493 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_overriding_saga_id_creation.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_overriding_saga_id_creation.cs @@ -24,7 +24,7 @@ public async Task Should_generate_saga_id_accordingly() .Done(c => c.SagaId.HasValue) .Run(); - Assert.AreEqual(new Guid("1d99288a-418d-9e4d-46e4-d49a27908fc8"), context.SagaId); + Assert.That(context.SagaId, Is.EqualTo(new Guid("1d99288a-418d-9e4d-46e4-d49a27908fc8"))); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_starting_a_new_saga.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_starting_a_new_saga.cs index 752d493c0aa..247909c4551 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_starting_a_new_saga.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_starting_a_new_saga.cs @@ -21,7 +21,7 @@ public async Task Should_automatically_assign_correlation_property_value() .Done(c => c.SomeId != Guid.Empty) .Run(); - Assert.AreEqual(context.SomeId, id); + Assert.That(id, Is.EqualTo(context.SomeId)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator.cs index 47c8b21eaf9..945511ca70b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator.cs @@ -30,8 +30,11 @@ public async Task Should_preserve_correlation_context() .Done(c => c.CorrelationIdOnReply != null) .Run(); - Assert.AreEqual(MessageIntent.Reply, context.Intent); - Assert.AreEqual(context.OriginalCorrelationId, context.CorrelationIdOnReply, "Correlation id should be preserved so that things like callbacks work properly"); + Assert.Multiple(() => + { + Assert.That(context.Intent, Is.EqualTo(MessageIntent.Reply)); + Assert.That(context.CorrelationIdOnReply, Is.EqualTo(context.OriginalCorrelationId), "Correlation id should be preserved so that things like callbacks work properly"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator_and_outgoing_behavior.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator_and_outgoing_behavior.cs index 5627d3d9ceb..6781e681f94 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator_and_outgoing_behavior.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator_and_outgoing_behavior.cs @@ -30,9 +30,12 @@ public async Task Should_not_leak_correlation_context() .Done(c => c.SagaContinued && c.ReplyToOriginatorReceived && c.BehaviorMessageReceived && c.BehaviorEventReceived) .Run(); - Assert.AreEqual(context.StartingSagaCorrId, context.ReplyToOriginatorReceivedCorrId, "When using ReplyToOriginator, the correlationId should be the same of the message that originally started the saga"); - Assert.AreEqual(context.ContinueSagaMessageCorrId, context.HandlingBehaviorMessageCorrId, "When ReplyToOriginator is used, it shouldn't leak the CorrId to new messages sent from a behavior"); - Assert.AreEqual(context.ContinueSagaMessageCorrId, context.HandlingBehaviorEventCorrId, "When ReplyToOriginator is used, it shouldn't leak the CorrId to new events published from a behavior"); + Assert.Multiple(() => + { + Assert.That(context.ReplyToOriginatorReceivedCorrId, Is.EqualTo(context.StartingSagaCorrId), "When using ReplyToOriginator, the correlationId should be the same of the message that originally started the saga"); + Assert.That(context.HandlingBehaviorMessageCorrId, Is.EqualTo(context.ContinueSagaMessageCorrId), "When ReplyToOriginator is used, it shouldn't leak the CorrId to new messages sent from a behavior"); + Assert.That(context.HandlingBehaviorEventCorrId, Is.EqualTo(context.ContinueSagaMessageCorrId), "When ReplyToOriginator is used, it shouldn't leak the CorrId to new events published from a behavior"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator_with_headers.cs b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator_with_headers.cs index 3237c5e004a..f8a1c8d2bba 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator_with_headers.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Sagas/When_using_ReplyToOriginator_with_headers.cs @@ -22,7 +22,7 @@ public async Task Should_send_headers() .Done(c => c.CustomHeaderOnReply != null) .Run(); - Assert.AreEqual(customHeaderValue.ToString(), context.CustomHeaderOnReply, "Header values should be forwarded"); + Assert.That(context.CustomHeaderOnReply, Is.EqualTo(customHeaderValue.ToString()), "Header values should be forwarded"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/SelfVerification/ConventionEnforcementTests.cs b/src/NServiceBus.AcceptanceTests/Core/SelfVerification/ConventionEnforcementTests.cs index 5d50fb481f6..68477fa9496 100644 --- a/src/NServiceBus.AcceptanceTests/Core/SelfVerification/ConventionEnforcementTests.cs +++ b/src/NServiceBus.AcceptanceTests/Core/SelfVerification/ConventionEnforcementTests.cs @@ -18,7 +18,7 @@ public void Ensure_all_tests_derive_from_a_common_base_class() .Where(t => t.BaseType == null || !typeof(NServiceBusAcceptanceTest).IsAssignableFrom(t)) .ToList(); - CollectionAssert.IsEmpty(missingBaseClass, string.Join(",", missingBaseClass)); + Assert.That(missingBaseClass, Is.Empty, string.Join(",", missingBaseClass)); } [Test] @@ -35,7 +35,7 @@ public void Ensure_all_messages_are_public() ) .ToList(); - CollectionAssert.IsEmpty(missingBaseClass, string.Join(",", missingBaseClass)); + Assert.That(missingBaseClass, Is.Empty, string.Join(",", missingBaseClass)); } [Test] @@ -50,8 +50,8 @@ public void Ensure_all_diagnostics_tests_are_run_sequentially() var diagnosticTestsWithoutNonParallelizableAttribute = diagnosticTests.Where(t => t.GetCustomAttribute() == null); - CollectionAssert.IsNotEmpty(diagnosticTests); - CollectionAssert.IsEmpty(diagnosticTestsWithoutNonParallelizableAttribute, string.Join(",", diagnosticTests)); + Assert.That(diagnosticTests, Is.Not.Empty); + Assert.That(diagnosticTestsWithoutNonParallelizableAttribute, Is.Empty, string.Join(",", diagnosticTests)); } [Test] @@ -64,7 +64,7 @@ public void Ensure_all_sagadatas_are_public() .Where(t => typeof(IContainSagaData).IsAssignableFrom(t)) .ToList(); - CollectionAssert.IsEmpty(sagaDatas, string.Join(",", sagaDatas)); + Assert.That(sagaDatas, Is.Empty, string.Join(",", sagaDatas)); } static bool HasTestMethod(Type t) diff --git a/src/NServiceBus.AcceptanceTests/Core/SelfVerification/EndpointNameEnforcementTests.cs b/src/NServiceBus.AcceptanceTests/Core/SelfVerification/EndpointNameEnforcementTests.cs index e6f9e2bfd24..5396a7eeb32 100644 --- a/src/NServiceBus.AcceptanceTests/Core/SelfVerification/EndpointNameEnforcementTests.cs +++ b/src/NServiceBus.AcceptanceTests/Core/SelfVerification/EndpointNameEnforcementTests.cs @@ -21,7 +21,7 @@ public void EndpointName_should_not_exceed_maximum_length() .Where(t => AcceptanceTesting.Customization.Conventions.EndpointNamingConvention(t).Length > endpointNameMaxLength) .ToList(); - CollectionAssert.IsEmpty(violators, string.Join(",", violators)); + Assert.That(violators, Is.Empty, string.Join(",", violators)); } static bool IsEndpointClass(Type t) => endpointConfigurationBuilderType.IsAssignableFrom(t); diff --git a/src/NServiceBus.AcceptanceTests/Core/SelfVerification/When_running_saga_tests.cs b/src/NServiceBus.AcceptanceTests/Core/SelfVerification/When_running_saga_tests.cs index 39220b9e58b..2dc44d86538 100644 --- a/src/NServiceBus.AcceptanceTests/Core/SelfVerification/When_running_saga_tests.cs +++ b/src/NServiceBus.AcceptanceTests/Core/SelfVerification/When_running_saga_tests.cs @@ -37,7 +37,7 @@ public void All_saga_entities_in_acceptance_tests_should_have_virtual_properties } } - Assert.AreEqual(0, offenders); + Assert.That(offenders, Is.EqualTo(0)); } [Test] @@ -68,6 +68,6 @@ public void All_sagas_and_entities_should_have_unique_names() usedNames.Add(cls.Name); } - Assert.AreEqual(0, offenders); + Assert.That(offenders, Is.EqualTo(0)); } } \ No newline at end of file diff --git a/src/NServiceBus.AcceptanceTests/Core/SelfVerification/When_using_custom_components.cs b/src/NServiceBus.AcceptanceTests/Core/SelfVerification/When_using_custom_components.cs index f6c6d503fb6..03a9b7190ff 100644 --- a/src/NServiceBus.AcceptanceTests/Core/SelfVerification/When_using_custom_components.cs +++ b/src/NServiceBus.AcceptanceTests/Core/SelfVerification/When_using_custom_components.cs @@ -17,9 +17,12 @@ public async Task Should_properly_start_and_stop_them() .Done(c => c.Starting) .Run(); - Assert.IsTrue(ctx.Starting); - Assert.IsTrue(ctx.ComponentsStarted); - Assert.IsTrue(ctx.Stopped); + Assert.Multiple(() => + { + Assert.That(ctx.Starting, Is.True); + Assert.That(ctx.ComponentsStarted, Is.True); + Assert.That(ctx.Stopped, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Stopping/When_feature_startup_task_throws_on_stop.cs b/src/NServiceBus.AcceptanceTests/Core/Stopping/When_feature_startup_task_throws_on_stop.cs index 8b65aecdf9c..b4f768fa89b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Stopping/When_feature_startup_task_throws_on_stop.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Stopping/When_feature_startup_task_throws_on_stop.cs @@ -22,8 +22,8 @@ public async Task Should_log_exception() .Run(); var logItem = context.Logs.FirstOrDefault(item => item.Message.Contains("stopping of feature startup task") && item.Level == LogLevel.Warn); - Assert.IsNotNull(logItem); - StringAssert.Contains("Exception occurred during stopping of feature startup task 'CustomTask'. System.InvalidOperationException: CustomTaskThrows", logItem.Message); + Assert.That(logItem, Is.Not.Null); + Assert.That(logItem.Message, Does.Contain("Exception occurred during stopping of feature startup task 'CustomTask'. System.InvalidOperationException: CustomTaskThrows")); } public class EndpointThatThrowsOnInfrastructureStop : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Stopping/When_pump_throws_on_stop.cs b/src/NServiceBus.AcceptanceTests/Core/Stopping/When_pump_throws_on_stop.cs index 356c16ba178..2f54b2a7429 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Stopping/When_pump_throws_on_stop.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Stopping/When_pump_throws_on_stop.cs @@ -22,8 +22,8 @@ public async Task Should_not_throw_but_log_exception() var logEntry = context.Logs.FirstOrDefault(l => l.LoggerName == "NServiceBus.ReceiveComponent" && l.Level == LogLevel.Warn); - Assert.IsNotNull(logEntry); - StringAssert.StartsWith("Receiver Main threw an exception on stopping. System.InvalidOperationException: ExceptionInPumpStop", logEntry.Message); + Assert.That(logEntry, Is.Not.Null); + Assert.That(logEntry.Message, Does.StartWith("Receiver Main threw an exception on stopping. System.InvalidOperationException: ExceptionInPumpStop")); } public class EndpointThatThrowsOnPumpStop : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/Stopping/When_transport_infrastructure_throws_on_stop.cs b/src/NServiceBus.AcceptanceTests/Core/Stopping/When_transport_infrastructure_throws_on_stop.cs index 0b3066c9516..6f95f11e980 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Stopping/When_transport_infrastructure_throws_on_stop.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Stopping/When_transport_infrastructure_throws_on_stop.cs @@ -20,8 +20,8 @@ public async Task Should_log_exception() .Run(); var logItem = context.Logs.FirstOrDefault(item => item.Message.Contains("Shutdown of the transport") && item.Level == LogLevel.Error); - Assert.IsNotNull(logItem); - StringAssert.Contains("Shutdown of the transport infrastructure failed. System.InvalidOperationException: ExceptionInInfrastructureStop", logItem.Message); + Assert.That(logItem, Is.Not.Null); + Assert.That(logItem.Message, Does.Contain("Shutdown of the transport infrastructure failed. System.InvalidOperationException: ExceptionInInfrastructureStop")); } public class EndpointThatThrowsOnInfrastructureStop : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_publisher_has_subscription_migration_mode_enabled.cs b/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_publisher_has_subscription_migration_mode_enabled.cs index 93c0fbe665f..9bda72d689b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_publisher_has_subscription_migration_mode_enabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_publisher_has_subscription_migration_mode_enabled.cs @@ -18,8 +18,11 @@ public async Task CanHandleMessageDrivenSubscribers() .Done(c => c.EventReceived) .Run(); - Assert.IsTrue(context.EventReceived); - Assert.AreEqual(Conventions.EndpointNamingConvention(typeof(MessageDrivenSubscriber)), context.Subscriber); + Assert.Multiple(() => + { + Assert.That(context.EventReceived, Is.True); + Assert.That(context.Subscriber, Is.EqualTo(Conventions.EndpointNamingConvention(typeof(MessageDrivenSubscriber)))); + }); } [Test] @@ -32,7 +35,7 @@ public async Task CanHandleNativeSubscribers() .Done(c => c.EventReceived) .Run(); - Assert.IsTrue(context.EventReceived); + Assert.That(context.EventReceived, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_send_only_endpoint_uses_migration_mode.cs b/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_send_only_endpoint_uses_migration_mode.cs index e380b2278dd..f2ea851bdfd 100644 --- a/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_send_only_endpoint_uses_migration_mode.cs +++ b/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_send_only_endpoint_uses_migration_mode.cs @@ -16,7 +16,7 @@ public void Should_throw_InvalidOperationException_on_subscribe() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Send-only endpoints cannot subscribe to events", exception.Message); + Assert.That(exception.Message, Does.Contain("Send-only endpoints cannot subscribe to events")); } [Test] @@ -28,7 +28,7 @@ public void Should_throw_InvalidOperationException_on_unsubscribe() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("Send-only endpoints cannot unsubscribe to events", exception.Message); + Assert.That(exception.Message, Does.Contain("Send-only endpoints cannot unsubscribe to events")); } class SendOnlyEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_subscriber_has_subscription_migration_mode_enabled.cs b/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_subscriber_has_subscription_migration_mode_enabled.cs index 92b857ffaec..66263b6f1b4 100644 --- a/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_subscriber_has_subscription_migration_mode_enabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/SubscriptionMigration/When_subscriber_has_subscription_migration_mode_enabled.cs @@ -19,8 +19,11 @@ public async Task CanSubscribeToMessageDrivenPublishers() .Done(c => c.EventReceived) .Run(); - Assert.IsTrue(context.EventReceived); - Assert.AreEqual(Conventions.EndpointNamingConvention(typeof(MigratedSubscriber)), context.Subscriber); + Assert.Multiple(() => + { + Assert.That(context.EventReceived, Is.True); + Assert.That(context.Subscriber, Is.EqualTo(Conventions.EndpointNamingConvention(typeof(MigratedSubscriber)))); + }); } [Test] @@ -33,7 +36,7 @@ public async Task CanSubscribeToNativePublishers() .Done(c => c.EventReceived) .Run(); - Assert.IsTrue(context.EventReceived); + Assert.That(context.EventReceived, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/Transactions/When_transport_supports_transaction_scope_on_windows.cs b/src/NServiceBus.AcceptanceTests/Core/Transactions/When_transport_supports_transaction_scope_on_windows.cs index c1c55cc8fad..85467ee3dbb 100644 --- a/src/NServiceBus.AcceptanceTests/Core/Transactions/When_transport_supports_transaction_scope_on_windows.cs +++ b/src/NServiceBus.AcceptanceTests/Core/Transactions/When_transport_supports_transaction_scope_on_windows.cs @@ -30,7 +30,7 @@ await Scenario.Define() .Done(c => c.EndpointsStarted) .Run(); - Assert.True(fakeTransport.DtcIsAvailable, fakeTransport.DtcCheckException?.Message); + Assert.That(fakeTransport.DtcIsAvailable, Is.True, fakeTransport.DtcCheckException?.Message); } public class TransactionScopeEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_configuring_transport.cs b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_configuring_transport.cs index af7b413f3d9..54c4268ad71 100644 --- a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_configuring_transport.cs +++ b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_configuring_transport.cs @@ -17,7 +17,7 @@ public async Task Should_provide_transport_definition_to_features() .Done(c => c.EndpointsStarted) .Run(); - Assert.IsNotNull(context.TransportDefinition); + Assert.That(context.TransportDefinition, Is.Not.Null); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_initializing_transport.cs b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_initializing_transport.cs index 452b8a9f9f7..9e1402d6e4c 100644 --- a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_initializing_transport.cs +++ b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_initializing_transport.cs @@ -18,14 +18,14 @@ public async Task Should_follow_the_startup_sequence() .Done(c => c.EndpointsStarted) .Run(); - CollectionAssert.AreEqual(new List + Assert.That(context.StartUpSequence, Is.EqualTo(new List { $"{nameof(TransportDefinition)}.{nameof(TransportDefinition.Initialize)}", $"{nameof(IMessageReceiver)}.{nameof(IMessageReceiver.Initialize)} for receiver Main", $"{nameof(IMessageReceiver)}.{nameof(IMessageReceiver.StartReceive)} for receiver Main", $"{nameof(IMessageReceiver)}.{nameof(IMessageReceiver.StopReceive)} for receiver Main", $"{nameof(TransportInfrastructure)}.{nameof(TransportInfrastructure.Shutdown)}", - }, context.StartUpSequence); + }).AsCollection); } [Test] @@ -36,11 +36,11 @@ public async Task Should_follow_the_startup_sequence_for_send_only_endpoints() .Done(c => c.EndpointsStarted) .Run(); - CollectionAssert.AreEqual(new List + Assert.That(context.StartUpSequence, Is.EqualTo(new List { $"{nameof(TransportDefinition)}.{nameof(TransportDefinition.Initialize)}", $"{nameof(TransportInfrastructure)}.{nameof(TransportInfrastructure.Shutdown)}", - }, context.StartUpSequence); + }).AsCollection); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_querying_for_transaction_mode.cs b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_querying_for_transaction_mode.cs index 860961107c7..4641bf0234b 100644 --- a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_querying_for_transaction_mode.cs +++ b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_querying_for_transaction_mode.cs @@ -17,7 +17,7 @@ public async Task Should_retrieve_value_set_for_transport_transaction_mode() .Done(c => c.EndpointsStarted) .Run(); - Assert.AreEqual(TransportTransactionMode.ReceiveOnly, context.TransactionModeFromSettingsExtensions, "Transport transaction mode for the endpoint did not match the expected value."); + Assert.That(context.TransactionModeFromSettingsExtensions, Is.EqualTo(TransportTransactionMode.ReceiveOnly), "Transport transaction mode for the endpoint did not match the expected value."); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_transport_is_started.cs b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_transport_is_started.cs index f1b6a586661..2e75e5073e5 100644 --- a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_transport_is_started.cs +++ b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_transport_is_started.cs @@ -21,12 +21,15 @@ public async Task Should_provide_access_to_addresses_and_address_resolution() var endpointName = AcceptanceTesting.Customization.Conventions.EndpointNamingConvention(typeof(Endpoint)); - Assert.AreEqual("SomeAddress", context.ResolvedAddress); - Assert.AreEqual(endpointName, context.ReceiveAddresses.MainReceiveAddress); - Assert.AreEqual(endpointName + "-MyInstance", context.ReceiveAddresses.InstanceReceiveAddress); - Assert.AreEqual("MySatellite", context.ReceiveAddresses.SatelliteReceiveAddresses.Single()); - Assert.AreEqual(endpointName, context.LocalQueueAddress.ToString()); - Assert.AreEqual(endpointName + "-MyInstance", context.InstanceSpecificQueueAddress.ToString()); + Assert.Multiple(() => + { + Assert.That(context.ResolvedAddress, Is.EqualTo("SomeAddress")); + Assert.That(context.ReceiveAddresses.MainReceiveAddress, Is.EqualTo(endpointName)); + Assert.That(context.ReceiveAddresses.InstanceReceiveAddress, Is.EqualTo(endpointName + "-MyInstance")); + Assert.That(context.ReceiveAddresses.SatelliteReceiveAddresses.Single(), Is.EqualTo("MySatellite")); + Assert.That(context.LocalQueueAddress.ToString(), Is.EqualTo(endpointName)); + Assert.That(context.InstanceSpecificQueueAddress.ToString(), Is.EqualTo(endpointName + "-MyInstance")); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_transport_is_started_send_only.cs b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_transport_is_started_send_only.cs index facbe75f6e5..ba3d76aa475 100644 --- a/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_transport_is_started_send_only.cs +++ b/src/NServiceBus.AcceptanceTests/Core/TransportSeam/When_transport_is_started_send_only.cs @@ -19,7 +19,7 @@ public async Task Should_provide_access_to_address_resolution() .Done(c => c.EndpointsStarted) .Run(); - Assert.AreEqual("SomeAddress", context.ResolvedAddress); + Assert.That(context.ResolvedAddress, Is.EqualTo("SomeAddress")); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_transactionscope_enabled.cs b/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_transactionscope_enabled.cs index 6062e846713..70c6fbc7901 100644 --- a/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_transactionscope_enabled.cs +++ b/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_transactionscope_enabled.cs @@ -16,8 +16,11 @@ public async Task Should_wrap_the_handlers_in_a_scope() .Done(c => c.Done) .Run(); - Assert.True(context.AmbientTransactionPresent, "There should be a ambient transaction present"); - Assert.AreEqual(context.IsolationLevel, IsolationLevel.RepeatableRead, "There should be a ambient transaction present"); + Assert.Multiple(() => + { + Assert.That(context.AmbientTransactionPresent, Is.True, "There should be a ambient transaction present"); + Assert.That(context.IsolationLevel, Is.EqualTo(IsolationLevel.RepeatableRead), "There should be a ambient transaction present"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_used_with_default_transaction_mode.cs b/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_used_with_default_transaction_mode.cs index e8833f50e97..600427e0654 100644 --- a/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_used_with_default_transaction_mode.cs +++ b/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_used_with_default_transaction_mode.cs @@ -25,7 +25,7 @@ public async Task Should_work() .Done(c => c.EndpointsStarted) .Run(); - Assert.True(context.EndpointsStarted); + Assert.That(context.EndpointsStarted, Is.True); } public class ScopeEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_used_with_transport_scopes.cs b/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_used_with_transport_scopes.cs index c207004189c..58545991516 100644 --- a/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_used_with_transport_scopes.cs +++ b/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_used_with_transport_scopes.cs @@ -27,7 +27,7 @@ await Scenario.Define() .Run(); }); - Assert.True(exception.Message.Contains("A Transaction scope unit of work can't be used when the transport already uses a scope")); + Assert.That(exception.Message, Does.Contain("A Transaction scope unit of work can't be used when the transport already uses a scope")); } public class ScopeEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_using_timeout_greater_than_machine_max.cs b/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_using_timeout_greater_than_machine_max.cs index cf04e7b2cf4..820675043ed 100644 --- a/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_using_timeout_greater_than_machine_max.cs +++ b/src/NServiceBus.AcceptanceTests/Core/UnitOfWork/TransactionScope/When_using_timeout_greater_than_machine_max.cs @@ -17,7 +17,7 @@ await Scenario.Define() .Run(); }); - Assert.True(exception.Message.Contains("Timeout requested is longer than the maximum value for this machine")); + Assert.That(exception.Message, Does.Contain("Timeout requested is longer than the maximum value for this machine")); } public class ScopeEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Correlation/When_replying_to_received_message_without_correlationid.cs b/src/NServiceBus.AcceptanceTests/Correlation/When_replying_to_received_message_without_correlationid.cs index 2f5c8f7ea78..bc51f177d0e 100644 --- a/src/NServiceBus.AcceptanceTests/Correlation/When_replying_to_received_message_without_correlationid.cs +++ b/src/NServiceBus.AcceptanceTests/Correlation/When_replying_to_received_message_without_correlationid.cs @@ -24,7 +24,7 @@ public async Task Should_use_the_incoming_message_id_as_the_correlation_id() .Done(c => c.GotResponse) .Run(); - Assert.AreEqual(mycustomid, context.CorrelationIdReceived, "Correlation id should match MessageId"); + Assert.That(context.CorrelationIdReceived, Is.EqualTo(mycustomid), "Correlation id should match MessageId"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Correlation/When_sending_with_no_correlation_id.cs b/src/NServiceBus.AcceptanceTests/Correlation/When_sending_with_no_correlation_id.cs index 4ada0440aa0..753b3b5eaea 100644 --- a/src/NServiceBus.AcceptanceTests/Correlation/When_sending_with_no_correlation_id.cs +++ b/src/NServiceBus.AcceptanceTests/Correlation/When_sending_with_no_correlation_id.cs @@ -15,7 +15,7 @@ public async Task Should_use_the_message_id_as_the_correlation_id() .Done(c => c.GotRequest) .Run(); - Assert.AreEqual(context.MessageIdReceived, context.CorrelationIdReceived, "Correlation id should match MessageId"); + Assert.That(context.CorrelationIdReceived, Is.EqualTo(context.MessageIdReceived), "Correlation id should match MessageId"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/DataBus/When_sender_serializer_differ.cs b/src/NServiceBus.AcceptanceTests/DataBus/When_sender_serializer_differ.cs index ea043790c47..6832c8bc0a8 100644 --- a/src/NServiceBus.AcceptanceTests/DataBus/When_sender_serializer_differ.cs +++ b/src/NServiceBus.AcceptanceTests/DataBus/When_sender_serializer_differ.cs @@ -31,7 +31,7 @@ public async Task Should_deserialize_based_on_serializer_used() .Done(c => c.ReceivedPayload != null) .Run(); - Assert.AreEqual(payloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus"); + Assert.That(context.ReceivedPayload, Is.EqualTo(payloadToSend), "The large payload should be marshalled correctly using the databus"); } const int PayloadSize = 500; diff --git a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_from_different_environments.cs b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_from_different_environments.cs index cc10f66e86b..51fa6850e43 100644 --- a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_from_different_environments.cs +++ b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_from_different_environments.cs @@ -31,7 +31,7 @@ public async Task Should_receive_messages_with_largepayload_correctly_from_windo .Done(c => c.ReceivedPayload != null) .Run(); - Assert.AreEqual(payloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus"); + Assert.That(context.ReceivedPayload, Is.EqualTo(payloadToSend), "The large payload should be marshalled correctly using the databus"); } [Test] @@ -48,7 +48,7 @@ public async Task Should_receive_messages_with_largepayload_correctly_from_linux .Done(c => c.ReceivedPayload != null) .Run(); - Assert.AreEqual(payloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus"); + Assert.That(context.ReceivedPayload, Is.EqualTo(payloadToSend), "The large payload should be marshalled correctly using the databus"); } const int PayloadSize = 500; diff --git a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_with_systemjson_message_serializer.cs b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_with_systemjson_message_serializer.cs index 9b0dd00d1ee..33a32e4ec06 100644 --- a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_with_systemjson_message_serializer.cs +++ b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_with_systemjson_message_serializer.cs @@ -30,7 +30,7 @@ public async Task Should_receive_messages_with_largepayload_correctly() .Done(c => c.ReceivedPayload != null) .Run(); - Assert.AreEqual(payloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus"); + Assert.That(context.ReceivedPayload, Is.EqualTo(payloadToSend), "The large payload should be marshalled correctly using the databus"); } const int PayloadSize = 500; diff --git a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_with_xml_message_serializer.cs b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_with_xml_message_serializer.cs index bf705167c11..3a9bf69ed81 100644 --- a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_with_xml_message_serializer.cs +++ b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_databus_properties_with_xml_message_serializer.cs @@ -30,7 +30,7 @@ public async Task Should_receive_messages_with_largepayload_correctly() .Done(c => c.ReceivedPayload != null) .Run(); - Assert.AreEqual(payloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus"); + Assert.That(context.ReceivedPayload, Is.EqualTo(payloadToSend), "The large payload should be marshalled correctly using the databus"); } const int PayloadSize = 500; diff --git a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_unobtrusive_databus_properties_with_systemjson_message_serializer.cs b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_unobtrusive_databus_properties_with_systemjson_message_serializer.cs index e60d45c9371..8734d3a0fe1 100644 --- a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_unobtrusive_databus_properties_with_systemjson_message_serializer.cs +++ b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_unobtrusive_databus_properties_with_systemjson_message_serializer.cs @@ -30,7 +30,7 @@ public async Task Should_receive_messages_with_largepayload_correctly() .Done(c => c.ReceivedPayload != null) .Run(); - Assert.AreEqual(payloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus"); + Assert.That(context.ReceivedPayload, Is.EqualTo(payloadToSend), "The large payload should be marshalled correctly using the databus"); } const int PayloadSize = 500; diff --git a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_unobtrusive_databus_properties_with_xml_message_serializer.cs b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_unobtrusive_databus_properties_with_xml_message_serializer.cs index 541f7e4afed..c4e589b47d4 100644 --- a/src/NServiceBus.AcceptanceTests/DataBus/When_sending_unobtrusive_databus_properties_with_xml_message_serializer.cs +++ b/src/NServiceBus.AcceptanceTests/DataBus/When_sending_unobtrusive_databus_properties_with_xml_message_serializer.cs @@ -30,7 +30,7 @@ public async Task Should_receive_messages_with_largepayload_correctly() .Done(c => c.ReceivedPayload != null) .Run(); - Assert.AreEqual(payloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus"); + Assert.That(context.ReceivedPayload, Is.EqualTo(payloadToSend), "The large payload should be marshalled correctly using the databus"); } const int PayloadSize = 500; diff --git a/src/NServiceBus.AcceptanceTests/DataBus/When_using_custom_IDataBus.cs b/src/NServiceBus.AcceptanceTests/DataBus/When_using_custom_IDataBus.cs index 9c88448825a..9cbbbd5b74e 100644 --- a/src/NServiceBus.AcceptanceTests/DataBus/When_using_custom_IDataBus.cs +++ b/src/NServiceBus.AcceptanceTests/DataBus/When_using_custom_IDataBus.cs @@ -30,7 +30,7 @@ public async Task Should_be_able_to_register_via_fluent() .Done(c => c.ReceivedPayload != null) .Run(); - Assert.AreEqual(PayloadToSend, context.ReceivedPayload, "The large payload should be marshalled correctly using the databus"); + Assert.That(context.ReceivedPayload, Is.EqualTo(PayloadToSend), "The large payload should be marshalled correctly using the databus"); } static byte[] PayloadToSend = new byte[1024 * 10]; diff --git a/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_Deferring_a_message.cs b/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_Deferring_a_message.cs index a89118afd47..0476531547a 100644 --- a/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_Deferring_a_message.cs +++ b/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_Deferring_a_message.cs @@ -31,7 +31,7 @@ public async Task Should_delay_delivery() .Run(); var sendReceiveDifference = context.ReceivedAt - context.SentAt; - Assert.GreaterOrEqual(sendReceiveDifference, delay); + Assert.That(sendReceiveDifference, Is.GreaterThanOrEqualTo(delay)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_a_message_to_the_past.cs b/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_a_message_to_the_past.cs index 92ce0e5faf0..260d6c6091f 100644 --- a/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_a_message_to_the_past.cs +++ b/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_a_message_to_the_past.cs @@ -26,7 +26,7 @@ public async Task Should_deliver_message() .Done(c => c.MessageReceived) .Run(); - Assert.IsTrue(context.MessageReceived); + Assert.That(context.MessageReceived, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_outer_send.cs b/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_outer_send.cs index b94fa8ed903..825d158e58b 100644 --- a/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_outer_send.cs +++ b/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_outer_send.cs @@ -27,8 +27,11 @@ public async Task Should_not_defer_inner_send() .Done(c => c.ReceivedNonDelayedMessage && c.ReceivedDelayedMessage) .Run(); - Assert.IsTrue(context.DelayedMessageDelayed, "should delay the message sent with 'DelayDeliveryWith'"); - Assert.IsFalse(context.NonDelayedMessageDelayed, "should not delay the message sent with default options"); + Assert.Multiple(() => + { + Assert.That(context.DelayedMessageDelayed, Is.True, "should delay the message sent with 'DelayDeliveryWith'"); + Assert.That(context.NonDelayedMessageDelayed, Is.False, "should not delay the message sent with default options"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_to_non_local.cs b/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_to_non_local.cs index 9953ed084eb..3e3c8db78fd 100644 --- a/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_to_non_local.cs +++ b/src/NServiceBus.AcceptanceTests/DelayedDelivery/When_deferring_to_non_local.cs @@ -31,7 +31,7 @@ public async Task Message_should_be_received() .Done(c => c.WasCalled) .Run(); - Assert.GreaterOrEqual(context.ReceivedAt - context.SentAt, delay); + Assert.That(context.ReceivedAt - context.SentAt, Is.GreaterThanOrEqualTo(delay)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Feature/When_purging_queues.cs b/src/NServiceBus.AcceptanceTests/Feature/When_purging_queues.cs index d10cad94f5a..65a8a02a5cb 100644 --- a/src/NServiceBus.AcceptanceTests/Feature/When_purging_queues.cs +++ b/src/NServiceBus.AcceptanceTests/Feature/When_purging_queues.cs @@ -19,7 +19,7 @@ public async Task Should_purge_before_FeatureStartupTasks() .Done(c => c.LocalMessageReceived) .Run(); - Assert.IsTrue(context.LocalMessageReceived); + Assert.That(context.LocalMessageReceived, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Feature/When_subscribing_in_FST.cs b/src/NServiceBus.AcceptanceTests/Feature/When_subscribing_in_FST.cs index 57a43f7b8c8..fb6ca4151bf 100644 --- a/src/NServiceBus.AcceptanceTests/Feature/When_subscribing_in_FST.cs +++ b/src/NServiceBus.AcceptanceTests/Feature/When_subscribing_in_FST.cs @@ -23,7 +23,7 @@ public async Task Should_receive_subscribed_events_native() .Done(c => c.LocalEventReceived) .Run(); - Assert.IsTrue(context.LocalEventReceived); + Assert.That(context.LocalEventReceived, Is.True); } [Test] @@ -37,7 +37,7 @@ public async Task Should_receive_subscribed_events_mdps() .Done(c => c.LocalEventReceived) .Run(); - Assert.IsTrue(context.LocalEventReceived); + Assert.That(context.LocalEventReceived, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Forwarding/When_requesting_message_to_be_forwarded.cs b/src/NServiceBus.AcceptanceTests/Forwarding/When_requesting_message_to_be_forwarded.cs index 27c2c0974f9..69b4c7d3a61 100644 --- a/src/NServiceBus.AcceptanceTests/Forwarding/When_requesting_message_to_be_forwarded.cs +++ b/src/NServiceBus.AcceptanceTests/Forwarding/When_requesting_message_to_be_forwarded.cs @@ -18,8 +18,8 @@ public async Task Should_forward_message() .Done(c => c.GotForwardedMessage) .Run(); - Assert.IsTrue(context.GotForwardedMessage); - CollectionAssert.AreEqual(context.ForwardedHeaders, context.ReceivedHeaders, "Headers should be preserved on the forwarded message"); + Assert.That(context.GotForwardedMessage, Is.True); + Assert.That(context.ReceivedHeaders, Is.EqualTo(context.ForwardedHeaders).AsCollection, "Headers should be preserved on the forwarded message"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/MessageId/When_message_has_empty_id_header.cs b/src/NServiceBus.AcceptanceTests/MessageId/When_message_has_empty_id_header.cs index 934218d7c64..28fb1811acd 100644 --- a/src/NServiceBus.AcceptanceTests/MessageId/When_message_has_empty_id_header.cs +++ b/src/NServiceBus.AcceptanceTests/MessageId/When_message_has_empty_id_header.cs @@ -19,8 +19,11 @@ public async Task A_message_id_is_generated_by_the_transport_layer() .Done(c => c.MessageReceived) .Run(); - Assert.IsFalse(string.IsNullOrWhiteSpace(context.MessageId)); - Assert.AreEqual(context.MessageId, context.Headers[Headers.MessageId], "Should populate the NServiceBus.MessageId header with the new value"); + Assert.Multiple(() => + { + Assert.That(string.IsNullOrWhiteSpace(context.MessageId), Is.False); + Assert.That(context.Headers[Headers.MessageId], Is.EqualTo(context.MessageId), "Should populate the NServiceBus.MessageId header with the new value"); + }); } class CorruptionBehavior : IBehavior diff --git a/src/NServiceBus.AcceptanceTests/MessageId/When_message_has_no_id_header.cs b/src/NServiceBus.AcceptanceTests/MessageId/When_message_has_no_id_header.cs index def6a892738..da173a95591 100644 --- a/src/NServiceBus.AcceptanceTests/MessageId/When_message_has_no_id_header.cs +++ b/src/NServiceBus.AcceptanceTests/MessageId/When_message_has_no_id_header.cs @@ -18,7 +18,7 @@ public async Task A_message_id_is_generated_by_the_transport_layer_on_receiving_ .Done(c => c.MessageReceived) .Run(); - Assert.IsFalse(string.IsNullOrWhiteSpace(context.MessageId)); + Assert.That(string.IsNullOrWhiteSpace(context.MessageId), Is.False); } class CorruptionBehavior : IBehavior diff --git a/src/NServiceBus.AcceptanceTests/NServiceBus.AcceptanceTests.csproj b/src/NServiceBus.AcceptanceTests/NServiceBus.AcceptanceTests.csproj index fb2ec7e80c2..e24d10bc905 100644 --- a/src/NServiceBus.AcceptanceTests/NServiceBus.AcceptanceTests.csproj +++ b/src/NServiceBus.AcceptanceTests/NServiceBus.AcceptanceTests.csproj @@ -12,6 +12,7 @@ + diff --git a/src/NServiceBus.AcceptanceTests/NServiceBusAcceptanceTest.cs b/src/NServiceBus.AcceptanceTests/NServiceBusAcceptanceTest.cs index 88f786a3efa..af888e1ab93 100644 --- a/src/NServiceBus.AcceptanceTests/NServiceBusAcceptanceTest.cs +++ b/src/NServiceBus.AcceptanceTests/NServiceBusAcceptanceTest.cs @@ -48,23 +48,23 @@ public void TearDown() if (Environment.GetEnvironmentVariable("CI") != "true" || Environment.GetEnvironmentVariable("VERBOSE_TEST_LOGGING")?.ToLower() == "true") { - TestContext.WriteLine($@"Test settings: + TestContext.Out.WriteLine($@"Test settings: {string.Join(Environment.NewLine, runDescriptor.Settings.Select(setting => $" {setting.Key}: {setting.Value}"))}"); - TestContext.WriteLine($@"Context: + TestContext.Out.WriteLine($@"Context: {string.Join(Environment.NewLine, scenarioContext.GetType().GetProperties().Select(p => $"{p.Name} = {p.GetValue(scenarioContext, null)}"))}"); } if (TestExecutionContext.CurrentContext.CurrentResult.ResultState == ResultState.Failure || TestExecutionContext.CurrentContext.CurrentResult.ResultState == ResultState.Error) { - TestContext.WriteLine(string.Empty); - TestContext.WriteLine($"Log entries (log level: {scenarioContext.LogLevel}):"); - TestContext.WriteLine("--- Start log entries ---------------------------------------------------"); + TestContext.Out.WriteLine(string.Empty); + TestContext.Out.WriteLine($"Log entries (log level: {scenarioContext.LogLevel}):"); + TestContext.Out.WriteLine("--- Start log entries ---------------------------------------------------"); foreach (var logEntry in scenarioContext.Logs) { - TestContext.WriteLine($"{logEntry.Timestamp:T} {logEntry.Level} {logEntry.Endpoint ?? TestContext.CurrentContext.Test.Name}: {logEntry.Message}"); + TestContext.Out.WriteLine($"{logEntry.Timestamp:T} {logEntry.Level} {logEntry.Endpoint ?? TestContext.CurrentContext.Test.Name}: {logEntry.Message}"); } - TestContext.WriteLine("--- End log entries ---------------------------------------------------"); + TestContext.Out.WriteLine("--- End log entries ---------------------------------------------------"); } } } diff --git a/src/NServiceBus.AcceptanceTests/Outbox/When_a_duplicate_message_arrives.cs b/src/NServiceBus.AcceptanceTests/Outbox/When_a_duplicate_message_arrives.cs index 2ae6b035b8c..e01cb217d4e 100644 --- a/src/NServiceBus.AcceptanceTests/Outbox/When_a_duplicate_message_arrives.cs +++ b/src/NServiceBus.AcceptanceTests/Outbox/When_a_duplicate_message_arrives.cs @@ -35,8 +35,11 @@ await session.SendLocal(new PlaceOrder .Done(c => c.Done && c.MessagesReceivedByDownstreamEndpoint >= 2 && c.MessagesReceivedByOutboxEndpoint >= 2) .Run(); - Assert.AreEqual(2, context.MessagesReceivedByDownstreamEndpoint); - Assert.AreEqual(2, context.MessagesReceivedByOutboxEndpoint); + Assert.Multiple(() => + { + Assert.That(context.MessagesReceivedByDownstreamEndpoint, Is.EqualTo(2)); + Assert.That(context.MessagesReceivedByOutboxEndpoint, Is.EqualTo(2)); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Outbox/When_a_message_is_audited.cs b/src/NServiceBus.AcceptanceTests/Outbox/When_a_message_is_audited.cs index e7939a41e6f..4cb44d09af1 100644 --- a/src/NServiceBus.AcceptanceTests/Outbox/When_a_message_is_audited.cs +++ b/src/NServiceBus.AcceptanceTests/Outbox/When_a_message_is_audited.cs @@ -24,7 +24,7 @@ public async Task Should_dispatch_audit_message_immediately() .Done(c => c.MessageAudited) .Run(); - Assert.True(context.MessageAudited); + Assert.That(context.MessageAudited, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Outbox/When_blowing_up_just_after_dispatch.cs b/src/NServiceBus.AcceptanceTests/Outbox/When_blowing_up_just_after_dispatch.cs index 738d2f237f4..21fe985d7bf 100644 --- a/src/NServiceBus.AcceptanceTests/Outbox/When_blowing_up_just_after_dispatch.cs +++ b/src/NServiceBus.AcceptanceTests/Outbox/When_blowing_up_just_after_dispatch.cs @@ -21,7 +21,7 @@ public async Task Should_still_release_the_outgoing_messages_to_the_transport() .Done(c => c.OrderAckReceived) .Run(TimeSpan.FromSeconds(20)); - Assert.IsTrue(context.OrderAckReceived, "Order ack should have been received since outbox dispatch isn't part of the receive tx"); + Assert.That(context.OrderAckReceived, Is.True, "Order ack should have been received since outbox dispatch isn't part of the receive tx"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Outbox/When_headers_contain_special_characters.cs b/src/NServiceBus.AcceptanceTests/Outbox/When_headers_contain_special_characters.cs index 08bde014a4a..01de6e12128 100644 --- a/src/NServiceBus.AcceptanceTests/Outbox/When_headers_contain_special_characters.cs +++ b/src/NServiceBus.AcceptanceTests/Outbox/When_headers_contain_special_characters.cs @@ -35,8 +35,8 @@ public async Task Outbox_should_work() .Done(c => c.MessageReceived) .Run(); - Assert.IsNotEmpty(context.UnicodeHeaders); - CollectionAssert.IsSubsetOf(sentHeaders, context.UnicodeHeaders); + Assert.That(context.UnicodeHeaders, Is.Not.Empty); + Assert.That(sentHeaders, Is.SubsetOf(context.UnicodeHeaders)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Outbox/When_publishing_with_outbox.cs b/src/NServiceBus.AcceptanceTests/Outbox/When_publishing_with_outbox.cs index 64a3bef7132..f188abb78fa 100644 --- a/src/NServiceBus.AcceptanceTests/Outbox/When_publishing_with_outbox.cs +++ b/src/NServiceBus.AcceptanceTests/Outbox/When_publishing_with_outbox.cs @@ -55,8 +55,11 @@ public async Task Should_be_delivered_to_all_subscribers() .Done(c => c.Subscriber1GotTheEvent && c.Subscriber2GotTheEvent) .Run(TimeSpan.FromSeconds(10)); - Assert.True(context.Subscriber1GotTheEvent); - Assert.True(context.Subscriber2GotTheEvent); + Assert.Multiple(() => + { + Assert.That(context.Subscriber1GotTheEvent, Is.True); + Assert.That(context.Subscriber2GotTheEvent, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Outbox/When_receiving_a_message.cs b/src/NServiceBus.AcceptanceTests/Outbox/When_receiving_a_message.cs index 0688ed74561..6bcb6eb6317 100644 --- a/src/NServiceBus.AcceptanceTests/Outbox/When_receiving_a_message.cs +++ b/src/NServiceBus.AcceptanceTests/Outbox/When_receiving_a_message.cs @@ -18,7 +18,7 @@ public async Task Should_handle_it() .Done(c => c.OrderAckReceived == 1) .Run(TimeSpan.FromSeconds(20)); - Assert.AreEqual(1, context.OrderAckReceived, "Order ack should have been received"); + Assert.That(context.OrderAckReceived, Is.EqualTo(1), "Order ack should have been received"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Pipeline/When_a_message_is_audited.cs b/src/NServiceBus.AcceptanceTests/Pipeline/When_a_message_is_audited.cs index 06d74af6c35..46d3997e6fd 100644 --- a/src/NServiceBus.AcceptanceTests/Pipeline/When_a_message_is_audited.cs +++ b/src/NServiceBus.AcceptanceTests/Pipeline/When_a_message_is_audited.cs @@ -17,8 +17,11 @@ public async Task Should_flow_causation_headers() .Done(c => c.Done) .Run(); - Assert.AreEqual(context.OriginRelatedTo, context.RelatedTo, "The RelatedTo header in audit message should be be equal to RelatedTo header in origin."); - Assert.AreEqual(context.OriginConversationId, context.ConversationId, "The ConversationId header in audit message should be be equal to ConversationId header in origin."); + Assert.Multiple(() => + { + Assert.That(context.RelatedTo, Is.EqualTo(context.OriginRelatedTo), "The RelatedTo header in audit message should be be equal to RelatedTo header in origin."); + Assert.That(context.ConversationId, Is.EqualTo(context.OriginConversationId), "The ConversationId header in audit message should be be equal to ConversationId header in origin."); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Pipeline/When_a_message_is_faulted.cs b/src/NServiceBus.AcceptanceTests/Pipeline/When_a_message_is_faulted.cs index 92713aa5bf7..df6c0199778 100644 --- a/src/NServiceBus.AcceptanceTests/Pipeline/When_a_message_is_faulted.cs +++ b/src/NServiceBus.AcceptanceTests/Pipeline/When_a_message_is_faulted.cs @@ -17,8 +17,11 @@ public async Task Should_flow_causation_headers() .Done(c => c.Done) .Run(); - Assert.AreEqual(context.OriginRelatedTo, context.RelatedTo, "The RelatedTo header in fault message should be be equal to RelatedTo header in origin."); - Assert.AreEqual(context.OriginConversationId, context.ConversationId, "The ConversationId header in fault message should be be equal to ConversationId header in origin."); + Assert.Multiple(() => + { + Assert.That(context.RelatedTo, Is.EqualTo(context.OriginRelatedTo), "The RelatedTo header in fault message should be be equal to RelatedTo header in origin."); + Assert.That(context.ConversationId, Is.EqualTo(context.OriginConversationId), "The ConversationId header in fault message should be be equal to ConversationId header in origin."); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Pipeline/When_message_processing_fails.cs b/src/NServiceBus.AcceptanceTests/Pipeline/When_message_processing_fails.cs index 4d1b1b42a65..034f8988972 100644 --- a/src/NServiceBus.AcceptanceTests/Pipeline/When_message_processing_fails.cs +++ b/src/NServiceBus.AcceptanceTests/Pipeline/When_message_processing_fails.cs @@ -18,11 +18,14 @@ public async Task Should_provide_additional_exception_information() .Done(c => c.MessageFailed) .Run(); - Assert.IsTrue(context.Exception.Data.Contains("Message type")); - Assert.IsTrue(context.Exception.Data.Contains("Handler type")); - Assert.IsTrue(context.Exception.Data.Contains("Handler start time")); - Assert.IsTrue(context.Exception.Data.Contains("Handler failure time")); - Assert.IsTrue(context.Exception.Data.Contains("Message ID")); + Assert.Multiple(() => + { + Assert.That(context.Exception.Data.Contains("Message type"), Is.True); + Assert.That(context.Exception.Data.Contains("Handler type"), Is.True); + Assert.That(context.Exception.Data.Contains("Handler start time"), Is.True); + Assert.That(context.Exception.Data.Contains("Handler failure time"), Is.True); + Assert.That(context.Exception.Data.Contains("Message ID"), Is.True); + }); // we can't assert for the native message ID as not every transport has uses a different ID internally } diff --git a/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_record_class_messages.cs b/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_record_class_messages.cs index 6fc58d26c6e..2a041a068c2 100644 --- a/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_record_class_messages.cs +++ b/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_record_class_messages.cs @@ -19,7 +19,7 @@ public async Task Should_process_record_message() .Done(c => c.ReceivedText != null) .Run(); - Assert.AreEqual(expectedText, context.ReceivedText); + Assert.That(context.ReceivedText, Is.EqualTo(expectedText)); } [Test] @@ -33,7 +33,7 @@ public async Task Should_process_positional_record_message() .Done(c => c.ReceivedText != null) .Run(); - Assert.AreEqual(expectedText, context.ReceivedText); + Assert.That(context.ReceivedText, Is.EqualTo(expectedText)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_record_struct_messages.cs b/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_record_struct_messages.cs index 474bf651069..8053c67f5af 100644 --- a/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_record_struct_messages.cs +++ b/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_record_struct_messages.cs @@ -19,7 +19,7 @@ public async Task Should_process_record_message() .Done(c => c.ReceivedText != null) .Run(); - Assert.AreEqual(expectedText, context.ReceivedText); + Assert.That(context.ReceivedText, Is.EqualTo(expectedText)); } [Test] @@ -33,7 +33,7 @@ public async Task Should_process_readonly_record_message() .Done(c => c.ReceivedText != null) .Run(); - Assert.AreEqual(expectedText, context.ReceivedText); + Assert.That(context.ReceivedText, Is.EqualTo(expectedText)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_to_another_endpoint.cs b/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_to_another_endpoint.cs index 48582b14228..c4625bdde83 100644 --- a/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_to_another_endpoint.cs +++ b/src/NServiceBus.AcceptanceTests/Pipeline/When_sending_to_another_endpoint.cs @@ -31,11 +31,14 @@ public async Task Should_receive_the_message() .Done(c => c.WasCalled) .Run(); - Assert.True(context.WasCalled, "The message handler should be called"); - Assert.AreEqual(1, context.TimesCalled, "The message handler should only be invoked once"); - Assert.AreEqual("StaticHeaderValue", context.ReceivedHeaders["MyStaticHeader"], "Static headers should be attached to outgoing messages"); - Assert.AreEqual("MyHeaderValue", context.MyHeader, "Static headers should be attached to outgoing messages"); - Assert.AreEqual("MyMessageId", context.MyMessageId, "MessageId should be applied to outgoing messages"); + Assert.Multiple(() => + { + Assert.That(context.WasCalled, Is.True, "The message handler should be called"); + Assert.That(context.TimesCalled, Is.EqualTo(1), "The message handler should only be invoked once"); + Assert.That(context.ReceivedHeaders["MyStaticHeader"], Is.EqualTo("StaticHeaderValue"), "Static headers should be attached to outgoing messages"); + Assert.That(context.MyHeader, Is.EqualTo("MyHeaderValue"), "Static headers should be attached to outgoing messages"); + Assert.That(context.MyMessageId, Is.EqualTo("MyMessageId"), "MessageId should be applied to outgoing messages"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/Cross_q_tx_msg_moved_to_error_q.cs b/src/NServiceBus.AcceptanceTests/Recoverability/Cross_q_tx_msg_moved_to_error_q.cs index ea70972e9b0..768f656924b 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/Cross_q_tx_msg_moved_to_error_q.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/Cross_q_tx_msg_moved_to_error_q.cs @@ -27,8 +27,11 @@ public async Task Should_not_dispatch_outgoing_messages() .Done(c => c.MessageMovedToErrorQueue) .Run(); - Assert.IsFalse(context.OutgoingMessageSent, "Outgoing messages should not be sent"); - Assert.IsTrue(!context.FailedMessages.IsEmpty); + Assert.Multiple(() => + { + Assert.That(context.OutgoingMessageSent, Is.False, "Outgoing messages should not be sent"); + Assert.That(!context.FailedMessages.IsEmpty, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/CustomPolicyDoes1DelayedRetryThenSendsToError.cs b/src/NServiceBus.AcceptanceTests/Recoverability/CustomPolicyDoes1DelayedRetryThenSendsToError.cs index b84e9cb0aa2..5dcf0601677 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/CustomPolicyDoes1DelayedRetryThenSendsToError.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/CustomPolicyDoes1DelayedRetryThenSendsToError.cs @@ -29,8 +29,8 @@ public async Task Should_execute_twice_and_send_to_error_queue() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.AreEqual(2, context.Count); - Assert.AreEqual(messageId, context.FailedMessages.Single().Value.Single().MessageId); + Assert.That(context.Count, Is.EqualTo(2)); + Assert.That(context.FailedMessages.Single().Value.Single().MessageId, Is.EqualTo(messageId)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_always_moves_to_error.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_always_moves_to_error.cs index 501dca99592..ffac7d7b33a 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_always_moves_to_error.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_always_moves_to_error.cs @@ -27,8 +27,8 @@ public async Task Should_execute_only_once_and_send_to_error_queue() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.AreEqual(1, context.Count); - Assert.AreEqual(messageId, context.FailedMessages.Single().Value.Single().MessageId); + Assert.That(context.Count, Is.EqualTo(1)); + Assert.That(context.FailedMessages.Single().Value.Single().MessageId, Is.EqualTo(messageId)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_discards_message.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_discards_message.cs index ca8fe7c11e2..d5bca01c6d9 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_discards_message.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_discards_message.cs @@ -16,8 +16,11 @@ public async Task Should_consume_message_without_retries() .Done(c => c.HandlerInvoked >= 1) .Run(); - Assert.IsEmpty(context.FailedMessages, "the message should not be moved to the error queue"); - Assert.AreEqual(1, context.HandlerInvoked, "the discarded message should not be retried"); + Assert.Multiple(() => + { + Assert.That(context.FailedMessages, Is.Empty, "the message should not be moved to the error queue"); + Assert.That(context.HandlerInvoked, Is.EqualTo(1), "the discarded message should not be retried"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_moves_to_overridden_error_queue.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_moves_to_overridden_error_queue.cs index bd8324c1467..f318f53fad9 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_moves_to_overridden_error_queue.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_custom_policy_moves_to_overridden_error_queue.cs @@ -24,7 +24,7 @@ public async Task Should_move_to_defined_error_queue() .Done(c => c.MessageMovedToErrorQueue) .Run(); - Assert.IsTrue(context.MessageMovedToErrorQueue); + Assert.That(context.MessageMovedToErrorQueue, Is.True); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_delayed_retries_with_immediate_retries_disabled.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_delayed_retries_with_immediate_retries_disabled.cs index 6c93777f5e6..814465db024 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_delayed_retries_with_immediate_retries_disabled.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_delayed_retries_with_immediate_retries_disabled.cs @@ -21,7 +21,7 @@ public async Task Should_reschedule_message_the_configured_number_of_times() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.AreEqual(ConfiguredNumberOfDelayedRetries + 1, context.ReceiveCount, "Message should be delivered 4 times. Once initially and retried 3 times by Delayed Retries"); + Assert.That(context.ReceiveCount, Is.EqualTo(ConfiguredNumberOfDelayedRetries + 1), "Message should be delivered 4 times. Once initially and retried 3 times by Delayed Retries"); } const int ConfiguredNumberOfDelayedRetries = 3; diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_error_is_overridden_in_code.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_error_is_overridden_in_code.cs index bf83b6484b8..129490c2960 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_error_is_overridden_in_code.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_error_is_overridden_in_code.cs @@ -18,7 +18,7 @@ public async Task Should_error_to_target_queue() .Done(c => c.MessageReceived) .Run(); - Assert.True(context.MessageReceived); + Assert.That(context.MessageReceived, Is.True); } public class UserEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_are_enabled.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_are_enabled.cs index f206fbef2db..263979ca143 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_are_enabled.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_are_enabled.cs @@ -19,10 +19,13 @@ public async Task Should_do_the_configured_number_of_retries() .Done(c => c.ForwardedToErrorQueue) .Run(); - Assert.True(context.ForwardedToErrorQueue); - Assert.AreEqual(numberOfRetries + 1, context.NumberOfTimesInvoked, "Message should be retried 5 times immediately"); - Assert.AreEqual(numberOfRetries, context.Logs.Count(l => l.Message - .StartsWith($"Immediate Retry is going to retry message '{context.MessageId}' because of an exception:"))); + Assert.Multiple(() => + { + Assert.That(context.ForwardedToErrorQueue, Is.True); + Assert.That(context.NumberOfTimesInvoked, Is.EqualTo(numberOfRetries + 1), "Message should be retried 5 times immediately"); + Assert.That(context.Logs.Count(l => l.Message + .StartsWith($"Immediate Retry is going to retry message '{context.MessageId}' because of an exception:")), Is.EqualTo(numberOfRetries)); + }); } const int numberOfRetries = 5; diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_disabled.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_disabled.cs index 2018d4c8e0f..4456cafdf6c 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_disabled.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_disabled.cs @@ -23,7 +23,7 @@ public async Task Should_not_retry_the_message_using_immediate_retries() .Done(c => c.GaveUp) .Run(); - Assert.AreEqual(1, context.NumberOfTimesInvoked, "No Immediate Retry should be in use if NumberOfRetries is set to 0"); + Assert.That(context.NumberOfTimesInvoked, Is.EqualTo(1), "No Immediate Retry should be in use if NumberOfRetries is set to 0"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_fail.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_fail.cs index 87e94a1aca6..14cf8101c76 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_fail.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_immediate_retries_fail.cs @@ -24,7 +24,7 @@ public async Task Should_do_delayed_retries() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.GreaterOrEqual(context.NumberOfRetriesAttempted, 1, "Should retry one or more times"); + Assert.That(context.NumberOfRetriesAttempted, Is.GreaterThanOrEqualTo(1), "Should retry one or more times"); } static TimeSpan Delay = TimeSpan.FromMilliseconds(1); diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_message_fails_retries.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_message_fails_retries.cs index 454afb4fc7d..e4f98bb4985 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_message_fails_retries.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_message_fails_retries.cs @@ -18,15 +18,18 @@ public void Should_forward_message_to_error_queue() .Done(c => !c.FailedMessages.IsEmpty) .Run()); - Assert.AreEqual(1, exception.ScenarioContext.FailedMessages.Count); + Assert.That(exception.ScenarioContext.FailedMessages, Has.Count.EqualTo(1)); var testContext = (Context)exception.ScenarioContext; - Assert.AreEqual(typeof(MessageWhichFailsRetries).AssemblyQualifiedName, exception.FailedMessage.Headers[Headers.EnclosedMessageTypes]); - Assert.AreEqual(testContext.PhysicalMessageId, exception.FailedMessage.MessageId); + Assert.Multiple(() => + { + Assert.That(exception.FailedMessage.Headers[Headers.EnclosedMessageTypes], Is.EqualTo(typeof(MessageWhichFailsRetries).AssemblyQualifiedName)); + Assert.That(exception.FailedMessage.MessageId, Is.EqualTo(testContext.PhysicalMessageId)); + }); Assert.IsAssignableFrom(typeof(SimulatedException), exception.FailedMessage.Exception); - Assert.AreEqual(1, testContext.Logs.Count(l => l.Message - .StartsWith($"Moving message '{testContext.PhysicalMessageId}' to the error queue 'error' because processing failed due to an exception:"))); + Assert.That(testContext.Logs.Count(l => l.Message + .StartsWith($"Moving message '{testContext.PhysicalMessageId}' to the error queue 'error' because processing failed due to an exception:")), Is.EqualTo(1)); } public class RetryEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_message_is_deferred_by_delayed_retries_using_dtc.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_message_is_deferred_by_delayed_retries_using_dtc.cs index 9f59a35a2c3..522e0812e72 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_message_is_deferred_by_delayed_retries_using_dtc.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_message_is_deferred_by_delayed_retries_using_dtc.cs @@ -27,8 +27,11 @@ public async Task Should_not_commit_distributed_transaction() .Done(c => !c.FailedMessages.IsEmpty) .Run(); - Assert.GreaterOrEqual(context.NumberOfRetriesAttempted, 3, "Should retry at least three times"); - Assert.That(context.TransactionStatuses, Is.All.Not.EqualTo(TransactionStatus.Committed)); + Assert.Multiple(() => + { + Assert.That(context.NumberOfRetriesAttempted, Is.GreaterThanOrEqualTo(3), "Should retry at least three times"); + Assert.That(context.TransactionStatuses, Is.All.Not.EqualTo(TransactionStatus.Committed)); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_message_with_TimeToBeReceived_fails.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_message_with_TimeToBeReceived_fails.cs index b07ee8e5d9a..6f5b95c45ca 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_message_with_TimeToBeReceived_fails.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_message_with_TimeToBeReceived_fails.cs @@ -26,8 +26,11 @@ public async Task Should_not_honor_TimeToBeReceived_for_error_message() .Done(c => c.MessageFailed && c.TTBRHasExpiredAndMessageIsStillInErrorQueue) .Run(); - Assert.IsTrue(context.MessageFailed); - Assert.IsTrue(context.TTBRHasExpiredAndMessageIsStillInErrorQueue); + Assert.Multiple(() => + { + Assert.That(context.MessageFailed, Is.True); + Assert.That(context.TTBRHasExpiredAndMessageIsStillInErrorQueue, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_non_transactional_message_is_moved_to_error_queue.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_non_transactional_message_is_moved_to_error_queue.cs index 9f50ef38287..3a0660e9595 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_non_transactional_message_is_moved_to_error_queue.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_non_transactional_message_is_moved_to_error_queue.cs @@ -27,7 +27,7 @@ public async Task Should_dispatch_outgoing_messages() .Done(c => c.MessageMovedToErrorQueue && c.OutgoingMessageSent) .Run(); - Assert.IsTrue(!context.FailedMessages.IsEmpty, "Messages should have failed"); + Assert.That(!context.FailedMessages.IsEmpty, Is.True, "Messages should have failed"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_receiveonly_message_is_moved_to_error_queue.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_receiveonly_message_is_moved_to_error_queue.cs index 20a745a8bf0..bceac303e57 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_receiveonly_message_is_moved_to_error_queue.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_receiveonly_message_is_moved_to_error_queue.cs @@ -27,7 +27,7 @@ public async Task Should_dispatch_outgoing_messages() .Done(c => c.MessageMovedToErrorQueue && c.OutgoingMessageSent) .Run(); - Assert.IsTrue(!context.FailedMessages.IsEmpty, "Messages should have failed"); + Assert.That(!context.FailedMessages.IsEmpty, Is.True, "Messages should have failed"); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_retrying_control_message_from_error_queue.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_retrying_control_message_from_error_queue.cs index bfdbd402eee..d31f04bd29e 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_retrying_control_message_from_error_queue.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_retrying_control_message_from_error_queue.cs @@ -28,7 +28,7 @@ public async Task Should_confirm_successful_processing() .Done(c => c.ConfirmedRetryId != null) .Run(); - Assert.AreEqual(RetryId, context.ConfirmedRetryId); + Assert.That(context.ConfirmedRetryId, Is.EqualTo(RetryId)); var processingTime = DateTimeOffsetHelper.ToDateTimeOffset(context.RetryProcessingTimestamp); Assert.That(processingTime, Is.EqualTo(DateTimeOffset.UtcNow).Within(TimeSpan.FromMinutes(1))); } diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_retrying_message_from_error_queue.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_retrying_message_from_error_queue.cs index 1f33bfe9cec..2c3b6cd7629 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_retrying_message_from_error_queue.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_retrying_message_from_error_queue.cs @@ -30,11 +30,17 @@ public async Task Should_confirm_successful_processing() .Done(c => c.ConfirmedRetryId != null && c.AuditHeaders != null) .Run(); - Assert.IsTrue(context.MessageProcessed); - Assert.AreEqual(context.RetryId, context.ConfirmedRetryId); + Assert.Multiple(() => + { + Assert.That(context.MessageProcessed, Is.True); + Assert.That(context.ConfirmedRetryId, Is.EqualTo(context.RetryId)); + }); var processingTime = DateTimeOffsetHelper.ToDateTimeOffset(context.RetryProcessingTimestamp); - Assert.That(processingTime, Is.EqualTo(DateTimeOffset.UtcNow).Within(TimeSpan.FromMinutes(1))); - Assert.IsTrue(context.AuditHeaders.ContainsKey("ServiceControl.Retry.AcknowledgementSent")); + Assert.Multiple(() => + { + Assert.That(processingTime, Is.EqualTo(DateTimeOffset.UtcNow).Within(TimeSpan.FromMinutes(1))); + Assert.That(context.AuditHeaders.ContainsKey("ServiceControl.Retry.AcknowledgementSent"), Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_transactionscope_message_is_moved_to_error_queue.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_transactionscope_message_is_moved_to_error_queue.cs index 979570acd44..e7ad5ecd0e3 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_transactionscope_message_is_moved_to_error_queue.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_transactionscope_message_is_moved_to_error_queue.cs @@ -27,8 +27,11 @@ public async Task Should_not_dispatch_outgoing_messages() .Done(c => c.MessageMovedToErrorQueue) .Run(); - Assert.IsFalse(context.OutgoingMessageSent, "Outgoing messages should not be sent"); - Assert.IsTrue(!context.FailedMessages.IsEmpty, "There should be failed messages registered in this scenario"); + Assert.Multiple(() => + { + Assert.That(context.OutgoingMessageSent, Is.False, "Outgoing messages should not be sent"); + Assert.That(!context.FailedMessages.IsEmpty, Is.True, "There should be failed messages registered in this scenario"); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Extend_event_routing.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Extend_event_routing.cs index 31a1c0f6805..f351e18bad2 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Extend_event_routing.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Extend_event_routing.cs @@ -26,7 +26,7 @@ public async Task Should_route_events_correctly() .Done(c => c.MessageDelivered) .Run(); - Assert.True(context.MessageDelivered); + Assert.That(context.MessageDelivered, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Missing_pub_info.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Missing_pub_info.cs index ffa231c7c22..d29a0ed5baa 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Missing_pub_info.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Missing_pub_info.cs @@ -20,12 +20,15 @@ public async Task Should_log_events_with_missing_routes() .Done(c => c.EndpointsStarted) .Run(); - Assert.True(context.EndpointsStarted, "because it should not prevent endpoint startup"); + Assert.That(context.EndpointsStarted, Is.True, "because it should not prevent endpoint startup"); var log = context.Logs.Single(l => l.Message.Contains($"AutoSubscribe was unable to subscribe to an event:")); - Assert.AreEqual(LogLevel.Error, log.Level); - Assert.AreEqual(typeof(AutoSubscribe).FullName, log.LoggerName); - StringAssert.Contains($"No publisher address could be found for message type '{typeof(MyEvent).FullName}'.", log.Message); + Assert.Multiple(() => + { + Assert.That(log.Level, Is.EqualTo(LogLevel.Error)); + Assert.That(log.LoggerName, Is.EqualTo(typeof(AutoSubscribe).FullName)); + }); + Assert.That(log.Message, Does.Contain($"No publisher address could be found for message type '{typeof(MyEvent).FullName}'.")); } public class Subscriber : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Multi_sub_to_poly_event.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Multi_sub_to_poly_event.cs index 8c103b4aac3..3fe913d766a 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Multi_sub_to_poly_event.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Multi_sub_to_poly_event.cs @@ -33,8 +33,11 @@ public async Task Both_events_should_be_delivered() .Done(c => c.SubscriberGotIMyEvent && c.SubscriberGotMyEvent2) .Run(); - Assert.True(context.SubscriberGotIMyEvent); - Assert.True(context.SubscriberGotMyEvent2); + Assert.Multiple(() => + { + Assert.That(context.SubscriberGotIMyEvent, Is.True); + Assert.That(context.SubscriberGotMyEvent2, Is.True); + }); } diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Pub_from_sendonly.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Pub_from_sendonly.cs index a93bef3ba45..cdf450864ce 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Pub_from_sendonly.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Pub_from_sendonly.cs @@ -29,7 +29,7 @@ public async Task Should_be_delivered_to_all_subscribers() .Done(c => c.SubscriberGotTheEvent) .Run(); - Assert.True(context.SubscriberGotTheEvent); + Assert.That(context.SubscriberGotTheEvent, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Pub_to_scaled_out_subs.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Pub_to_scaled_out_subs.cs index 44c7bcce96c..2906fd40106 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Pub_to_scaled_out_subs.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Pub_to_scaled_out_subs.cs @@ -22,8 +22,11 @@ public async Task Each_event_should_be_delivered_to_single_instance_of_each_subs .Done(c => c.ProcessedByA > 0 && c.ProcessedByB > 0) .Run(); - Assert.AreEqual(1, context.ProcessedByA); - Assert.AreEqual(1, context.ProcessedByB); + Assert.Multiple(() => + { + Assert.That(context.ProcessedByA, Is.EqualTo(1)); + Assert.That(context.ProcessedByB, Is.EqualTo(1)); + }); } diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_base_event.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_base_event.cs index c80f7993e1c..9a62f6f4132 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_base_event.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_base_event.cs @@ -23,8 +23,11 @@ public async Task Both_base_and_specific_events_should_be_delivered() .Done(c => c.SubscriberGotBaseEvent && c.SubscriberGotSpecificEvent) .Run(); - Assert.True(context.SubscriberGotBaseEvent); - Assert.True(context.SubscriberGotSpecificEvent); + Assert.Multiple(() => + { + Assert.That(context.SubscriberGotBaseEvent, Is.True); + Assert.That(context.SubscriberGotSpecificEvent, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_derived_event.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_derived_event.cs index ebe63fdbf38..d6913755a87 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_derived_event.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_derived_event.cs @@ -24,7 +24,7 @@ public async Task Base_event_should_not_be_delivered() .Done(c => c.Done) .Run(); - Assert.IsFalse(context.SubscriberGotEvent); + Assert.That(context.SubscriberGotEvent, Is.False); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_multiple_pubs.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_multiple_pubs.cs index 12adedd565b..611c7a507c8 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_multiple_pubs.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_multiple_pubs.cs @@ -31,8 +31,11 @@ public async Task Should_subscribe_to_all_registered_publishers_of_same_type() .Done(c => c.SubscribedToPublisher1 && c.SubscribedToPublisher2) .Run(); - Assert.That(context.SubscribedToPublisher1, Is.True); - Assert.That(context.SubscribedToPublisher2, Is.True); + Assert.Multiple(() => + { + Assert.That(context.SubscribedToPublisher1, Is.True); + Assert.That(context.SubscribedToPublisher2, Is.True); + }); } diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_scaled_out_pubs.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_scaled_out_pubs.cs index 497cab5b35e..5f9fec4349e 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_scaled_out_pubs.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Sub_to_scaled_out_pubs.cs @@ -26,7 +26,7 @@ public async Task Should_send_subscription_message_to_each_instance() // each instance should receive a subscription message Assert.That(context.PublisherReceivedSubscription, Does.Contain("1")); Assert.That(context.PublisherReceivedSubscription, Does.Contain("2")); - Assert.That(context.PublisherReceivedSubscription.Count, Is.EqualTo(2)); + Assert.That(context.PublisherReceivedSubscription, Has.Count.EqualTo(2)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Unsub_from_event.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Unsub_from_event.cs index 65921bc5547..22aeac4eebd 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Unsub_from_event.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Unsub_from_event.cs @@ -38,9 +38,12 @@ public async Task Should_no_longer_receive_event() .Done(c => c.Subscriber1ReceivedMessages >= 4) .Run(); - Assert.AreEqual(4, context.Subscriber1ReceivedMessages); - Assert.AreEqual(1, context.Subscriber2ReceivedMessages); - Assert.IsTrue(context.Subscriber2Unsubscribed); + Assert.Multiple(() => + { + Assert.That(context.Subscriber1ReceivedMessages, Is.EqualTo(4)); + Assert.That(context.Subscriber2ReceivedMessages, Is.EqualTo(1)); + Assert.That(context.Subscriber2Unsubscribed, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Unsub_from_scaled_out_pubs.cs b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Unsub_from_scaled_out_pubs.cs index 5c62279ac37..16180732548 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Unsub_from_scaled_out_pubs.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/MessageDrivenSubscriptions/Unsub_from_scaled_out_pubs.cs @@ -26,7 +26,7 @@ public async Task Should_send_unsubscribe_message_to_each_instance() // each instance should receive an unsubscribe message Assert.That(context.PublisherReceivedUnsubscribeMessage, Does.Contain("1")); Assert.That(context.PublisherReceivedUnsubscribeMessage, Does.Contain("2")); - Assert.That(context.PublisherReceivedUnsubscribeMessage.Count, Is.EqualTo(2)); + Assert.That(context.PublisherReceivedUnsubscribeMessage, Has.Count.EqualTo(2)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/MultiSubscribeToPolymorphicEvent.cs b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/MultiSubscribeToPolymorphicEvent.cs index a7ef97070f9..915338e6662 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/MultiSubscribeToPolymorphicEvent.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/MultiSubscribeToPolymorphicEvent.cs @@ -27,8 +27,11 @@ public async Task Both_events_should_be_delivered() .Done(c => c.SubscriberGotIMyEvent && c.SubscriberGotMyEvent2) .Run(); - Assert.True(context.SubscriberGotIMyEvent); - Assert.True(context.SubscriberGotMyEvent2); + Assert.Multiple(() => + { + Assert.That(context.SubscriberGotIMyEvent, Is.True); + Assert.That(context.SubscriberGotMyEvent2, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_publishing_from_sendonly.cs b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_publishing_from_sendonly.cs index c480e89955c..7c3b2d0021c 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_publishing_from_sendonly.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_publishing_from_sendonly.cs @@ -19,7 +19,7 @@ public async Task Should_be_delivered_to_all_subscribers() .Done(c => c.SubscriberGotTheEvent) .Run(); - Assert.True(context.SubscriberGotTheEvent); + Assert.That(context.SubscriberGotTheEvent, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_publishing_to_scaled_out_subscribers.cs b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_publishing_to_scaled_out_subscribers.cs index f929bbc6bb2..23d85070011 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_publishing_to_scaled_out_subscribers.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_publishing_to_scaled_out_subscribers.cs @@ -23,8 +23,11 @@ public async Task Should_route_event_to_shared_queue() .Done(c => c.SubscriberACounter > 0 && c.SubscriberBCounter > 0) .Run(); - Assert.AreEqual(1, context.SubscriberACounter); - Assert.AreEqual(1, context.SubscriberBCounter); + Assert.Multiple(() => + { + Assert.That(context.SubscriberACounter, Is.EqualTo(1)); + Assert.That(context.SubscriberBCounter, Is.EqualTo(1)); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_subscribing_to_a_base_event.cs b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_subscribing_to_a_base_event.cs index 43560553045..55f8a9bbc45 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_subscribing_to_a_base_event.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_subscribing_to_a_base_event.cs @@ -27,8 +27,11 @@ public async Task Both_base_and_specific_events_should_be_delivered() .Done(c => c.SubscriberGotBaseEvent && c.SubscriberGotSpecificEvent) .Run(); - Assert.True(context.SubscriberGotBaseEvent); - Assert.True(context.SubscriberGotSpecificEvent); + Assert.Multiple(() => + { + Assert.That(context.SubscriberGotBaseEvent, Is.True); + Assert.That(context.SubscriberGotSpecificEvent, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_subscribing_to_a_derived_event.cs b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_subscribing_to_a_derived_event.cs index ecc4e51077a..b677dc98598 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_subscribing_to_a_derived_event.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_subscribing_to_a_derived_event.cs @@ -28,7 +28,7 @@ public async Task Base_event_should_not_be_delivered() .Done(c => c.Done) .Run(); - Assert.IsFalse(context.SubscriberGotEvent); + Assert.That(context.SubscriberGotEvent, Is.False); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_unsubscribing_from_event.cs b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_unsubscribing_from_event.cs index da5fc73ba59..4cc2275f7f4 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_unsubscribing_from_event.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/NativePublishSubscribe/When_unsubscribing_from_event.cs @@ -49,9 +49,12 @@ public async Task Should_no_longer_receive_event() .Done(c => c.Subscriber1ReceivedMessages >= 4) .Run(); - Assert.AreEqual(4, context.Subscriber1ReceivedMessages); - Assert.AreEqual(1, context.Subscriber2ReceivedMessages); - Assert.IsTrue(context.Subscriber2Unsubscribed); + Assert.Multiple(() => + { + Assert.That(context.Subscriber1ReceivedMessages, Is.EqualTo(4)); + Assert.That(context.Subscriber2ReceivedMessages, Is.EqualTo(1)); + Assert.That(context.Subscriber2Unsubscribed, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_base_event_from_2_publishers.cs b/src/NServiceBus.AcceptanceTests/Routing/When_base_event_from_2_publishers.cs index 0e47888a1f9..bfdb6c64789 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_base_event_from_2_publishers.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_base_event_from_2_publishers.cs @@ -33,8 +33,11 @@ public async Task Should_receive_events_from_all_publishers() .Done(c => c.GotTheEventFromPublisher1 && c.GotTheEventFromPublisher2) .Run(); - Assert.True(context.GotTheEventFromPublisher1); - Assert.True(context.GotTheEventFromPublisher2); + Assert.Multiple(() => + { + Assert.That(context.GotTheEventFromPublisher1, Is.True); + Assert.That(context.GotTheEventFromPublisher2, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_extending_command_routing.cs b/src/NServiceBus.AcceptanceTests/Routing/When_extending_command_routing.cs index 59c8b0ff3fd..50129a1c8c3 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_extending_command_routing.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_extending_command_routing.cs @@ -32,7 +32,7 @@ public async Task Should_route_commands_correctly() .Done(c => c.MessageDelivered >= 4) .Run(); - Assert.IsTrue(ctx.MessageDelivered >= 4); + Assert.That(ctx.MessageDelivered, Is.GreaterThanOrEqualTo(4)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_making_endpoint_uniquely_addressable.cs b/src/NServiceBus.AcceptanceTests/Routing/When_making_endpoint_uniquely_addressable.cs index 42e27277cc5..8702114b6ee 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_making_endpoint_uniquely_addressable.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_making_endpoint_uniquely_addressable.cs @@ -25,7 +25,7 @@ public async Task Should_be_addressable_both_by_shared_queue_and_unique_queue() .Done(c => c.MessagesReceived > 1) .Run(); - Assert.AreEqual(2, context.MessagesReceived); + Assert.That(context.MessagesReceived, Is.EqualTo(2)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_multiple_mappings_exists.cs b/src/NServiceBus.AcceptanceTests/Routing/When_multiple_mappings_exists.cs index 6d03bb0b7c0..91e25ab709f 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_multiple_mappings_exists.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_multiple_mappings_exists.cs @@ -18,8 +18,11 @@ public async Task First_registration_should_be_the_final_destination() .Done(c => c.WasCalled1 || c.WasCalled2) .Run(); - Assert.IsTrue(context.WasCalled1); - Assert.IsFalse(context.WasCalled2); + Assert.Multiple(() => + { + Assert.That(context.WasCalled1, Is.True); + Assert.That(context.WasCalled2, Is.False); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_overriding_local_address.cs b/src/NServiceBus.AcceptanceTests/Routing/When_overriding_local_address.cs index 1bfd4d2f464..f840577801f 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_overriding_local_address.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_overriding_local_address.cs @@ -38,7 +38,7 @@ public void Should_not_be_allowed_when_send_only() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains("send-only", ex.Message); + Assert.That(ex.Message, Does.Contain("send-only")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_publishing.cs b/src/NServiceBus.AcceptanceTests/Routing/When_publishing.cs index 263c7110078..69daa1b6b6f 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_publishing.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_publishing.cs @@ -29,7 +29,7 @@ public async Task Issue_1851() .Done(c => c.Subscriber3GotTheEvent) .Run(); - Assert.True(context.Subscriber3GotTheEvent); + Assert.That(context.Subscriber3GotTheEvent, Is.True); } [Test] @@ -77,9 +77,12 @@ public async Task Should_be_delivered_to_all_subscribers() .Done(c => c.Subscriber1GotTheEvent && c.Subscriber2GotTheEvent) .Run(TimeSpan.FromSeconds(10)); - Assert.True(context.Subscriber1GotTheEvent); - Assert.True(context.Subscriber2GotTheEvent); - Assert.AreEqual("SomeValue", context.HeaderValue); + Assert.Multiple(() => + { + Assert.That(context.Subscriber1GotTheEvent, Is.True); + Assert.That(context.Subscriber2GotTheEvent, Is.True); + Assert.That(context.HeaderValue, Is.EqualTo("SomeValue")); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_event_implementing_two_unrelated_interfaces.cs b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_event_implementing_two_unrelated_interfaces.cs index df0a1f5685b..f8ee789b3c9 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_event_implementing_two_unrelated_interfaces.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_event_implementing_two_unrelated_interfaces.cs @@ -37,8 +37,11 @@ public async Task Event_should_be_published_using_instance_type() .Done(c => c.GotEventA && c.GotEventB) .Run(TimeSpan.FromSeconds(20)); - Assert.True(context.GotEventA); - Assert.True(context.GotEventB); + Assert.Multiple(() => + { + Assert.That(context.GotEventA, Is.True); + Assert.That(context.GotEventB, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_interface.cs b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_interface.cs index 40e94c5e0a0..efff6540e9a 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_interface.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_interface.cs @@ -28,8 +28,11 @@ public async Task Should_receive_event() .Done(c => c.GotTheEvent) .Run(); - Assert.True(context.GotTheEvent); - Assert.AreEqual(typeof(IMyEvent), context.EventTypePassedToRouting); + Assert.Multiple(() => + { + Assert.That(context.GotTheEvent, Is.True); + Assert.That(context.EventTypePassedToRouting, Is.EqualTo(typeof(IMyEvent))); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_interface_with_unobtrusive.cs b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_interface_with_unobtrusive.cs index 7d9cd52ed15..c8b4da9c91b 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_interface_with_unobtrusive.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_an_interface_with_unobtrusive.cs @@ -28,8 +28,11 @@ public async Task Should_receive_event() .Done(c => c.GotTheEvent) .Run(); - Assert.True(context.GotTheEvent); - Assert.AreEqual(typeof(IMyEvent), context.EventTypePassedToRouting); + Assert.Multiple(() => + { + Assert.That(context.GotTheEvent, Is.True); + Assert.That(context.EventTypePassedToRouting, Is.EqualTo(typeof(IMyEvent))); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_pre_created_interface.cs b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_pre_created_interface.cs index da85b55a759..06c19ff6eaa 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_pre_created_interface.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_pre_created_interface.cs @@ -28,8 +28,11 @@ public async Task Should_publish_event_to_interface_type_subscribers() .Done(c => c.GotTheEvent) .Run(); - Assert.True(context.GotTheEvent); - Assert.AreEqual(typeof(IMyEvent), context.EventTypePassedToRouting); + Assert.Multiple(() => + { + Assert.That(context.GotTheEvent, Is.True); + Assert.That(context.EventTypePassedToRouting, Is.EqualTo(typeof(IMyEvent))); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_using_base_type.cs b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_using_base_type.cs index c55e5997554..958a8509175 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_using_base_type.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_using_base_type.cs @@ -33,7 +33,7 @@ public async Task Event_should_be_published_using_instance_type() .Done(c => c.Subscriber1GotTheEvent) .Run(TimeSpan.FromSeconds(20)); - Assert.True(context.Subscriber1GotTheEvent); + Assert.That(context.Subscriber1GotTheEvent, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_with_overridden_local_address.cs b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_with_overridden_local_address.cs index eb4bc6e1c54..e80ccbad4db 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_publishing_with_overridden_local_address.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_publishing_with_overridden_local_address.cs @@ -27,7 +27,7 @@ public async Task Should_be_delivered_to_all_subscribers() .Done(c => c.Subscriber1GotTheEvent) .Run(); - Assert.True(context.Subscriber1GotTheEvent); + Assert.That(context.Subscriber1GotTheEvent, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_registering_publishers_unobtrusive_messages_code.cs b/src/NServiceBus.AcceptanceTests/Routing/When_registering_publishers_unobtrusive_messages_code.cs index 545ba0d2a10..271bcf48643 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_registering_publishers_unobtrusive_messages_code.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_registering_publishers_unobtrusive_messages_code.cs @@ -19,8 +19,11 @@ public async Task Should_deliver_event() .Done(c => c.ReceivedMessage) .Run(); - Assert.That(context.Subscribed, Is.True); - Assert.That(context.ReceivedMessage, Is.True); + Assert.Multiple(() => + { + Assert.That(context.Subscribed, Is.True); + Assert.That(context.ReceivedMessage, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_registering_publishers_unobtrusive_messages_config.cs b/src/NServiceBus.AcceptanceTests/Routing/When_registering_publishers_unobtrusive_messages_config.cs index 0c7b73abf21..5d8d41ca1fe 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_registering_publishers_unobtrusive_messages_config.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_registering_publishers_unobtrusive_messages_config.cs @@ -19,8 +19,11 @@ public async Task Should_deliver_event() .Done(c => c.ReceivedMessage) .Run(); - Assert.That(context.Subscribed, Is.True); - Assert.That(context.ReceivedMessage, Is.True); + Assert.Multiple(() => + { + Assert.That(context.Subscribed, Is.True); + Assert.That(context.ReceivedMessage, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_replying_to_message.cs b/src/NServiceBus.AcceptanceTests/Routing/When_replying_to_message.cs index 4ad748970a7..2ef24b799ae 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_replying_to_message.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_replying_to_message.cs @@ -20,8 +20,11 @@ public async Task Should_reply_to_originator() .Done(c => c.SendingEndpointGotResponse) .Run(); - Assert.IsTrue(ctx.SendingEndpointGotResponse); - Assert.IsFalse(ctx.OtherEndpointGotResponse); + Assert.Multiple(() => + { + Assert.That(ctx.SendingEndpointGotResponse, Is.True); + Assert.That(ctx.OtherEndpointGotResponse, Is.False); + }); } [Test] @@ -37,8 +40,8 @@ public async Task Should_reply_to_shared_queue_by_default() .Done(c => c.SendingEndpointGotResponse) .Run(); - Assert.IsTrue(ctx.SendingEndpointGotResponse); - StringAssert.DoesNotContain(instanceDiscriminator, ctx.ReplyToAddress); + Assert.That(ctx.SendingEndpointGotResponse, Is.True); + Assert.That(ctx.ReplyToAddress, Does.Not.Contain(instanceDiscriminator)); } [Test] @@ -53,8 +56,11 @@ public async Task Should_reply_to_configured_return_address() .Done(c => c.OtherEndpointGotResponse) .Run(); - Assert.IsTrue(ctx.OtherEndpointGotResponse); - Assert.IsFalse(ctx.SendingEndpointGotResponse); + Assert.Multiple(() => + { + Assert.That(ctx.OtherEndpointGotResponse, Is.True); + Assert.That(ctx.SendingEndpointGotResponse, Is.False); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_replying_to_message_with_interface_and_unobtrusive.cs b/src/NServiceBus.AcceptanceTests/Routing/When_replying_to_message_with_interface_and_unobtrusive.cs index e9bb9f3c132..57fb4241ddd 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_replying_to_message_with_interface_and_unobtrusive.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_replying_to_message_with_interface_and_unobtrusive.cs @@ -19,8 +19,11 @@ public async Task Should_reply_to_originator() .Done(c => c.SendingEndpointGotResponse) .Run(); - Assert.IsTrue(ctx.SendingEndpointGotResponse); - Assert.IsFalse(ctx.OtherEndpointGotResponse); + Assert.Multiple(() => + { + Assert.That(ctx.SendingEndpointGotResponse, Is.True); + Assert.That(ctx.OtherEndpointGotResponse, Is.False); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_any_instance.cs b/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_any_instance.cs index 1cef8806f39..137f4e85e8a 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_any_instance.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_any_instance.cs @@ -24,8 +24,8 @@ public async Task Should_route_reply_to_shared_queue() .Done(c => c.ReplyReceived) .Run(); - Assert.IsTrue(context.ReplyReceived); - StringAssert.DoesNotContain(instanceDiscriminator, context.ReplyToAddress); + Assert.That(context.ReplyReceived, Is.True); + Assert.That(context.ReplyToAddress, Does.Not.Contain(instanceDiscriminator)); } const string instanceDiscriminator = "instance-42"; diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_specific_address.cs b/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_specific_address.cs index 283b6b60dcc..da80741b08f 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_specific_address.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_specific_address.cs @@ -27,8 +27,8 @@ public async Task Should_route_reply_to_instance_specific_queue() .Done(c => c.ReplyReceived) .Run(); - Assert.IsTrue(context.ReplyReceived); - StringAssert.Contains(replyHandlerAddress, context.ReplyToAddress); + Assert.That(context.ReplyReceived, Is.True); + Assert.That(context.ReplyToAddress, Does.Contain(replyHandlerAddress)); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_specific_instance.cs b/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_specific_instance.cs index 6604d89356c..adcffae3704 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_specific_instance.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_routing_reply_to_specific_instance.cs @@ -24,8 +24,8 @@ public async Task Should_route_reply_to_instance_specific_queue() .Done(c => c.ReplyReceived) .Run(); - Assert.IsTrue(context.ReplyReceived); - StringAssert.Contains(instanceDiscriminator, context.ReplyToAddress); + Assert.That(context.ReplyReceived, Is.True); + Assert.That(context.ReplyToAddress, Does.Contain(instanceDiscriminator)); } const string instanceDiscriminator = "instance-42"; diff --git a/src/NServiceBus.AcceptanceTests/Routing/When_using_custom_routing_strategy.cs b/src/NServiceBus.AcceptanceTests/Routing/When_using_custom_routing_strategy.cs index d9bfd00e9a0..0781db537fc 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/When_using_custom_routing_strategy.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/When_using_custom_routing_strategy.cs @@ -33,8 +33,11 @@ public async Task Should_route_commands_correctly() .Done(c => c.MessageDeliveredReceiver1 >= 3 && c.MessageDeliveredReceiver2 >= 1) .Run(); - Assert.AreEqual(3, ctx.MessageDeliveredReceiver1); - Assert.AreEqual(1, ctx.MessageDeliveredReceiver2); + Assert.Multiple(() => + { + Assert.That(ctx.MessageDeliveredReceiver1, Is.EqualTo(3)); + Assert.That(ctx.MessageDeliveredReceiver2, Is.EqualTo(1)); + }); } static string Discriminator1 = "553E9649"; diff --git a/src/NServiceBus.AcceptanceTests/Routing/when_replying_to_a_message_sent_to_specific_instance.cs b/src/NServiceBus.AcceptanceTests/Routing/when_replying_to_a_message_sent_to_specific_instance.cs index 164ef3e458e..40eaf92beac 100644 --- a/src/NServiceBus.AcceptanceTests/Routing/when_replying_to_a_message_sent_to_specific_instance.cs +++ b/src/NServiceBus.AcceptanceTests/Routing/when_replying_to_a_message_sent_to_specific_instance.cs @@ -22,7 +22,7 @@ public async Task Reply_address_should_be_set_to_shared_endpoint_queue() .Done(c => c.ReplyToAddress != null) .Run(); - StringAssert.DoesNotContain("XZY", context.ReplyToAddress); + Assert.That(context.ReplyToAddress, Does.Not.Contain("XZY")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_an_endpoint_replies_to_a_saga.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_an_endpoint_replies_to_a_saga.cs index 6a520ef46ea..d37a7b19fc6 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_an_endpoint_replies_to_a_saga.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_an_endpoint_replies_to_a_saga.cs @@ -23,7 +23,7 @@ public async Task Should_correlate_all_saga_messages_properly() .Done(c => c.Done) .Run(); - Assert.AreEqual(context.RunId, context.ResponseRunId); + Assert.That(context.ResponseRunId, Is.EqualTo(context.RunId)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_correlated_property_value_is_changed.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_correlated_property_value_is_changed.cs index 53e0ee33ca9..7eefa72ea47 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_correlated_property_value_is_changed.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_correlated_property_value_is_changed.cs @@ -23,10 +23,10 @@ await Scenario.Define() .Done(c => c.ModifiedCorrelationProperty) .Run()); - Assert.AreEqual(1, exception.ScenarioContext.FailedMessages.Count); - StringAssert.Contains( - "Changing the value of correlated properties at runtime is currently not supported", - exception.FailedMessage.Exception.Message); + Assert.That(exception.ScenarioContext.FailedMessages, Has.Count.EqualTo(1)); + Assert.That( + exception.FailedMessage.Exception.Message, + Does.Contain("Changing the value of correlated properties at runtime is currently not supported")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_correlating_on_special_characters.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_correlating_on_special_characters.cs index bee6b25506c..f888f05bc4f 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_correlating_on_special_characters.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_correlating_on_special_characters.cs @@ -21,7 +21,7 @@ public async Task Saga_persistence_and_correlation_should_work() .Done(c => c.RehydratedValueForCorrelatedHandler != null) .Run(); - Assert.AreEqual(propertyValue, context.RehydratedValueForCorrelatedHandler); + Assert.That(context.RehydratedValueForCorrelatedHandler, Is.EqualTo(propertyValue)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_guid.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_guid.cs index eb71e6fb20d..7d57c84918b 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_guid.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_guid.cs @@ -22,8 +22,11 @@ public async Task Show_allow_default() .Done(c => c.MessageCorrelated) .Run(); - Assert.That(context.MessageCorrelated, Is.True); - Assert.That(context.CorrelatedId, Is.EqualTo(default(Guid))); + Assert.Multiple(() => + { + Assert.That(context.MessageCorrelated, Is.True); + Assert.That(context.CorrelatedId, Is.EqualTo(default(Guid))); + }); } public class MessageWithGuidCorrelationProperty : IMessage diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_int.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_int.cs index 2f26eef1814..5073d3ae3a5 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_int.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_int.cs @@ -21,8 +21,11 @@ public async Task Show_allow_default() .Done(c => c.MessageCorrelated) .Run(); - Assert.That(context.MessageCorrelated, Is.True); - Assert.That(context.CorrelatedId, Is.EqualTo(default(int))); + Assert.Multiple(() => + { + Assert.That(context.MessageCorrelated, Is.True); + Assert.That(context.CorrelatedId, Is.EqualTo(default(int))); + }); } public class MessageWithIntCorrelationProperty : IMessage diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_null.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_null.cs index 7c0fe4946e2..13fd367bd73 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_null.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_correlation_property_is_null.cs @@ -23,7 +23,7 @@ public void Should_throw_an_exception_with_details() var errorMessage = $"Message {typeof(MessageWithNullCorrelationProperty).FullName} mapped to saga {typeof(SagaWithCorrelationPropertyEndpoint.SagaWithCorrelatedProperty).FullName} has attempted to assign null to the correlation property {nameof(SagaWithCorrelationPropertyEndpoint.SagaDataWithCorrelatedProperty.CorrelatedProperty)}. Correlation properties cannot be assigned null."; - StringAssert.Contains(errorMessage, exception.FailedMessage.Exception.Message); + Assert.That(exception.FailedMessage.Exception.Message, Does.Contain(errorMessage)); } public class SagaWithCorrelationPropertyEndpoint : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_doing_request_response_between_sagas.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_doing_request_response_between_sagas.cs index da3a4737a47..a3287449a08 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_doing_request_response_between_sagas.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_doing_request_response_between_sagas.cs @@ -16,7 +16,7 @@ public async Task Should_autocorrelate_the_response_back_to_the_requesting_saga( .Done(c => c.DidRequestingSagaGetTheResponse) .Run(); - Assert.True(context.DidRequestingSagaGetTheResponse); + Assert.That(context.DidRequestingSagaGetTheResponse, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_handling_concurrent_messages.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_handling_concurrent_messages.cs index 7368212c83e..5029da2fe54 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_handling_concurrent_messages.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_handling_concurrent_messages.cs @@ -36,12 +36,12 @@ public async Task Should_not_overwrite_each_other(bool useOutbox) .Done(c => c.SagaData != null) .Run(); - Assert.IsNotNull(context.SagaData); - Assert.AreEqual(3, context.SagaData.ContinueCount); + Assert.That(context.SagaData, Is.Not.Null); + Assert.That(context.SagaData.ContinueCount, Is.EqualTo(3)); - StringAssert.Contains("1", context.SagaData.CollectedIndexes); - StringAssert.Contains("2", context.SagaData.CollectedIndexes); - StringAssert.Contains("3", context.SagaData.CollectedIndexes); + Assert.That(context.SagaData.CollectedIndexes, Does.Contain("1")); + Assert.That(context.SagaData.CollectedIndexes, Does.Contain("2")); + Assert.That(context.SagaData.CollectedIndexes, Does.Contain("3")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_message_has_a_saga_id.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_message_has_a_saga_id.cs index 9df1114441f..ae1dd388740 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_message_has_a_saga_id.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_message_has_a_saga_id.cs @@ -29,9 +29,12 @@ public async Task Should_not_start_a_new_saga_if_not_found() .Done(c => c.Done) .Run(); - Assert.True(context.NotFoundHandlerCalled); - Assert.False(context.MessageHandlerCalled); - Assert.False(context.TimeoutHandlerCalled); + Assert.Multiple(() => + { + Assert.That(context.NotFoundHandlerCalled, Is.True); + Assert.That(context.MessageHandlerCalled, Is.False); + Assert.That(context.TimeoutHandlerCalled, Is.False); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_receiving_multiple_timeouts.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_receiving_multiple_timeouts.cs index 5a1db7c4d32..3b4db95219e 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_receiving_multiple_timeouts.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_receiving_multiple_timeouts.cs @@ -23,9 +23,12 @@ public async Task It_should_not_invoke_SagaNotFound_handler() .Done(c => (c.Saga1TimeoutFired && c.Saga2TimeoutFired) || c.SagaNotFound) .Run(TimeSpan.FromSeconds(60)); - Assert.IsFalse(context.SagaNotFound); - Assert.IsTrue(context.Saga1TimeoutFired); - Assert.IsTrue(context.Saga2TimeoutFired); + Assert.Multiple(() => + { + Assert.That(context.SagaNotFound, Is.False); + Assert.That(context.Saga1TimeoutFired, Is.True); + Assert.That(context.Saga2TimeoutFired, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_reply_from_saga_not_found_handler.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_reply_from_saga_not_found_handler.cs index d0ce1fa83bb..1435afe5ad2 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_reply_from_saga_not_found_handler.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_reply_from_saga_not_found_handler.cs @@ -21,10 +21,13 @@ public async Task It_should_invoke_message_handler() .Done(c => c.ReplyReceived) .Run(); - Assert.IsTrue(context.Logs.Any(m => m.Message.Equals("Could not find a started saga of 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+ReceiverWithSaga+NotFoundHandlerSaga1' for message type 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+MessageToSaga'."))); - Assert.IsTrue(context.Logs.Any(m => m.Message.Equals("Could not find a started saga of 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+ReceiverWithSaga+NotFoundHandlerSaga2' for message type 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+MessageToSaga'."))); - Assert.IsTrue(context.Logs.Count(m => m.Message.Equals("Could not find any started sagas for message type 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+MessageToSaga'. Going to invoke SagaNotFoundHandlers.")) == 1); - Assert.IsTrue(context.ReplyReceived); + Assert.Multiple(() => + { + Assert.That(context.Logs.Any(m => m.Message.Equals("Could not find a started saga of 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+ReceiverWithSaga+NotFoundHandlerSaga1' for message type 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+MessageToSaga'.")), Is.True); + Assert.That(context.Logs.Any(m => m.Message.Equals("Could not find a started saga of 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+ReceiverWithSaga+NotFoundHandlerSaga2' for message type 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+MessageToSaga'.")), Is.True); + Assert.That(context.Logs.Count(m => m.Message.Equals("Could not find any started sagas for message type 'NServiceBus.AcceptanceTests.Sagas.When_reply_from_saga_not_found_handler+MessageToSaga'. Going to invoke SagaNotFoundHandlers.")), Is.EqualTo(1)); + Assert.That(context.ReplyReceived, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_originator.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_originator.cs index 0f5c5d79dad..f75bdec84ff 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_originator.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_originator.cs @@ -16,7 +16,7 @@ public async Task Should_route_the_message_to_the_endpoint_starting_the_saga() .Done(c => c.DidRequestingSagaGetTheResponse) .Run(); - Assert.True(context.DidRequestingSagaGetTheResponse); + Assert.That(context.DidRequestingSagaGetTheResponse, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_originator_from_a_timeout.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_originator_from_a_timeout.cs index b3200b6c059..59e70844e43 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_originator_from_a_timeout.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_originator_from_a_timeout.cs @@ -18,7 +18,7 @@ public async Task Should_route_the_message_to_the_endpoint_starting_the_saga() .Done(c => c.DidRequestingSagaGetTheResponse) .Run(TimeSpan.FromSeconds(15)); - Assert.True(context.DidRequestingSagaGetTheResponse); + Assert.That(context.DidRequestingSagaGetTheResponse, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_saga_event.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_saga_event.cs index 54e246ea393..40945212b7b 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_saga_event.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_replying_to_saga_event.cs @@ -31,7 +31,7 @@ public async Task Should_correlate_reply_to_publishing_saga_instance() .Done(c => c.CorrelatedResponseReceived) .Run(); - Assert.True(context.CorrelatedResponseReceived); + Assert.That(context.CorrelatedResponseReceived, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_exists_for_start_message.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_exists_for_start_message.cs index b347cf4e91b..ce32d84ff2b 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_exists_for_start_message.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_exists_for_start_message.cs @@ -31,8 +31,8 @@ await session.SendLocal( .Done(c => c.SagaIds.Count >= 2) .Run(); - Assert.AreEqual(2, context.SagaIds.Count); - Assert.AreEqual(context.SagaIds[0], context.SagaIds[1]); + Assert.That(context.SagaIds, Has.Count.EqualTo(2)); + Assert.That(context.SagaIds[1], Is.EqualTo(context.SagaIds[0])); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_handles_unmapped_message.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_handles_unmapped_message.cs index 93fe44d63f4..17695003cc1 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_handles_unmapped_message.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_handles_unmapped_message.cs @@ -27,11 +27,14 @@ public async Task Should_throw_on_unmapped_uncorrelated_msg() .Done(c => c.MappedEchoReceived && (c.EchoReceived || !c.FailedMessages.IsEmpty)) .Run(); - Assert.AreEqual(true, context.StartReceived); - Assert.AreEqual(true, context.OutboundReceived); - Assert.AreEqual(true, context.MappedEchoReceived); - Assert.AreEqual(false, context.EchoReceived); - Assert.AreEqual(1, context.FailedMessages.Count); + Assert.Multiple(() => + { + Assert.That(context.StartReceived, Is.EqualTo(true)); + Assert.That(context.OutboundReceived, Is.EqualTo(true)); + Assert.That(context.MappedEchoReceived, Is.EqualTo(true)); + Assert.That(context.EchoReceived, Is.EqualTo(false)); + Assert.That(context.FailedMessages, Has.Count.EqualTo(1)); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_id_changed.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_id_changed.cs index 13e2f788c78..5900251d267 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_id_changed.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_id_changed.cs @@ -24,9 +24,12 @@ await Scenario.Define() .Done(c => !c.FailedMessages.IsEmpty) .Run()); - Assert.That(exception.ScenarioContext.FailedMessages, Has.Count.EqualTo(1)); - Assert.That(((Context)exception.ScenarioContext).MessageId, Is.EqualTo(exception.FailedMessage.MessageId), "Message should be moved to errorqueue"); - Assert.That(exception.FailedMessage.Exception.Message, Contains.Substring("A modification of IContainSagaData.Id has been detected. This property is for infrastructure purposes only and should not be modified. SagaType:")); + Assert.Multiple(() => + { + Assert.That(exception.ScenarioContext.FailedMessages, Has.Count.EqualTo(1)); + Assert.That(((Context)exception.ScenarioContext).MessageId, Is.EqualTo(exception.FailedMessage.MessageId), "Message should be moved to errorqueue"); + Assert.That(exception.FailedMessage.Exception.Message, Contains.Substring("A modification of IContainSagaData.Id has been detected. This property is for infrastructure purposes only and should not be modified. SagaType:")); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_is_mapped_to_complex_expression.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_is_mapped_to_complex_expression.cs index 3681689889e..04c2e12ce28 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_is_mapped_to_complex_expression.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_is_mapped_to_complex_expression.cs @@ -25,8 +25,11 @@ public async Task Should_hydrate_and_invoke_the_existing_instance() .Done(c => c.SecondMessageReceived) .Run(); - Assert.IsTrue(context.SecondMessageReceived); - Assert.AreEqual(context.SagaIdWhenStartSagaMessageReceived, context.SagaIdWhenOtherMessageReceived); + Assert.Multiple(() => + { + Assert.That(context.SecondMessageReceived, Is.True); + Assert.That(context.SagaIdWhenOtherMessageReceived, Is.EqualTo(context.SagaIdWhenStartSagaMessageReceived)); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_started_concurrently.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_started_concurrently.cs index a9837ca22d3..12b0075f28c 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_saga_started_concurrently.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_saga_started_concurrently.cs @@ -30,9 +30,12 @@ public async Task Should_start_single_saga() .Done(c => c.PlacedSagaId != Guid.Empty && c.BilledSagaId != Guid.Empty) .Run(); - Assert.AreNotEqual(Guid.Empty, context.PlacedSagaId); - Assert.AreNotEqual(Guid.Empty, context.BilledSagaId); - Assert.AreEqual(context.PlacedSagaId, context.BilledSagaId, "Both messages should have been handled by the same saga, but SagaIds don't match."); + Assert.Multiple(() => + { + Assert.That(context.PlacedSagaId, Is.Not.EqualTo(Guid.Empty)); + Assert.That(context.BilledSagaId, Is.Not.EqualTo(Guid.Empty)); + }); + Assert.That(context.BilledSagaId, Is.EqualTo(context.PlacedSagaId), "Both messages should have been handled by the same saga, but SagaIds don't match."); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_sagas_cant_be_found.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_sagas_cant_be_found.cs index 3ac699f2c0c..3ca0f9dfd8c 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_sagas_cant_be_found.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_sagas_cant_be_found.cs @@ -21,7 +21,7 @@ public async Task IHandleSagaNotFound_only_called_once() .Done(c => c.Done) .Run(); - Assert.AreEqual(1, context.TimesFired); + Assert.That(context.TimesFired, Is.EqualTo(1)); } [Test] @@ -35,11 +35,14 @@ public async Task IHandleSagaNotFound_not_called_if_second_saga_is_executed() .Done(c => c.Done) .Run(); - Assert.IsTrue(context.Logs.Any(m => m.Message.Equals("Could not find a started saga of 'NServiceBus.AcceptanceTests.Sagas.When_sagas_cant_be_found+ReceiverWithOrderedSagas+ReceiverWithOrderedSagasSaga1' for message type 'NServiceBus.AcceptanceTests.Sagas.When_sagas_cant_be_found+MessageToSaga'."))); - Assert.IsFalse(context.Logs.Any(m => m.Message.Equals("Could not find a started saga of 'NServiceBus.AcceptanceTests.Sagas.When_sagas_cant_be_found+ReceiverWithOrderedSagas+ReceiverWithOrderedSagasSaga2' for message type 'NServiceBus.AcceptanceTests.Sagas.When_sagas_cant_be_found+MessageToSaga'."))); - Assert.IsFalse(context.Logs.Any(m => m.Message.Contains("Going to invoke SagaNotFoundHandlers."))); + Assert.Multiple(() => + { + Assert.That(context.Logs.Any(m => m.Message.Equals("Could not find a started saga of 'NServiceBus.AcceptanceTests.Sagas.When_sagas_cant_be_found+ReceiverWithOrderedSagas+ReceiverWithOrderedSagasSaga1' for message type 'NServiceBus.AcceptanceTests.Sagas.When_sagas_cant_be_found+MessageToSaga'.")), Is.True); + Assert.That(context.Logs.Any(m => m.Message.Equals("Could not find a started saga of 'NServiceBus.AcceptanceTests.Sagas.When_sagas_cant_be_found+ReceiverWithOrderedSagas+ReceiverWithOrderedSagasSaga2' for message type 'NServiceBus.AcceptanceTests.Sagas.When_sagas_cant_be_found+MessageToSaga'.")), Is.False); + Assert.That(context.Logs.Any(m => m.Message.Contains("Going to invoke SagaNotFoundHandlers.")), Is.False); - Assert.AreEqual(0, context.TimesFired); + Assert.That(context.TimesFired, Is.EqualTo(0)); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_sagas_share_timeout_messages.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_sagas_share_timeout_messages.cs index 24ee1f2d4ea..d89678380b7 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_sagas_share_timeout_messages.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_sagas_share_timeout_messages.cs @@ -21,8 +21,11 @@ public async Task Should_invoke_instance_that_requested_the_timeout() .Done(c => c.Saga1ReceivedTimeout || c.Saga2ReceivedTimeout) .Run(TimeSpan.FromSeconds(30)); - Assert.IsTrue(context.Saga2ReceivedTimeout); - Assert.IsFalse(context.Saga1ReceivedTimeout); + Assert.Multiple(() => + { + Assert.That(context.Saga2ReceivedTimeout, Is.True); + Assert.That(context.Saga1ReceivedTimeout, Is.False); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_sending_from_a_saga_handle.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_sending_from_a_saga_handle.cs index 954f4c5a2ab..2a8d20f0af5 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_sending_from_a_saga_handle.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_sending_from_a_saga_handle.cs @@ -19,7 +19,7 @@ public async Task Should_match_different_saga() .Done(c => c.DidSaga2ReceiveMessage) .Run(); - Assert.True(context.DidSaga2ReceiveMessage); + Assert.That(context.DidSaga2ReceiveMessage, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_sending_from_a_saga_timeout.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_sending_from_a_saga_timeout.cs index 6c189ed228e..6420035079a 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_sending_from_a_saga_timeout.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_sending_from_a_saga_timeout.cs @@ -21,7 +21,7 @@ public async Task Should_match_different_saga() .Done(c => c.DidSaga2ReceiveMessage) .Run(); - Assert.True(context.DidSaga2ReceiveMessage); + Assert.That(context.DidSaga2ReceiveMessage, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_started_by_base_event_from_other_saga.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_started_by_base_event_from_other_saga.cs index 5832df5e902..1f1e5d5fc24 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_started_by_base_event_from_other_saga.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_started_by_base_event_from_other_saga.cs @@ -31,7 +31,7 @@ public async Task Should_start_the_saga_when_set_up_to_start_for_the_base_event( .Done(c => c.DidSagaComplete) .Run(); - Assert.True(context.DidSagaComplete); + Assert.That(context.DidSagaComplete, Is.True); } public class SagaContext : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_started_by_event_from_another_saga.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_started_by_event_from_another_saga.cs index 780dac0e0e6..bc3d456258f 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_started_by_event_from_another_saga.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_started_by_event_from_another_saga.cs @@ -36,7 +36,7 @@ public async Task Should_start_the_saga_and_request_a_timeout() .Done(c => c.DidSaga1Complete && c.DidSaga2Complete) .Run(); - Assert.True(context.DidSaga1Complete && context.DidSaga2Complete); + Assert.That(context.DidSaga1Complete && context.DidSaga2Complete, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_timeout_hit_not_found_saga.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_timeout_hit_not_found_saga.cs index a53d995603e..15c1ee2bb66 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_timeout_hit_not_found_saga.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_timeout_hit_not_found_saga.cs @@ -22,7 +22,7 @@ public async Task Should_not_fire_notfound_for_tm() .Done(c => c.NotFoundHandlerCalledForRegularMessage) .Run(); - Assert.False(context.NotFoundHandlerCalledForTimeout); + Assert.That(context.NotFoundHandlerCalledForTimeout, Is.False); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_two_sagas_subscribe_to_the_same_event.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_two_sagas_subscribe_to_the_same_event.cs index 94ae22a354c..d996e29d63e 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_two_sagas_subscribe_to_the_same_event.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_two_sagas_subscribe_to_the_same_event.cs @@ -27,7 +27,7 @@ public async Task Should_invoke_all_handlers_on_all_sagas() .Done(c => c.DidSaga1EventHandlerGetInvoked && c.DidSaga2EventHandlerGetInvoked) .Run(); - Assert.True(context.DidSaga1EventHandlerGetInvoked && context.DidSaga2EventHandlerGetInvoked); + Assert.That(context.DidSaga1EventHandlerGetInvoked && context.DidSaga2EventHandlerGetInvoked, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_updating_existing_correlation_property.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_updating_existing_correlation_property.cs index cc9b6bd2f31..c9e5aca66de 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_updating_existing_correlation_property.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_updating_existing_correlation_property.cs @@ -22,11 +22,14 @@ await Scenario.Define() .Done(c => !c.FailedMessages.IsEmpty) .Run()); - Assert.IsTrue(((Context)exception.ScenarioContext).ModifiedCorrelationProperty); - Assert.AreEqual(1, exception.ScenarioContext.FailedMessages.Count); - StringAssert.Contains( - "Changing the value of correlated properties at runtime is currently not supported", - exception.FailedMessage.Exception.Message); + Assert.Multiple(() => + { + Assert.That(((Context)exception.ScenarioContext).ModifiedCorrelationProperty, Is.True); + Assert.That(exception.ScenarioContext.FailedMessages, Has.Count.EqualTo(1)); + }); + Assert.That( + exception.FailedMessage.Exception.Message, + Does.Contain("Changing the value of correlated properties at runtime is currently not supported")); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_using_a_received_message_for_timeout.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_using_a_received_message_for_timeout.cs index b9e275ff1b5..612e3aea17a 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_using_a_received_message_for_timeout.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_using_a_received_message_for_timeout.cs @@ -21,8 +21,11 @@ public async Task Timeout_should_be_received_after_expiration() .Done(c => c.TimeoutReceived) .Run(); - Assert.True(context.TimeoutReceived); - Assert.AreEqual(1, context.HandlerCalled); + Assert.Multiple(() => + { + Assert.That(context.TimeoutReceived, Is.True); + Assert.That(context.HandlerCalled, Is.EqualTo(1)); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Sagas/When_using_contain_saga_data.cs b/src/NServiceBus.AcceptanceTests/Sagas/When_using_contain_saga_data.cs index 496cacc828f..0894cfeed76 100644 --- a/src/NServiceBus.AcceptanceTests/Sagas/When_using_contain_saga_data.cs +++ b/src/NServiceBus.AcceptanceTests/Sagas/When_using_contain_saga_data.cs @@ -22,7 +22,7 @@ public async Task Should_handle_timeouts_properly() .Done(c => c.TimeoutReceived) .Run(); - Assert.True(context.TimeoutReceived); + Assert.That(context.TimeoutReceived, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Satellites/When_a_message_is_available.cs b/src/NServiceBus.AcceptanceTests/Satellites/When_a_message_is_available.cs index f31bca197cc..0537e07f4e4 100644 --- a/src/NServiceBus.AcceptanceTests/Satellites/When_a_message_is_available.cs +++ b/src/NServiceBus.AcceptanceTests/Satellites/When_a_message_is_available.cs @@ -20,12 +20,15 @@ public async Task Should_receive_the_message() .Done(c => c.MessageReceived) .Run(); - Assert.True(context.MessageReceived); - // In the future we want the transport transaction to be an explicit - // concept in the persisters API as well. Adding transport transaction - // to the context will not be necessary at that point. - // See GitHub issue #4047 for more background information. - Assert.True(context.TransportTransactionAddedToContext); + Assert.Multiple(() => + { + Assert.That(context.MessageReceived, Is.True); + // In the future we want the transport transaction to be an explicit + // concept in the persisters API as well. Adding transport transaction + // to the context will not be necessary at that point. + // See GitHub issue #4047 for more background information. + Assert.That(context.TransportTransactionAddedToContext, Is.True); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_configuring_custom_xml_namespace.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_configuring_custom_xml_namespace.cs index 8d87c2aa42a..be666a8e8f8 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_configuring_custom_xml_namespace.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_configuring_custom_xml_namespace.cs @@ -21,7 +21,7 @@ public async Task Should_use_as_root_namespace_in_messages() .Done(c => c.MessageReceived) .Run(); - Assert.AreEqual($"{CustomXmlNamespace}/{typeof(SimpleMessage).Namespace}", context.MessageNamespace); + Assert.That(context.MessageNamespace, Is.EqualTo($"{CustomXmlNamespace}/{typeof(SimpleMessage).Namespace}")); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_defining_serializer_with_no_content_type.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_defining_serializer_with_no_content_type.cs index b0eac289b05..d52cbbc0af9 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_defining_serializer_with_no_content_type.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_defining_serializer_with_no_content_type.cs @@ -21,7 +21,7 @@ public void Should_fail_endpoint_startup_for_main_serializer() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains($"Serializer '{nameof(InvalidSerializer)}' defines no content type. Ensure the 'ContentType' property of the serializer has a value.", exception.Message); + Assert.That(exception.Message, Does.Contain($"Serializer '{nameof(InvalidSerializer)}' defines no content type. Ensure the 'ContentType' property of the serializer has a value.")); } [Test] @@ -33,7 +33,7 @@ public void Should_fail_endpoint_startup_for_additional_deserializer() .Done(c => c.EndpointsStarted) .Run()); - StringAssert.Contains($"Serializer '{nameof(InvalidSerializer)}' defines no content type. Ensure the 'ContentType' property of the serializer has a value.", exception.Message); + Assert.That(exception.Message, Does.Contain($"Serializer '{nameof(InvalidSerializer)}' defines no content type. Ensure the 'ContentType' property of the serializer has a value.")); } class EndpointWithInvalidSerializer : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_disabling_serializer_type_inference.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_disabling_serializer_type_inference.cs index a25883fc956..0cb1408c33e 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_disabling_serializer_type_inference.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_disabling_serializer_type_inference.cs @@ -25,11 +25,14 @@ public async Task Should_not_deserialize_messages_without_types_header() .Done(c => c.IncomingMessageReceived) .Run(TimeSpan.FromSeconds(35)); - Assert.IsFalse(context.HandlerInvoked); - Assert.AreEqual(1, context.FailedMessages.Single().Value.Count); + Assert.Multiple(() => + { + Assert.That(context.HandlerInvoked, Is.False); + Assert.That(context.FailedMessages.Single().Value, Has.Count.EqualTo(1)); + }); Exception exception = context.FailedMessages.Single().Value.Single().Exception; - Assert.IsInstanceOf(exception); - StringAssert.Contains($"Could not determine the message type from the '{Headers.EnclosedMessageTypes}' header", exception.InnerException.Message); + Assert.That(exception, Is.InstanceOf()); + Assert.That(exception.InnerException.Message, Does.Contain($"Could not determine the message type from the '{Headers.EnclosedMessageTypes}' header")); } [Test] @@ -42,11 +45,14 @@ public async Task Should_not_deserialize_messages_with_unknown_type_header() .Done(c => c.IncomingMessageReceived) .Run(TimeSpan.FromSeconds(35)); - Assert.IsFalse(context.HandlerInvoked); - Assert.AreEqual(1, context.FailedMessages.Single().Value.Count); + Assert.Multiple(() => + { + Assert.That(context.HandlerInvoked, Is.False); + Assert.That(context.FailedMessages.Single().Value, Has.Count.EqualTo(1)); + }); Exception exception = context.FailedMessages.Single().Value.Single().Exception; - Assert.IsInstanceOf(exception); - StringAssert.Contains($"Could not determine the message type from the '{Headers.EnclosedMessageTypes}' header", exception.InnerException.Message); + Assert.That(exception, Is.InstanceOf()); + Assert.That(exception.InnerException.Message, Does.Contain($"Could not determine the message type from the '{Headers.EnclosedMessageTypes}' header")); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_dynamic_loading_is_disabled.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_dynamic_loading_is_disabled.cs index 31175f72a60..3522a03157c 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_dynamic_loading_is_disabled.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_dynamic_loading_is_disabled.cs @@ -21,10 +21,10 @@ public async Task Should_not_load_type_dynamically() .Done(c => c.MessageReceived) .Run(); - Assert.AreEqual(1, context.FailedMessages.Single().Value.Count); + Assert.That(context.FailedMessages.Single().Value, Has.Count.EqualTo(1)); Exception exception = context.FailedMessages.Single().Value.Single().Exception; - Assert.IsInstanceOf(exception); - Assert.AreEqual($"Could not determine the message type from the '{Headers.EnclosedMessageTypes}' header and message type inference from the message body has been disabled. Ensure the header is set or enable message type inference.", exception.InnerException.Message); + Assert.That(exception, Is.InstanceOf()); + Assert.That(exception.InnerException.Message, Is.EqualTo($"Could not determine the message type from the '{Headers.EnclosedMessageTypes}' header and message type inference from the message body has been disabled. Ensure the header is set or enable message type inference.")); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_message_type_header_is_whitespaces.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_message_type_header_is_whitespaces.cs index 4540537c001..9576165e542 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_message_type_header_is_whitespaces.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_message_type_header_is_whitespaces.cs @@ -20,10 +20,13 @@ public async Task Should_move_message_to_error_queue() .Done(c => c.IncomingMessageReceived) .Run(TimeSpan.FromSeconds(20)); - Assert.IsFalse(context.HandlerInvoked); - Assert.AreEqual(1, context.FailedMessages.Single().Value.Count); + Assert.Multiple(() => + { + Assert.That(context.HandlerInvoked, Is.False); + Assert.That(context.FailedMessages.Single().Value, Has.Count.EqualTo(1)); + }); Exception exception = context.FailedMessages.Single().Value.Single().Exception; - Assert.IsInstanceOf(exception); + Assert.That(exception, Is.InstanceOf()); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_registering_additional_deserializers.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_registering_additional_deserializers.cs index b707bcc88dc..e506b6658c4 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_registering_additional_deserializers.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_registering_additional_deserializers.cs @@ -30,10 +30,13 @@ public async Task Two_endpoints_with_different_serializers_should_deserialize_th .Done(c => c.HandlerGotTheRequest) .Run(); - Assert.True(context.HandlerGotTheRequest); - Assert.True(context.SerializeCalled); - Assert.True(context.DeserializeCalled); - Assert.AreEqual("SomeFancySettings", context.ValueFromSettings); + Assert.Multiple(() => + { + Assert.That(context.HandlerGotTheRequest, Is.True); + Assert.That(context.SerializeCalled, Is.True); + Assert.That(context.DeserializeCalled, Is.True); + Assert.That(context.ValueFromSettings, Is.EqualTo("SomeFancySettings")); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_registering_custom_serializer.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_registering_custom_serializer.cs index ad7e4d0c50b..cbf96cd8e61 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_registering_custom_serializer.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_registering_custom_serializer.cs @@ -24,8 +24,11 @@ public async Task Should_use_the_custom_serializer() .Done(c => c.HandlerGotTheRequest) .Run(); - Assert.IsTrue(context.SerializeCalled); - Assert.IsTrue(context.DeserializeCalled); + Assert.Multiple(() => + { + Assert.That(context.SerializeCalled, Is.True); + Assert.That(context.DeserializeCalled, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_registering_deserializers_with_settings.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_registering_deserializers_with_settings.cs index 3773576cb22..9e20d9f483b 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_registering_deserializers_with_settings.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_registering_deserializers_with_settings.cs @@ -32,11 +32,14 @@ public async Task Should_not_override_serializer_settings() .Done(c => c.DeserializeCalled) .Run(); - Assert.True(context.HandlerGotTheRequest); - Assert.True(context.SerializeCalled); - Assert.True(context.DeserializeCalled); - Assert.AreEqual(Value1, context.ValueFromSettingsForMainSerializer); - Assert.AreEqual(Value2, context.ValueFromSettingsForDeserializer); + Assert.Multiple(() => + { + Assert.That(context.HandlerGotTheRequest, Is.True); + Assert.That(context.SerializeCalled, Is.True); + Assert.That(context.DeserializeCalled, Is.True); + Assert.That(context.ValueFromSettingsForMainSerializer, Is.EqualTo(Value1)); + Assert.That(context.ValueFromSettingsForDeserializer, Is.EqualTo(Value2)); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_serializing_a_message.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_serializing_a_message.cs index e46461357a1..107b4e8968e 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_serializing_a_message.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_serializing_a_message.cs @@ -35,16 +35,22 @@ public async Task DateTime_properties_should_keep_their_original_timezone_inform .Done(c => c.ReceivedMessage != null) .Run(); - Assert.AreEqual(expectedDateTime, context.ReceivedMessage.DateTime); - Assert.AreEqual(expectedDateTimeLocal, context.ReceivedMessage.DateTimeLocal); - Assert.AreEqual(expectedDateTimeUtc, context.ReceivedMessage.DateTimeUtc); - Assert.AreEqual(expectedDateTimeOffset, context.ReceivedMessage.DateTimeOffset); - Assert.AreEqual(expectedDateTimeOffsetLocal, context.ReceivedMessage.DateTimeOffsetLocal); - Assert.AreEqual(expectedDateTimeOffsetUtc, context.ReceivedMessage.DateTimeOffsetUtc); - Assert.AreEqual(expectedDateTimeOffsetLocal, context.ReceivedMessage.DateTimeOffsetLocal); - Assert.AreEqual(expectedDateTimeOffsetLocal.Offset, context.ReceivedMessage.DateTimeOffsetLocal.Offset); - Assert.AreEqual(expectedDateTimeOffsetUtc, context.ReceivedMessage.DateTimeOffsetUtc); - Assert.AreEqual(expectedDateTimeOffsetUtc.Offset, context.ReceivedMessage.DateTimeOffsetUtc.Offset); + Assert.Multiple(() => + { + Assert.That(context.ReceivedMessage.DateTime, Is.EqualTo(expectedDateTime)); + Assert.That(context.ReceivedMessage.DateTimeLocal, Is.EqualTo(expectedDateTimeLocal)); + Assert.That(context.ReceivedMessage.DateTimeUtc, Is.EqualTo(expectedDateTimeUtc)); + Assert.That(context.ReceivedMessage.DateTimeOffset, Is.EqualTo(expectedDateTimeOffset)); + Assert.That(context.ReceivedMessage.DateTimeOffsetLocal, Is.EqualTo(expectedDateTimeOffsetLocal)); + Assert.That(context.ReceivedMessage.DateTimeOffsetUtc, Is.EqualTo(expectedDateTimeOffsetUtc)); + }); + Assert.That(context.ReceivedMessage.DateTimeOffsetLocal, Is.EqualTo(expectedDateTimeOffsetLocal)); + Assert.Multiple(() => + { + Assert.That(context.ReceivedMessage.DateTimeOffsetLocal.Offset, Is.EqualTo(expectedDateTimeOffsetLocal.Offset)); + Assert.That(context.ReceivedMessage.DateTimeOffsetUtc, Is.EqualTo(expectedDateTimeOffsetUtc)); + }); + Assert.That(context.ReceivedMessage.DateTimeOffsetUtc.Offset, Is.EqualTo(expectedDateTimeOffsetUtc.Offset)); } class DateTimeReceiver : EndpointConfigurationBuilder diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_skip_wrapping_xml.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_skip_wrapping_xml.cs index 7210731f135..2514e2e6af4 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_skip_wrapping_xml.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_skip_wrapping_xml.cs @@ -23,9 +23,12 @@ public async Task Should_not_wrap_xml_content() .Done(c => c.MessageReceived) .Run(); - Assert.That(context.XmlPropertyValue.ToString(), Is.EqualTo(xmlContent.ToString())); - Assert.That(context.XmlMessage.Root.Name.LocalName, Is.EqualTo(nameof(MessageWithRawXml))); - Assert.That(context.XmlMessage.Root.Elements().Single().ToString(), Is.EqualTo(xmlContent.ToString())); + Assert.Multiple(() => + { + Assert.That(context.XmlPropertyValue.ToString(), Is.EqualTo(xmlContent.ToString())); + Assert.That(context.XmlMessage.Root.Name.LocalName, Is.EqualTo(nameof(MessageWithRawXml))); + Assert.That(context.XmlMessage.Root.Elements().Single().ToString(), Is.EqualTo(xmlContent.ToString())); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_wrapping_is_not_skipped.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_wrapping_is_not_skipped.cs index 70d7892e3e9..2826bad198d 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_wrapping_is_not_skipped.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_wrapping_is_not_skipped.cs @@ -23,11 +23,14 @@ public async Task Should_wrap_xml_content() .Done(c => c.MessageReceived) .Run(); - Assert.That(context.XmlPropertyValue.ToString(), Is.EqualTo(xmlContent.ToString())); - Assert.That(context.XmlMessage.Root.Name.LocalName, Is.EqualTo(nameof(MessageWithRawXml))); - Assert.That(context.XmlMessage.Root.Elements().Single().Name.LocalName, Is.EqualTo("Document")); - Assert.That(context.XmlMessage.Root.Elements().Single().Elements().Single().Name.LocalName, Is.EqualTo("Document")); - Assert.That(context.XmlMessage.Root.Elements().Single().Elements().Single().ToString(), Is.EqualTo(xmlContent.ToString())); + Assert.Multiple(() => + { + Assert.That(context.XmlPropertyValue.ToString(), Is.EqualTo(xmlContent.ToString())); + Assert.That(context.XmlMessage.Root.Name.LocalName, Is.EqualTo(nameof(MessageWithRawXml))); + Assert.That(context.XmlMessage.Root.Elements().Single().Name.LocalName, Is.EqualTo("Document")); + Assert.That(context.XmlMessage.Root.Elements().Single().Elements().Single().Name.LocalName, Is.EqualTo("Document")); + Assert.That(context.XmlMessage.Root.Elements().Single().Elements().Single().ToString(), Is.EqualTo(xmlContent.ToString())); + }); } class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_xml_serializer_processes_message_without_type_header.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_xml_serializer_processes_message_without_type_header.cs index b951934ca76..f315f96eb69 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_xml_serializer_processes_message_without_type_header.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_xml_serializer_processes_message_without_type_header.cs @@ -17,7 +17,7 @@ public async Task Should_work_in_unobtrusive() .Done(c => c.WasCalled) .Run(); - Assert.True(context.WasCalled); + Assert.That(context.WasCalled, Is.True); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Serialization/When_xml_serializer_used_with_unobtrusive_mode.cs b/src/NServiceBus.AcceptanceTests/Serialization/When_xml_serializer_used_with_unobtrusive_mode.cs index 3377d50e9be..04ae152c51a 100644 --- a/src/NServiceBus.AcceptanceTests/Serialization/When_xml_serializer_used_with_unobtrusive_mode.cs +++ b/src/NServiceBus.AcceptanceTests/Serialization/When_xml_serializer_used_with_unobtrusive_mode.cs @@ -20,7 +20,7 @@ public async Task Should_deserialize_message() .Done(c => c.WasCalled) .Run(); - Assert.AreEqual(expectedData, context.Data); + Assert.That(context.Data, Is.EqualTo(expectedData)); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_expired.cs b/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_expired.cs index b1b9db47bd8..6cef645ee53 100644 --- a/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_expired.cs +++ b/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_expired.cs @@ -20,7 +20,7 @@ public async Task Message_should_not_be_received() .Done(c => c.WasCalled || DateTime.UtcNow - start > TimeSpan.FromSeconds(15)) .Run(); - Assert.IsFalse(context.WasCalled); + Assert.That(context.WasCalled, Is.False); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_expired_convention.cs b/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_expired_convention.cs index 2405d89f67e..80c1a2a4eaa 100644 --- a/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_expired_convention.cs +++ b/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_expired_convention.cs @@ -20,7 +20,7 @@ public async Task Message_should_not_be_received() .Done(c => c.WasCalled || DateTime.UtcNow - start > TimeSpan.FromSeconds(15)) .Run(); - Assert.IsFalse(context.WasCalled); + Assert.That(context.WasCalled, Is.False); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_not_expired.cs b/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_not_expired.cs index 4c3c204a9f0..533850d25a6 100644 --- a/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_not_expired.cs +++ b/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_has_not_expired.cs @@ -16,8 +16,11 @@ public async Task Message_should_be_received() .Done(c => c.WasCalled) .Run(); - Assert.IsTrue(context.WasCalled); - Assert.AreEqual(TimeSpan.FromSeconds(10), context.TTBROnIncomingMessage, "TTBR should be available as a header so receiving endpoints can know what value was used when the message was originally sent"); + Assert.Multiple(() => + { + Assert.That(context.WasCalled, Is.True); + Assert.That(context.TTBROnIncomingMessage, Is.EqualTo(TimeSpan.FromSeconds(10)), "TTBR should be available as a header so receiving endpoints can know what value was used when the message was originally sent"); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_used_with_unobtrusive_mode.cs b/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_used_with_unobtrusive_mode.cs index f62d6325ad2..70bd7dc0ed3 100644 --- a/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_used_with_unobtrusive_mode.cs +++ b/src/NServiceBus.AcceptanceTests/TimeToBeReceived/When_TimeToBeReceived_used_with_unobtrusive_mode.cs @@ -20,7 +20,7 @@ public async Task Message_should_not_be_received() .Done(c => c.WasCalled || DateTime.UtcNow - start > TimeSpan.FromSeconds(15)) .Run(); - Assert.IsFalse(context.WasCalled); + Assert.That(context.WasCalled, Is.False); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/At_least_once.cs b/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/At_least_once.cs index 40f34422de7..ec1c40ce08d 100644 --- a/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/At_least_once.cs +++ b/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/At_least_once.cs @@ -17,7 +17,7 @@ public async Task Should_dispatch_immediately() .Done(c => c.MessageDispatched) .Run(); - Assert.True(context.MessageDispatched, "Should dispatch the message immediately"); + Assert.That(context.MessageDispatched, Is.True, "Should dispatch the message immediately"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/At_most_once.cs b/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/At_most_once.cs index 752da3911fc..c3e513c6ca7 100644 --- a/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/At_most_once.cs +++ b/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/At_most_once.cs @@ -17,7 +17,7 @@ public async Task Should_dispatch_immediately() .Done(c => c.MessageDispatched) .Run(); - Assert.True(context.MessageDispatched, "Should dispatch the message immediately"); + Assert.That(context.MessageDispatched, Is.True, "Should dispatch the message immediately"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/Exactly_once.cs b/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/Exactly_once.cs index 867d184afb1..c2443c04dbe 100644 --- a/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/Exactly_once.cs +++ b/src/NServiceBus.AcceptanceTests/Tx/ImmediateDispatch/Exactly_once.cs @@ -17,7 +17,7 @@ public async Task Should_dispatch_immediately() .Done(c => c.MessageDispatched) .Run(); - Assert.True(context.MessageDispatched, "Should dispatch the message immediately"); + Assert.That(context.MessageDispatched, Is.True, "Should dispatch the message immediately"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Tx/When_receiving_in_transaction_scope_mode.cs b/src/NServiceBus.AcceptanceTests/Tx/When_receiving_in_transaction_scope_mode.cs index c027c590c16..b728b122a1a 100644 --- a/src/NServiceBus.AcceptanceTests/Tx/When_receiving_in_transaction_scope_mode.cs +++ b/src/NServiceBus.AcceptanceTests/Tx/When_receiving_in_transaction_scope_mode.cs @@ -19,7 +19,7 @@ public async Task Should_enlist_in_dtc_transaction() .Done(c => c.HandlerInvoked) .Run(); - Assert.True(context.DtcTransactionPresent, "There should exists a DTC tx"); + Assert.That(context.DtcTransactionPresent, Is.True, "There should exists a DTC tx"); } diff --git a/src/NServiceBus.AcceptanceTests/Tx/When_receiving_with_native_multi_queue_transaction.cs b/src/NServiceBus.AcceptanceTests/Tx/When_receiving_with_native_multi_queue_transaction.cs index 136040d5986..09655906fd1 100644 --- a/src/NServiceBus.AcceptanceTests/Tx/When_receiving_with_native_multi_queue_transaction.cs +++ b/src/NServiceBus.AcceptanceTests/Tx/When_receiving_with_native_multi_queue_transaction.cs @@ -17,8 +17,11 @@ public async Task Should_not_send_outgoing_messages_if_receiving_transaction_is_ .Done(c => c.MessageHandled) .Run(); - Assert.IsFalse(context.HasFailed); - Assert.IsTrue(context.MessageHandled); + Assert.Multiple(() => + { + Assert.That(context.HasFailed, Is.False); + Assert.That(context.MessageHandled, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Tx/When_sending_within_an_ambient_transaction.cs b/src/NServiceBus.AcceptanceTests/Tx/When_sending_within_an_ambient_transaction.cs index 75f4b44c71d..c2f1502f0b1 100644 --- a/src/NServiceBus.AcceptanceTests/Tx/When_sending_within_an_ambient_transaction.cs +++ b/src/NServiceBus.AcceptanceTests/Tx/When_sending_within_an_ambient_transaction.cs @@ -40,7 +40,7 @@ await session.Send(new MessageThatIsEnlisted .Done(c => c.MessageThatIsNotEnlistedHandlerWasCalled && c.TimesCalled >= 2) .Run(); - Assert.AreEqual(1, context.SequenceNumberOfFirstMessage, "The transport should preserve the order in which the transactional messages are delivered to the queuing system"); + Assert.That(context.SequenceNumberOfFirstMessage, Is.EqualTo(1), "The transport should preserve the order in which the transactional messages are delivered to the queuing system"); } [Test] @@ -62,7 +62,7 @@ public async Task Should_not_deliver_them_on_rollback() .Done(c => c.MessageThatIsNotEnlistedHandlerWasCalled) .Run(); - Assert.False(context.MessageThatIsEnlistedHandlerWasCalled, "The transactional handler should not be called"); + Assert.That(context.MessageThatIsEnlistedHandlerWasCalled, Is.False, "The transactional handler should not be called"); } public class Context : ScenarioContext diff --git a/src/NServiceBus.AcceptanceTests/Versioning/When_multiple_versions_of_a_message_is_published.cs b/src/NServiceBus.AcceptanceTests/Versioning/When_multiple_versions_of_a_message_is_published.cs index f6ba34d8c70..052dbe866a6 100644 --- a/src/NServiceBus.AcceptanceTests/Versioning/When_multiple_versions_of_a_message_is_published.cs +++ b/src/NServiceBus.AcceptanceTests/Versioning/When_multiple_versions_of_a_message_is_published.cs @@ -41,8 +41,11 @@ public async Task Should_deliver_is_to_both_v1_and_vX_subscribers() .Done(c => c.V1SubscriberGotTheMessage && c.V2SubscriberGotTheMessage) .Run(); - Assert.True(context.V1SubscriberGotTheMessage); - Assert.True(context.V2SubscriberGotTheMessage); + Assert.Multiple(() => + { + Assert.That(context.V1SubscriberGotTheMessage, Is.True); + Assert.That(context.V2SubscriberGotTheMessage, Is.True); + }); } public class Context : ScenarioContext diff --git a/src/NServiceBus.ContainerTests/NServiceBus.ContainerTests.csproj b/src/NServiceBus.ContainerTests/NServiceBus.ContainerTests.csproj index 2ed017d5ff0..7ba5b295ce1 100644 --- a/src/NServiceBus.ContainerTests/NServiceBus.ContainerTests.csproj +++ b/src/NServiceBus.ContainerTests/NServiceBus.ContainerTests.csproj @@ -14,6 +14,7 @@ + diff --git a/src/NServiceBus.ContainerTests/When_building_components.cs b/src/NServiceBus.ContainerTests/When_building_components.cs index 600dfb4b3dc..366be54fe17 100644 --- a/src/NServiceBus.ContainerTests/When_building_components.cs +++ b/src/NServiceBus.ContainerTests/When_building_components.cs @@ -13,7 +13,10 @@ public void Singleton_components_should_yield_the_same_instance() InitializeServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.AreEqual(serviceProvider.GetService(typeof(SingletonComponent)), serviceProvider.GetService(typeof(SingletonComponent))); + var instance1 = serviceProvider.GetService(typeof(SingletonComponent)); + var instance2 = serviceProvider.GetService(typeof(SingletonComponent)); + + Assert.That(instance1, Is.EqualTo(instance2)); } [Test] @@ -23,7 +26,10 @@ public void Transient_components_should_yield_unique_instances() InitializeServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.AreNotEqual(serviceProvider.GetService(), serviceProvider.GetService()); + var instance1 = serviceProvider.GetService(); + var instance2 = serviceProvider.GetService(); + + Assert.That(instance1, Is.Not.EqualTo(instance2)); } [Test] @@ -36,7 +42,7 @@ public void Scoped_components_should_yield_the_same_instance() var instance1 = serviceProvider.GetService(typeof(ScopedComponent)); var instance2 = serviceProvider.GetService(typeof(ScopedComponent)); - Assert.AreSame(instance1, instance2); + Assert.That(instance2, Is.SameAs(instance1)); } [Test] @@ -49,7 +55,7 @@ public void Lambda_scoped_components_should_yield_the_same_instance() var instance1 = serviceProvider.GetService(typeof(ScopedLambdaComponent)); var instance2 = serviceProvider.GetService(typeof(ScopedLambdaComponent)); - Assert.AreSame(instance1, instance2); + Assert.That(instance2, Is.SameAs(instance1)); } [Test] @@ -59,7 +65,10 @@ public void Lambda_transient_components_should_yield_unique_instances() InitializeServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.AreNotEqual(serviceProvider.GetService(typeof(TransientLambdaComponent)), serviceProvider.GetService(typeof(TransientLambdaComponent))); + var instance1 = serviceProvider.GetService(typeof(TransientLambdaComponent)); + var instance2 = serviceProvider.GetService(typeof(TransientLambdaComponent)); + + Assert.That(instance1, Is.Not.EqualTo(instance2)); } [Test] @@ -69,7 +78,10 @@ public void Lambda_singleton_components_should_yield_the_same_instance() InitializeServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.AreEqual(serviceProvider.GetService(typeof(SingletonLambdaComponent)), serviceProvider.GetService(typeof(SingletonLambdaComponent))); + var instance1 = serviceProvider.GetService(typeof(SingletonLambdaComponent)); + var instance2 = serviceProvider.GetService(typeof(SingletonLambdaComponent)); + + Assert.That(instance1, Is.EqualTo(instance2)); } [Test] @@ -79,7 +91,7 @@ public void Resolving_all_components_of_unregistered_types_should_give_empty_lis InitializeServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.IsEmpty(serviceProvider.GetServices(typeof(UnregisteredComponent))); + Assert.That(serviceProvider.GetServices(typeof(UnregisteredComponent)), Is.Empty); } [Test] diff --git a/src/NServiceBus.ContainerTests/When_disposing_the_builder.cs b/src/NServiceBus.ContainerTests/When_disposing_the_builder.cs index d4617c15e4f..9847cd7236b 100644 --- a/src/NServiceBus.ContainerTests/When_disposing_the_builder.cs +++ b/src/NServiceBus.ContainerTests/When_disposing_the_builder.cs @@ -22,8 +22,11 @@ public void Should_dispose_all_IDisposable_components() serviceProvider.GetService(typeof(AnotherSingletonComponent)); (serviceProvider as IDisposable)?.Dispose(); - Assert.True(DisposableComponent.DisposeCalled, "Dispose should be called on DisposableComponent"); - Assert.False(AnotherSingletonComponent.DisposeCalled, "Dispose should not be called on AnotherSingletonComponent"); + Assert.Multiple(() => + { + Assert.That(DisposableComponent.DisposeCalled, Is.True, "Dispose should be called on DisposableComponent"); + Assert.That(AnotherSingletonComponent.DisposeCalled, Is.False, "Dispose should not be called on AnotherSingletonComponent"); + }); } public class DisposableComponent : IDisposable diff --git a/src/NServiceBus.ContainerTests/When_querying_for_registered_components.cs b/src/NServiceBus.ContainerTests/When_querying_for_registered_components.cs index d5be6dd446c..75ce8158f22 100644 --- a/src/NServiceBus.ContainerTests/When_querying_for_registered_components.cs +++ b/src/NServiceBus.ContainerTests/When_querying_for_registered_components.cs @@ -13,7 +13,7 @@ public void Existing_components_should_return_true() var serviceCollection = new ServiceCollection(); InitializeBuilder(serviceCollection); - Assert.True(serviceCollection.Any(sd => sd.ServiceType == typeof(ExistingComponent))); + Assert.That(serviceCollection.Any(sd => sd.ServiceType == typeof(ExistingComponent)), Is.True); } [Test] @@ -22,7 +22,7 @@ public void Non_existing_components_should_return_false() var serviceCollection = new ServiceCollection(); InitializeBuilder(serviceCollection); - Assert.False(serviceCollection.Any(sd => sd.ServiceType == typeof(NonExistingComponent))); + Assert.That(serviceCollection.Any(sd => sd.ServiceType == typeof(NonExistingComponent)), Is.False); } [Test] @@ -31,7 +31,7 @@ public void Builders_should_not_determine_existence_by_building_components() var serviceCollection = new ServiceCollection(); InitializeBuilder(serviceCollection); - Assert.True(serviceCollection.Any(sd => sd.ServiceType == typeof(ExistingComponentWithUnsatisfiedDependency))); + Assert.That(serviceCollection.Any(sd => sd.ServiceType == typeof(ExistingComponentWithUnsatisfiedDependency)), Is.True); } static void InitializeBuilder(IServiceCollection c) diff --git a/src/NServiceBus.ContainerTests/When_registering_components.cs b/src/NServiceBus.ContainerTests/When_registering_components.cs index 1b1e74652ad..07d0a460fef 100644 --- a/src/NServiceBus.ContainerTests/When_registering_components.cs +++ b/src/NServiceBus.ContainerTests/When_registering_components.cs @@ -18,7 +18,7 @@ public void Multiple_registrations_of_the_same_component_should_be_allowed() serviceCollection.AddTransient(typeof(DuplicateClass)); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.AreEqual(2, serviceProvider.GetServices(typeof(DuplicateClass)).Count()); + Assert.That(serviceProvider.GetServices(typeof(DuplicateClass)).Count(), Is.EqualTo(2)); } [Test] @@ -29,7 +29,7 @@ public void Should_support_lambdas_that_uses_other_components_registered_later() serviceCollection.AddSingleton(_ => new StaticFactory()); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.NotNull(serviceProvider.GetService(typeof(ComponentCreatedByFactory))); + Assert.That(serviceProvider.GetService(typeof(ComponentCreatedByFactory)), Is.Not.Null); } [Test] @@ -40,7 +40,7 @@ public void A_registration_should_be_allowed_to_be_updated() serviceCollection.AddSingleton(typeof(ISingletonComponent), new AnotherSingletonComponent()); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.IsInstanceOf(serviceProvider.GetService(typeof(ISingletonComponent))); + Assert.That(serviceProvider.GetService(typeof(ISingletonComponent)), Is.InstanceOf()); } [Test] @@ -52,8 +52,8 @@ public void Register_singleton_should_be_supported() serviceCollection.AddSingleton(typeof(SingletonComponent), singleton); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.AreEqual(serviceProvider.GetService(typeof(SingletonComponent)), singleton); - Assert.AreEqual(serviceProvider.GetService(typeof(ISingletonComponent)), singleton); + Assert.That(singleton, Is.EqualTo(serviceProvider.GetService(typeof(SingletonComponent)))); + Assert.That(singleton, Is.EqualTo(serviceProvider.GetService(typeof(ISingletonComponent)))); } [Test] @@ -68,11 +68,14 @@ public void Registering_the_same_singleton_for_different_interfaces_should_be_su var serviceProvider = serviceCollection.BuildServiceProvider(); var dependency = (ComponentThatDependsOnMultiSingletons)serviceProvider.GetService(typeof(ComponentThatDependsOnMultiSingletons)); - Assert.NotNull(dependency.Singleton1); - Assert.NotNull(dependency.Singleton2); + Assert.Multiple(() => + { + Assert.That(dependency.Singleton1, Is.Not.Null); + Assert.That(dependency.Singleton2, Is.Not.Null); - Assert.AreEqual(serviceProvider.GetService(typeof(ISingleton1)), singleton); - Assert.AreEqual(serviceProvider.GetService(typeof(ISingleton2)), singleton); + Assert.That(singleton, Is.EqualTo(serviceProvider.GetService(typeof(ISingleton1)))); + }); + Assert.That(singleton, Is.EqualTo(serviceProvider.GetService(typeof(ISingleton2)))); } [Test] @@ -83,11 +86,11 @@ public void Given_lookupType_should_be_used_as_service_in_the_registration_when_ serviceCollection.AddSingleton(typeof(SomeClass), expected); var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.AreEqual(expected, serviceProvider.GetService(typeof(SomeClass))); + Assert.That(serviceProvider.GetService(typeof(SomeClass)), Is.EqualTo(expected)); using (var scope = serviceProvider.CreateScope()) { - Assert.AreEqual(expected, scope.ServiceProvider.GetService(typeof(SomeClass))); + Assert.That(scope.ServiceProvider.GetService(typeof(SomeClass)), Is.EqualTo(expected)); } } } diff --git a/src/NServiceBus.ContainerTests/When_using_nested_containers.cs b/src/NServiceBus.ContainerTests/When_using_nested_containers.cs index bbf22a1e1f6..9187ff3225f 100644 --- a/src/NServiceBus.ContainerTests/When_using_nested_containers.cs +++ b/src/NServiceBus.ContainerTests/When_using_nested_containers.cs @@ -17,7 +17,7 @@ public void Scoped__components_should_be_disposed_when_the_child_container_is_di { scope.ServiceProvider.GetService(typeof(ScopedComponent)); } - Assert.True(ScopedComponent.DisposeCalled); + Assert.That(ScopedComponent.DisposeCalled, Is.True); } [Test] @@ -32,7 +32,7 @@ public void Scoped_components_should_yield_different_instances_between_parent_an { var childInstance = scope.ServiceProvider.GetService(typeof(ScopedComponent)); - Assert.AreNotSame(parentInstance, childInstance); + Assert.That(childInstance, Is.Not.SameAs(parentInstance)); } } @@ -55,7 +55,7 @@ public void Scoped_components_should_yield_different_instances_between_different instance2 = scope.ServiceProvider.GetService(typeof(ScopedComponent)); } - Assert.AreNotSame(instance1, instance2); + Assert.That(instance2, Is.Not.SameAs(instance1)); } [Test] @@ -77,7 +77,7 @@ public void Transient_components_should_not_be_shared_across_child_containers() instance2 = scope.ServiceProvider.GetService(typeof(TransientComponent)); } - Assert.AreNotSame(instance1, instance2); + Assert.That(instance2, Is.Not.SameAs(instance1)); } [Test] @@ -92,7 +92,7 @@ public void Scoped_components_in_the_parent_container_should_be_singletons_in_th var instance1 = scope.ServiceProvider.GetService(typeof(ScopedComponent)); var instance2 = scope.ServiceProvider.GetService(typeof(ScopedComponent)); - Assert.AreSame(instance1, instance2, "UoW's should be singleton in child container"); + Assert.That(instance2, Is.SameAs(instance1), "UoW's should be singleton in child container"); } } @@ -109,7 +109,7 @@ public void Scoped_components_built_on_root_container_should_be_singletons_even_ } var instance1 = serviceProvider.GetService(typeof(ScopedComponent)); var instance2 = serviceProvider.GetService(typeof(ScopedComponent)); - Assert.AreSame(instance1, instance2, "UoW's should be singletons in the root container"); + Assert.That(instance2, Is.SameAs(instance1), "UoW's should be singletons in the root container"); } [Test] @@ -125,7 +125,7 @@ public void Should_not_dispose_singletons_when_container_goes_out_of_scope() { scope.ServiceProvider.GetService(typeof(ComponentThatDependsOfSingleton)); } - Assert.False(SingletonComponent.DisposeCalled); + Assert.That(SingletonComponent.DisposeCalled, Is.False); } [Test] @@ -143,8 +143,12 @@ public void Should_dispose_all_non_singleton_IDisposable_components_in_child_con { scope.ServiceProvider.GetService(typeof(DisposableComponent)); } - Assert.False(AnotherDisposableComponent.DisposeCalled, "Dispose should not be called on AnotherSingletonComponent because it belongs to main container"); - Assert.True(DisposableComponent.DisposeCalled, "Dispose should be called on DisposableComponent"); + + Assert.Multiple(() => + { + Assert.That(AnotherDisposableComponent.DisposeCalled, Is.False, "Dispose should not be called on AnotherSingletonComponent because it belongs to main container"); + Assert.That(DisposableComponent.DisposeCalled, Is.True, "Dispose should be called on DisposableComponent"); + }); } public interface IInstanceToReplaceInNested diff --git a/src/NServiceBus.Core.Analyzer.Tests.Common/ForwardCancellationToken/ForwardFromPipelineTests.cs b/src/NServiceBus.Core.Analyzer.Tests.Common/ForwardCancellationToken/ForwardFromPipelineTests.cs index 50e92ae07f8..f4fa6c13a98 100644 --- a/src/NServiceBus.Core.Analyzer.Tests.Common/ForwardCancellationToken/ForwardFromPipelineTests.cs +++ b/src/NServiceBus.Core.Analyzer.Tests.Common/ForwardCancellationToken/ForwardFromPipelineTests.cs @@ -46,20 +46,20 @@ public void EachTypeHasABasicTest() var coveredTypes = pipelineTypes.Intersect(typesCoveredByThisTest).ToArray(); var missingTestCases = pipelineTypes.Except(typesCoveredByThisTest).ToArray(); - TestContext.WriteLine($"Types covered by a {nameof(RunTestOnType)} TestCase to ensure analyzer support:"); + TestContext.Out.WriteLine($"Types covered by a {nameof(RunTestOnType)} TestCase to ensure analyzer support:"); foreach (var t in coveredTypes) { - TestContext.WriteLine(t.FullName); + TestContext.Out.WriteLine(t.FullName); } - TestContext.WriteLine(); - TestContext.WriteLine($"Types missing a {nameof(RunTestOnType)} TestCase:"); + TestContext.Out.WriteLine(); + TestContext.Out.WriteLine($"Types missing a {nameof(RunTestOnType)} TestCase:"); foreach (var t in missingTestCases) { - TestContext.WriteLine(t.FullName); + TestContext.Out.WriteLine(t.FullName); } - NUnit.Framework.Assert.AreEqual(0, missingTestCases.Length, $"One or more pipeline type(s) are not covered by the {nameof(RunTestOnType)} test in this class."); + NUnit.Framework.Assert.That(missingTestCases.Length, Is.EqualTo(0), $"One or more pipeline type(s) are not covered by the {nameof(RunTestOnType)} test in this class."); } [TestCase(typeof(IHandleMessages<>), "TestMessage", "Handle", "TestMessage message, IMessageHandlerContext context")] diff --git a/src/NServiceBus.Core.Analyzer.Tests.Common/Helpers/AnalyzerTestFixture.cs b/src/NServiceBus.Core.Analyzer.Tests.Common/Helpers/AnalyzerTestFixture.cs index 33759976be1..74e5e570cbb 100644 --- a/src/NServiceBus.Core.Analyzer.Tests.Common/Helpers/AnalyzerTestFixture.cs +++ b/src/NServiceBus.Core.Analyzer.Tests.Common/Helpers/AnalyzerTestFixture.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using NServiceBus.UniformSession; +using NUnit.Framework; public class AnalyzerTestFixture where TAnalyzer : DiagnosticAnalyzer, new() { @@ -56,7 +57,7 @@ protected async Task Assert(string[] expectedDiagnosticIds, string markupCode, s .Select(diagnostic => (diagnostic.Location.SourceTree.FilePath, diagnostic.Location.SourceSpan, diagnostic.Id)) .ToList(); - NUnit.Framework.CollectionAssert.AreEqual(expectedSpansAndIds, actualSpansAndIds); + NUnit.Framework.Assert.That(actualSpansAndIds, Is.EqualTo(expectedSpansAndIds).AsCollection); } protected static async Task WriteCode(Project project) diff --git a/src/NServiceBus.Core.Analyzer.Tests.Common/Helpers/CodeFixTestFixture.cs b/src/NServiceBus.Core.Analyzer.Tests.Common/Helpers/CodeFixTestFixture.cs index 6efcb94f6bc..3545cabd372 100644 --- a/src/NServiceBus.Core.Analyzer.Tests.Common/Helpers/CodeFixTestFixture.cs +++ b/src/NServiceBus.Core.Analyzer.Tests.Common/Helpers/CodeFixTestFixture.cs @@ -8,6 +8,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; +using NUnit.Framework; public abstract class CodeFixTestFixture : AnalyzerTestFixture where TAnalyzer : DiagnosticAnalyzer, new() @@ -27,7 +28,7 @@ protected virtual async Task Assert(string original, string expected, bool fixMu expectedCodeFiles[i] = expectedCodeFiles[i].Replace("\r\n", "\n"); } - NUnit.Framework.Assert.AreEqual(expectedCodeFiles, actual); + NUnit.Framework.Assert.That(actual, Is.EqualTo(expectedCodeFiles)); } async Task Fix(string[] codeFiles, bool fixMustCompile, CancellationToken cancellationToken, IEnumerable originalCompilerDiagnostics = null) @@ -46,7 +47,7 @@ async Task Fix(string[] codeFiles, bool fixMustCompile, CancellationTo } else if (fixMustCompile) { - NUnit.Framework.CollectionAssert.AreEqual(originalCompilerDiagnostics, compilerDiagnostics, "Fix introduced new compiler diagnostics."); + NUnit.Framework.Assert.That(compilerDiagnostics, Is.EqualTo(originalCompilerDiagnostics).AsCollection, "Fix introduced new compiler diagnostics."); } var compilation = await project.GetCompilationAsync(cancellationToken); diff --git a/src/NServiceBus.Core.Analyzer.Tests.Roslyn4/NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj b/src/NServiceBus.Core.Analyzer.Tests.Roslyn4/NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj index 0d902c51447..99cb73ace15 100644 --- a/src/NServiceBus.Core.Analyzer.Tests.Roslyn4/NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj +++ b/src/NServiceBus.Core.Analyzer.Tests.Roslyn4/NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj @@ -17,6 +17,7 @@ + diff --git a/src/NServiceBus.Core.Tests/API/Types.cs b/src/NServiceBus.Core.Tests/API/Types.cs index ea38cadc225..d357c09fcab 100644 --- a/src/NServiceBus.Core.Tests/API/Types.cs +++ b/src/NServiceBus.Core.Tests/API/Types.cs @@ -20,6 +20,6 @@ public static void StaticTypesDoNotHaveInterfacePrefixes() Console.Error.WriteViolators(violators); - Assert.IsEmpty(violators); + Assert.That(violators, Is.Empty); } } diff --git a/src/NServiceBus.Core.Tests/AssemblyScanner/AssemblyScanningComponentTests.cs b/src/NServiceBus.Core.Tests/AssemblyScanner/AssemblyScanningComponentTests.cs index d69dbafa55f..e6f4826fdcf 100644 --- a/src/NServiceBus.Core.Tests/AssemblyScanner/AssemblyScanningComponentTests.cs +++ b/src/NServiceBus.Core.Tests/AssemblyScanner/AssemblyScanningComponentTests.cs @@ -23,6 +23,6 @@ public void Should_initialize_scanner_with_custom_path_when_provided() var foundTypeFromScannedPath = component.AvailableTypes.Any(x => x.Name == "NestedClass"); - Assert.True(foundTypeFromScannedPath, "Was expected to scan a custom path, but 'nested.dll' was not scanned."); + Assert.That(foundTypeFromScannedPath, Is.True, "Was expected to scan a custom path, but 'nested.dll' was not scanned."); } } diff --git a/src/NServiceBus.Core.Tests/AssemblyScanner/When_configuring_assembly_scanning.cs b/src/NServiceBus.Core.Tests/AssemblyScanner/When_configuring_assembly_scanning.cs index ee041bc435d..2ced0d0b391 100644 --- a/src/NServiceBus.Core.Tests/AssemblyScanner/When_configuring_assembly_scanning.cs +++ b/src/NServiceBus.Core.Tests/AssemblyScanner/When_configuring_assembly_scanning.cs @@ -13,6 +13,6 @@ public void Should_provide_reflection_backdoor_via_endpoint_config() // * docs - https://github.com/Particular/docs.particular.net/blob/master/Snippets/Core/Core_7/Headers/Writers/EndpointConfigurationExtensions.cs // * metrics tests - https://github.com/Particular/NServiceBus.Metrics.PerformanceCounters/blob/master/src/NServiceBus.Metrics.PerformanceCounters.Tests/EndpointConfigurationExtensions.cs // * we also have users relying on this to prevent assembly scanning from happening - Assert.NotNull(typeof(EndpointConfiguration).GetMethod("TypesToScanInternal", BindingFlags.NonPublic | BindingFlags.Instance)); + Assert.That(typeof(EndpointConfiguration).GetMethod("TypesToScanInternal", BindingFlags.NonPublic | BindingFlags.Instance), Is.Not.Null); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/AssemblyScanner/When_directory_with_messages_referencing_core_or_interfaces_is_scanned.cs b/src/NServiceBus.Core.Tests/AssemblyScanner/When_directory_with_messages_referencing_core_or_interfaces_is_scanned.cs index 1edc14cddca..a14c2c25ab3 100644 --- a/src/NServiceBus.Core.Tests/AssemblyScanner/When_directory_with_messages_referencing_core_or_interfaces_is_scanned.cs +++ b/src/NServiceBus.Core.Tests/AssemblyScanner/When_directory_with_messages_referencing_core_or_interfaces_is_scanned.cs @@ -19,7 +19,7 @@ public void Assemblies_should_be_scanned() var result = scanner.GetScannableAssemblies(); var assemblyFullNames = result.Assemblies.Select(a => a.GetName().Name).ToList(); - CollectionAssert.Contains(assemblyFullNames, "Messages.Referencing.Core"); - CollectionAssert.Contains(assemblyFullNames, "Messages.Referencing.MessageInterfaces"); + Assert.That(assemblyFullNames, Has.Member("Messages.Referencing.Core")); + Assert.That(assemblyFullNames, Has.Member("Messages.Referencing.MessageInterfaces")); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/AssemblyScanner/When_directory_with_no_reference_dlls_is_scanned.cs b/src/NServiceBus.Core.Tests/AssemblyScanner/When_directory_with_no_reference_dlls_is_scanned.cs index cb0e60491e4..748e9670d39 100644 --- a/src/NServiceBus.Core.Tests/AssemblyScanner/When_directory_with_no_reference_dlls_is_scanned.cs +++ b/src/NServiceBus.Core.Tests/AssemblyScanner/When_directory_with_no_reference_dlls_is_scanned.cs @@ -16,7 +16,7 @@ public void Assemblies_without_nsb_reference_are_skipped() var result = scanner.GetScannableAssemblies(); - Assert.That(result.Assemblies.Contains(assemblyToScan), Is.False); + Assert.That(result.Assemblies, Does.Not.Contain(assemblyToScan)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/AssemblyScanner/When_scanning_assemblies_with_circular_dependencies.cs b/src/NServiceBus.Core.Tests/AssemblyScanner/When_scanning_assemblies_with_circular_dependencies.cs index 7d3cf55e2d2..ca19351a205 100644 --- a/src/NServiceBus.Core.Tests/AssemblyScanner/When_scanning_assemblies_with_circular_dependencies.cs +++ b/src/NServiceBus.Core.Tests/AssemblyScanner/When_scanning_assemblies_with_circular_dependencies.cs @@ -18,7 +18,10 @@ public void ReferencesNServiceBus_circular() var result = scanner.GetScannableAssemblies(); - Assert.That(result.Assemblies.Any(a => a.FullName.Contains("ClassLibraryA")), Is.False); - Assert.That(result.Assemblies.Any(a => a.FullName.Contains("ClassLibraryB")), Is.False); + Assert.Multiple(() => + { + Assert.That(result.Assemblies.Any(a => a.FullName.Contains("ClassLibraryA")), Is.False); + Assert.That(result.Assemblies.Any(a => a.FullName.Contains("ClassLibraryB")), Is.False); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/AssemblyScanner/When_scanning_directory_with_nested_directories.cs b/src/NServiceBus.Core.Tests/AssemblyScanner/When_scanning_directory_with_nested_directories.cs index 9f1b15a2e09..14dace35a4b 100644 --- a/src/NServiceBus.Core.Tests/AssemblyScanner/When_scanning_directory_with_nested_directories.cs +++ b/src/NServiceBus.Core.Tests/AssemblyScanner/When_scanning_directory_with_nested_directories.cs @@ -21,8 +21,11 @@ public void Should_not_scan_nested_directories_by_default() var foundTypeFromNestedAssembly = result.Types.Any(x => x.Name == "NestedClass"); var foundTypeFromDerivedAssembly = result.Types.Any(x => x.Name == "DerivedClass"); - Assert.False(foundTypeFromNestedAssembly, "Was expected not to scan nested assemblies, but 'nested.dll' was scanned."); - Assert.False(foundTypeFromDerivedAssembly, "Was expected not to scan nested assemblies, but 'Derived.dll' was scanned."); + Assert.Multiple(() => + { + Assert.That(foundTypeFromNestedAssembly, Is.False, "Was expected not to scan nested assemblies, but 'nested.dll' was scanned."); + Assert.That(foundTypeFromDerivedAssembly, Is.False, "Was expected not to scan nested assemblies, but 'Derived.dll' was scanned."); + }); } [Test] @@ -39,7 +42,10 @@ public void Should_scan_nested_directories_if_requested() var foundTypeFromNestedAssembly = result.Types.Any(x => x.Name == "NestedClass"); var foundTypeFromDerivedAssembly = result.Types.Any(x => x.Name == "DerivedClass"); - Assert.True(foundTypeFromNestedAssembly, "Was expected to scan nested assemblies, but 'nested.dll' was not scanned."); - Assert.True(foundTypeFromDerivedAssembly, "Was expected to scan nested assemblies, but 'Derived.dll' was not scanned."); + Assert.Multiple(() => + { + Assert.That(foundTypeFromNestedAssembly, Is.True, "Was expected to scan nested assemblies, but 'nested.dll' was not scanned."); + Assert.That(foundTypeFromDerivedAssembly, Is.True, "Was expected to scan nested assemblies, but 'Derived.dll' was not scanned."); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/AssemblyScanner/When_using_type_forwarding.cs b/src/NServiceBus.Core.Tests/AssemblyScanner/When_using_type_forwarding.cs index 947c51bd1ac..5379f65d114 100644 --- a/src/NServiceBus.Core.Tests/AssemblyScanner/When_using_type_forwarding.cs +++ b/src/NServiceBus.Core.Tests/AssemblyScanner/When_using_type_forwarding.cs @@ -41,6 +41,6 @@ public void Should_scan_assemblies_indicated_by_the_forwarding_metadata() var result = scanner.GetScannableAssemblies(); var assemblyFullNames = result.Assemblies.Select(a => a.GetName().Name).ToList(); - CollectionAssert.IsSubsetOf(assemblyNamesOfForwardedTypes, assemblyFullNames); + Assert.That(assemblyNamesOfForwardedTypes, Is.SubsetOf(assemblyFullNames)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/AssemblyScanner/When_validating_assemblies.cs b/src/NServiceBus.Core.Tests/AssemblyScanner/When_validating_assemblies.cs index 2b310f87169..9e7670c3e9d 100644 --- a/src/NServiceBus.Core.Tests/AssemblyScanner/When_validating_assemblies.cs +++ b/src/NServiceBus.Core.Tests/AssemblyScanner/When_validating_assemblies.cs @@ -16,8 +16,11 @@ public void Should_not_validate_system_assemblies() { AssemblyValidator.ValidateAssemblyFile(assembly.Location, out var shouldLoad, out var reason); - Assert.IsFalse(shouldLoad, $"Should not validate {assembly.FullName}"); - Assert.That(reason == "File is a .NET runtime assembly."); + Assert.Multiple(() => + { + Assert.That(shouldLoad, Is.False, $"Should not validate {assembly.FullName}"); + Assert.That(reason, Is.EqualTo("File is a .NET runtime assembly.")); + }); } } @@ -26,8 +29,11 @@ public void Should_validate_NServiceBus_Core_assembly() { AssemblyValidator.ValidateAssemblyFile(typeof(EndpointConfiguration).Assembly.Location, out var shouldLoad, out var reason); - Assert.IsTrue(shouldLoad); - Assert.That(reason == "File is a .NET assembly."); + Assert.Multiple(() => + { + Assert.That(shouldLoad, Is.True); + Assert.That(reason, Is.EqualTo("File is a .NET assembly.")); + }); } [Test] @@ -35,7 +41,10 @@ public void Should_validate_non_system_assemblies() { AssemblyValidator.ValidateAssemblyFile(GetType().Assembly.Location, out var shouldLoad, out var reason); - Assert.IsTrue(shouldLoad); - Assert.That(reason == "File is a .NET assembly."); + Assert.Multiple(() => + { + Assert.That(shouldLoad, Is.True); + Assert.That(reason, Is.EqualTo("File is a .NET assembly.")); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Audit/AuditConfigReaderTests.cs b/src/NServiceBus.Core.Tests/Audit/AuditConfigReaderTests.cs index 73b29db84dc..70b41f164d5 100644 --- a/src/NServiceBus.Core.Tests/Audit/AuditConfigReaderTests.cs +++ b/src/NServiceBus.Core.Tests/Audit/AuditConfigReaderTests.cs @@ -14,8 +14,11 @@ public void ShouldUseExplicitValueInSettingsIfPresent() settingsHolder.Set(new AuditConfigReader.Result(configuredAddress, null)); - Assert.True(settingsHolder.TryGetAuditQueueAddress(out var address)); - Assert.AreEqual(configuredAddress, address); + Assert.Multiple(() => + { + Assert.That(settingsHolder.TryGetAuditQueueAddress(out var address), Is.True); + Assert.That(address, Is.EqualTo(configuredAddress)); + }); } [Test] @@ -26,13 +29,16 @@ public void ShouldReturnConfiguredExpiration() settingsHolder.Set(new AuditConfigReader.Result("someAddress", configuredExpiration)); - Assert.True(settingsHolder.TryGetAuditMessageExpiration(out var expiration)); - Assert.AreEqual(configuredExpiration, expiration); + Assert.Multiple(() => + { + Assert.That(settingsHolder.TryGetAuditMessageExpiration(out var expiration), Is.True); + Assert.That(expiration, Is.EqualTo(configuredExpiration)); + }); } [Test] public void ShouldReturnFalseIfNoExpirationIsConfigured() { - Assert.False(new SettingsHolder().TryGetAuditMessageExpiration(out _)); + Assert.That(new SettingsHolder().TryGetAuditMessageExpiration(out _), Is.False); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Causation/AttachCausationHeadersBehaviorTests.cs b/src/NServiceBus.Core.Tests/Causation/AttachCausationHeadersBehaviorTests.cs index 439be9b70fc..63ba543e480 100644 --- a/src/NServiceBus.Core.Tests/Causation/AttachCausationHeadersBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/Causation/AttachCausationHeadersBehaviorTests.cs @@ -20,7 +20,7 @@ public async Task Should_generate_new_conversation_id_when_sending_outside_of_ha await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(generatedId, context.Headers[Headers.ConversationId]); + Assert.That(context.Headers[Headers.ConversationId], Is.EqualTo(generatedId)); } [Test] @@ -39,7 +39,7 @@ public async Task Should_set_the_conversation_id_to_conversation_id_of_incoming_ await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(incomingConversationId, context.Headers[Headers.ConversationId]); + Assert.That(context.Headers[Headers.ConversationId], Is.EqualTo(incomingConversationId)); } [Test] @@ -58,7 +58,7 @@ public async Task When_no_incoming_message_should_not_override_a_conversation_id await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(userConversationId, context.Headers[Headers.ConversationId]); + Assert.That(context.Headers[Headers.ConversationId], Is.EqualTo(userConversationId)); } [Test] @@ -83,7 +83,7 @@ public void When_user_defined_conversation_id_would_overwrite_incoming_conversat var exception = Assert.ThrowsAsync(() => behavior.Invoke(context, ctx => Task.CompletedTask)); - Assert.AreEqual($"Cannot set the {Headers.ConversationId} header to '{userDefinedConversationId}' as it cannot override the incoming header value ('{incomingConversationId}'). To start a new conversation use sendOptions.StartNewConversation().", exception.Message); + Assert.That(exception.Message, Is.EqualTo($"Cannot set the {Headers.ConversationId} header to '{userDefinedConversationId}' as it cannot override the incoming header value ('{incomingConversationId}'). To start a new conversation use sendOptions.StartNewConversation().")); } [Test] @@ -96,7 +96,7 @@ public async Task Should_set_the_related_to_header_with_the_id_of_the_current_me await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual("the message id", context.Headers[Headers.RelatedTo]); + Assert.That(context.Headers[Headers.RelatedTo], Is.EqualTo("the message id")); } string ReturnDefaultConversationId(IOutgoingLogicalMessageContext context) diff --git a/src/NServiceBus.Core.Tests/Causation/CustomConversationIdStrategyTests.cs b/src/NServiceBus.Core.Tests/Causation/CustomConversationIdStrategyTests.cs index a621b3a5022..a4c152842b1 100644 --- a/src/NServiceBus.Core.Tests/Causation/CustomConversationIdStrategyTests.cs +++ b/src/NServiceBus.Core.Tests/Causation/CustomConversationIdStrategyTests.cs @@ -26,13 +26,13 @@ public void Should_wrap_exceptions_for_better_debugging() { var ex = Assert.Throws(() => Invoke(_ => throw new Exception("User invocation failed"))); - StringAssert.Contains("Failed to execute the custom conversation ID strategy", ex.Message); + Assert.That(ex.Message, Does.Contain("Failed to execute the custom conversation ID strategy")); } [Test] public void Should_default_to_combguid_id() { - Assert.True(Guid.TryParse(Invoke(_ => ConversationId.Default), out var _)); + Assert.That(Guid.TryParse(Invoke(_ => ConversationId.Default), out var _), Is.True); } static string Invoke(Func strategy) diff --git a/src/NServiceBus.Core.Tests/Config/When_configuring_transport_twice.cs b/src/NServiceBus.Core.Tests/Config/When_configuring_transport_twice.cs index 61270a52950..0e7cca2b017 100644 --- a/src/NServiceBus.Core.Tests/Config/When_configuring_transport_twice.cs +++ b/src/NServiceBus.Core.Tests/Config/When_configuring_transport_twice.cs @@ -25,8 +25,11 @@ public async Task Last_one_wins() await endpoint.Stop(); - Assert.That(transport1.Initialized, Is.False, "First transport should not be initialized"); - Assert.That(transport2.Initialized, Is.True, "Second transport should be initialized"); + Assert.Multiple(() => + { + Assert.That(transport1.Initialized, Is.False, "First transport should not be initialized"); + Assert.That(transport2.Initialized, Is.True, "Second transport should be initialized"); + }); } class FakeTransportDefinition : TransportDefinition, IMessageDrivenSubscriptionTransport diff --git a/src/NServiceBus.Core.Tests/Config/When_scanning_assemblies.cs b/src/NServiceBus.Core.Tests/Config/When_scanning_assemblies.cs index b3748d81a85..9559979cd5b 100644 --- a/src/NServiceBus.Core.Tests/Config/When_scanning_assemblies.cs +++ b/src/NServiceBus.Core.Tests/Config/When_scanning_assemblies.cs @@ -22,22 +22,22 @@ public void SetUp() [Ignore("Does not work")] public void Should_for_our_code_exclude_everything_but_NServiceBus_by_default() { - CollectionAssert.AreEquivalent(System.Array.Empty(), - foundAssemblies.Where(a => !a.FullName.StartsWith("NServiceBus") && !a.FullName.StartsWith("Obsolete"))); + Assert.That(foundAssemblies.Where(a => !a.FullName.StartsWith("NServiceBus") && !a.FullName.StartsWith("Obsolete")), + Is.EquivalentTo(System.Array.Empty())); } [Test] public void Should_exclude_system_assemblies() { - CollectionAssert.AreEquivalent(System.Array.Empty(), - foundAssemblies.Where(a => a.FullName.StartsWith("System")).ToArray()); + Assert.That(foundAssemblies.Where(a => a.FullName.StartsWith("System")).ToArray(), + Is.EquivalentTo(System.Array.Empty())); } [Test] public void Should_exclude_nhibernate_assemblies() { - CollectionAssert.AreEquivalent(System.Array.Empty(), - foundAssemblies.Where(a => a.FullName.StartsWith("nhibernate", System.StringComparison.OrdinalIgnoreCase)).ToArray()); + Assert.That(foundAssemblies.Where(a => a.FullName.StartsWith("nhibernate", System.StringComparison.OrdinalIgnoreCase)).ToArray(), + Is.EquivalentTo(System.Array.Empty())); } static List GetAssembliesInDirectory(string path, params string[] assembliesToSkip) diff --git a/src/NServiceBus.Core.Tests/Config/When_starting_endpoint_without_configuring_serializer.cs b/src/NServiceBus.Core.Tests/Config/When_starting_endpoint_without_configuring_serializer.cs index 0b1c8110bcd..70c4c938d45 100644 --- a/src/NServiceBus.Core.Tests/Config/When_starting_endpoint_without_configuring_serializer.cs +++ b/src/NServiceBus.Core.Tests/Config/When_starting_endpoint_without_configuring_serializer.cs @@ -16,6 +16,6 @@ public void Should_throw() scanner.ExcludeAssemblies("NServiceBus.Core.Tests.dll"); var exception = Assert.ThrowsAsync(async () => await Endpoint.Create(configuration).ConfigureAwait(false)); - Assert.True(exception.Message.StartsWith("A serializer has not been configured")); + Assert.That(exception.Message, Does.StartWith("A serializer has not been configured")); } } diff --git a/src/NServiceBus.Core.Tests/Config/When_using_initialization.cs b/src/NServiceBus.Core.Tests/Config/When_using_initialization.cs index 176887571b0..ef99dc3e9c2 100644 --- a/src/NServiceBus.Core.Tests/Config/When_using_initialization.cs +++ b/src/NServiceBus.Core.Tests/Config/When_using_initialization.cs @@ -16,7 +16,7 @@ public void Should_throw_meaningful_exception() var ae = Assert.Throws(() => EndpointCreator.Create(endpointConfiguration, new ServiceCollection())); var expected = $"Unable to create the type '{nameof(FeatureWithInitialization)}'. Types implementing '{nameof(INeedInitialization)}' must have a public parameterless (default) constructor."; - Assert.AreEqual(expected, ae.Message); + Assert.That(ae.Message, Is.EqualTo(expected)); } public class FeatureWithInitialization : INeedInitialization diff --git a/src/NServiceBus.Core.Tests/ContextBagTests.cs b/src/NServiceBus.Core.Tests/ContextBagTests.cs index f8c7bec3dd7..7ff010f501c 100644 --- a/src/NServiceBus.Core.Tests/ContextBagTests.cs +++ b/src/NServiceBus.Core.Tests/ContextBagTests.cs @@ -14,7 +14,7 @@ public void ShouldAllowMonkeyPatching() contextBag.Set("MonkeyPatch", "some string"); ((IReadOnlyContextBag)contextBag).TryGet("MonkeyPatch", out string theValue); - Assert.AreEqual("some string", theValue); + Assert.That(theValue, Is.EqualTo("some string")); } [Test] @@ -29,8 +29,11 @@ public void SetOnRoot_should_set_value_on_root_context() context.SetOnRoot(key, 42); - Assert.AreEqual(42, root.Get(key), "should store value on root context"); - Assert.AreEqual(42, context.Get(key), "stored value should be readable in the writing context"); - Assert.AreEqual(42, fork.Get(key), "stored value should be visible to a forked context"); + Assert.Multiple(() => + { + Assert.That(root.Get(key), Is.EqualTo(42), "should store value on root context"); + Assert.That(context.Get(key), Is.EqualTo(42), "stored value should be readable in the writing context"); + Assert.That(fork.Get(key), Is.EqualTo(42), "stored value should be visible to a forked context"); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/ConventionsTests.cs b/src/NServiceBus.Core.Tests/ConventionsTests.cs index 368919a1aa7..920c8c24fee 100644 --- a/src/NServiceBus.Core.Tests/ConventionsTests.cs +++ b/src/NServiceBus.Core.Tests/ConventionsTests.cs @@ -10,7 +10,7 @@ public class ConventionsTests public void IsMessageType_should_return_false_for_unknown_type() { var conventions = new Conventions(); - Assert.IsFalse(conventions.IsMessageType(typeof(NoAMessage))); + Assert.That(conventions.IsMessageType(typeof(NoAMessage)), Is.False); } public class NoAMessage @@ -22,7 +22,7 @@ public class NoAMessage public void IsMessageType_should_return_true_for_IMessage() { var conventions = new Conventions(); - Assert.IsTrue(conventions.IsMessageType(typeof(MyMessage))); + Assert.That(conventions.IsMessageType(typeof(MyMessage)), Is.True); } public class MyMessage : IMessage @@ -34,7 +34,7 @@ public class MyMessage : IMessage public void IsMessageType_should_return_true_for_ICommand() { var conventions = new Conventions(); - Assert.IsTrue(conventions.IsMessageType(typeof(MyCommand))); + Assert.That(conventions.IsMessageType(typeof(MyCommand)), Is.True); } public class MyCommand : ICommand @@ -46,7 +46,7 @@ public class MyCommand : ICommand public void IsMessageType_should_return_true_for_IEvent() { var conventions = new Conventions(); - Assert.IsTrue(conventions.IsMessageType(typeof(MyEvent))); + Assert.That(conventions.IsMessageType(typeof(MyEvent)), Is.True); } public class MyEvent : IEvent @@ -59,7 +59,7 @@ public void IsMessageType_should_return_true_for_systemMessage() { var conventions = new Conventions(); conventions.AddSystemMessagesConventions(type => type == typeof(MySystemMessage)); - Assert.IsTrue(conventions.IsMessageType(typeof(MySystemMessage))); + Assert.That(conventions.IsMessageType(typeof(MySystemMessage)), Is.True); } public class MySystemMessage @@ -75,7 +75,7 @@ public void IsCommandType_should_return_false_for_NServiceBus_types() { var conventions = new Conventions(); conventions.DefineCommandTypeConventions(t => t.Assembly == typeof(Conventions).Assembly); - Assert.IsFalse(conventions.IsCommandType(typeof(Conventions))); + Assert.That(conventions.IsCommandType(typeof(Conventions)), Is.False); } [Test] @@ -84,7 +84,7 @@ public void IsMessageType_should_return_false_for_NServiceBus_types() var conventions = new Conventions(); conventions.DefineMessageTypeConvention(t => t.Assembly == typeof(Conventions).Assembly); - Assert.IsFalse(conventions.IsMessageType(typeof(Conventions))); + Assert.That(conventions.IsMessageType(typeof(Conventions)), Is.False); } [Test] @@ -92,7 +92,7 @@ public void IsEventType_should_return_false_for_NServiceBus_types() { var conventions = new Conventions(); conventions.DefineEventTypeConventions(t => t.Assembly == typeof(Conventions).Assembly); - Assert.IsFalse(conventions.IsEventType(typeof(Conventions))); + Assert.That(conventions.IsEventType(typeof(Conventions)), Is.False); } public class MyConventionExpress @@ -105,7 +105,7 @@ public void IsCommandType_should_return_true_for_matching_type() var conventions = new Conventions(); conventions.DefineCommandTypeConventions(t => t.Assembly == typeof(Conventions).Assembly || t == typeof(MyConventionCommand)); - Assert.IsTrue(conventions.IsCommandType(typeof(MyConventionCommand))); + Assert.That(conventions.IsCommandType(typeof(MyConventionCommand)), Is.True); } public class MyConventionCommand @@ -118,7 +118,7 @@ public void IsMessageType_should_return_true_for_matching_type() var conventions = new Conventions(); conventions.DefineMessageTypeConvention(t => t.Assembly == typeof(Conventions).Assembly || t == typeof(MyConventionMessage)); - Assert.IsTrue(conventions.IsMessageType(typeof(MyConventionMessage))); + Assert.That(conventions.IsMessageType(typeof(MyConventionMessage)), Is.True); } public class MyConventionMessage @@ -131,7 +131,7 @@ public void IsEventType_should_return_true_for_matching_type() var conventions = new Conventions(); conventions.DefineEventTypeConventions(t => t.Assembly == typeof(Conventions).Assembly || t == typeof(MyConventionEvent)); - Assert.IsTrue(conventions.IsEventType(typeof(MyConventionEvent))); + Assert.That(conventions.IsEventType(typeof(MyConventionEvent)), Is.True); } public class MyConventionEvent @@ -147,7 +147,7 @@ public void IsCommandType_should_return_true_for_matching_type() { var conventions = new Conventions(); conventions.Add(new MyConvention()); - Assert.IsTrue(conventions.IsCommandType(typeof(MyConventionCommand))); + Assert.That(conventions.IsCommandType(typeof(MyConventionCommand)), Is.True); } [Test] @@ -155,7 +155,7 @@ public void IsEventType_should_return_true_for_matching_type() { var conventions = new Conventions(); conventions.Add(new MyConvention()); - Assert.IsTrue(conventions.IsEventType(typeof(MyConventionEvent))); + Assert.That(conventions.IsEventType(typeof(MyConventionEvent)), Is.True); } [Test] @@ -163,7 +163,7 @@ public void IsMessageType_should_return_true_for_matching_type() { var conventions = new Conventions(); conventions.Add(new MyConvention()); - Assert.IsTrue(conventions.IsMessageType(typeof(MyConventionMessage))); + Assert.That(conventions.IsMessageType(typeof(MyConventionMessage)), Is.True); } [Test] @@ -171,7 +171,7 @@ public void IsCommandType_should_return_true_for_default_convention() { var conventions = new Conventions(); conventions.Add(new MyConvention()); - Assert.IsTrue(conventions.IsCommandType(typeof(DefaultConventionCommand))); + Assert.That(conventions.IsCommandType(typeof(DefaultConventionCommand)), Is.True); } [Test] @@ -179,7 +179,7 @@ public void IsEventType_should_return_true_for_default_convention() { var conventions = new Conventions(); conventions.Add(new MyConvention()); - Assert.IsTrue(conventions.IsEventType(typeof(DefaultConventionEvent))); + Assert.That(conventions.IsEventType(typeof(DefaultConventionEvent)), Is.True); } [Test] @@ -187,7 +187,7 @@ public void IsMessageType_should_return_true_for_default_convention() { var conventions = new Conventions(); conventions.Add(new MyConvention()); - Assert.IsTrue(conventions.IsMessageType(typeof(DefaultConventionMessage))); + Assert.That(conventions.IsMessageType(typeof(DefaultConventionMessage)), Is.True); } class DefaultConventionCommand : ICommand { } diff --git a/src/NServiceBus.Core.Tests/DataBus/DataBusConfigurationTests.cs b/src/NServiceBus.Core.Tests/DataBus/DataBusConfigurationTests.cs index 8c3dd6c14ef..28897bf860a 100644 --- a/src/NServiceBus.Core.Tests/DataBus/DataBusConfigurationTests.cs +++ b/src/NServiceBus.Core.Tests/DataBus/DataBusConfigurationTests.cs @@ -20,7 +20,7 @@ public void Should_allow_multiple_deserializers_to_be_used() .AddDeserializer(new FakeDataBusSerializer("content-type-1")) .AddDeserializer(new FakeDataBusSerializer("content-type-2")); - Assert.AreEqual(endpointConfiguration.Settings.Get>(NServiceBus.Features.DataBus.AdditionalDataBusDeserializersKey).Count, 2); + Assert.That(endpointConfiguration.Settings.Get>(NServiceBus.Features.DataBus.AdditionalDataBusDeserializersKey).Count, Is.EqualTo(2)); } [Test] diff --git a/src/NServiceBus.Core.Tests/DataBus/DataBusDeserializerTests.cs b/src/NServiceBus.Core.Tests/DataBus/DataBusDeserializerTests.cs index 72eaa1f62e8..7737440931b 100644 --- a/src/NServiceBus.Core.Tests/DataBus/DataBusDeserializerTests.cs +++ b/src/NServiceBus.Core.Tests/DataBus/DataBusDeserializerTests.cs @@ -23,7 +23,7 @@ public void Should_deserialized_with_the_serializer_used() var deserializedProperty = deserializer.Deserialize(jsonSerializer.ContentType, typeof(string), stream); - Assert.AreEqual(somePropertyValue, deserializedProperty); + Assert.That(deserializedProperty, Is.EqualTo(somePropertyValue)); } } @@ -41,7 +41,7 @@ public void Should_throw_if_serializer_used_not_available() var ex = Assert.Throws(() => deserializer.Deserialize("other-serializer-not-configured", typeof(string), stream)); - StringAssert.Contains("other-serializer-not-configured", ex.Message); + Assert.That(ex.Message, Does.Contain("other-serializer-not-configured")); } } @@ -54,7 +54,7 @@ public void Should_try_main_and_fallback_when_serializer_used_not_known() var somePropertyValue = "test"; var deserializedProperty = deserializer.Deserialize(null, typeof(string), new MemoryStream()); - Assert.AreEqual(somePropertyValue, deserializedProperty); + Assert.That(deserializedProperty, Is.EqualTo(somePropertyValue)); } [Test] diff --git a/src/NServiceBus.Core.Tests/DataBus/FileShare/AcceptanceTests.cs b/src/NServiceBus.Core.Tests/DataBus/FileShare/AcceptanceTests.cs index e8694697eba..823926b9117 100644 --- a/src/NServiceBus.Core.Tests/DataBus/FileShare/AcceptanceTests.cs +++ b/src/NServiceBus.Core.Tests/DataBus/FileShare/AcceptanceTests.cs @@ -37,7 +37,7 @@ public async Task Should_handle_be_able_to_read_stored_values() using (var stream = await dataBus.Get(key)) using (var streamReader = new StreamReader(stream)) { - Assert.AreEqual(await streamReader.ReadToEndAsync(), content); + Assert.That(await streamReader.ReadToEndAsync(), Is.EqualTo(content)); } } @@ -53,7 +53,7 @@ public async Task Should_handle_be_able_to_read_stored_values_concurrently() using (var stream = await dataBus.Get(key)) using (var streamReader = new StreamReader(stream)) { - Assert.AreEqual(await streamReader.ReadToEndAsync(), content); + Assert.That(await streamReader.ReadToEndAsync(), Is.EqualTo(content)); } }); } @@ -68,7 +68,7 @@ public async Task Should_handle_be_able_to_read_stored_values_when_received_from using (var stream = await dataBus.Get(key.Replace(Path.DirectorySeparatorChar, pathSeparator))) using (var streamReader = new StreamReader(stream)) { - Assert.AreEqual(await streamReader.ReadToEndAsync(), content); + Assert.That(await streamReader.ReadToEndAsync(), Is.EqualTo(content)); } } @@ -76,7 +76,7 @@ public async Task Should_handle_be_able_to_read_stored_values_when_received_from public async Task Should_handle_max_ttl() { await Put("Test", TimeSpan.MaxValue); - Assert.True(Directory.Exists(Path.Combine(basePath, DateTime.MaxValue.ToString("yyyy-MM-dd_HH")))); + Assert.That(Directory.Exists(Path.Combine(basePath, DateTime.MaxValue.ToString("yyyy-MM-dd_HH"))), Is.True); } [Test] @@ -85,6 +85,6 @@ public async Task Should_honor_the_ttl_limit() dataBus.MaxMessageTimeToLive = TimeSpan.FromDays(1); await Put("Test", TimeSpan.MaxValue); - Assert.True(Directory.Exists(Path.Combine(basePath, DateTime.UtcNow.AddDays(1).ToString("yyyy-MM-dd_HH")))); + Assert.That(Directory.Exists(Path.Combine(basePath, DateTime.UtcNow.AddDays(1).ToString("yyyy-MM-dd_HH"))), Is.True); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/DataBus/When_applying_the_databus_message_mutator_to_outgoing_messages.cs b/src/NServiceBus.Core.Tests/DataBus/When_applying_the_databus_message_mutator_to_outgoing_messages.cs index 6b63a3fbeae..e320b50b680 100644 --- a/src/NServiceBus.Core.Tests/DataBus/When_applying_the_databus_message_mutator_to_outgoing_messages.cs +++ b/src/NServiceBus.Core.Tests/DataBus/When_applying_the_databus_message_mutator_to_outgoing_messages.cs @@ -31,7 +31,7 @@ public async Task Outgoing_databus_properties_should_be_dehydrated() await sendBehavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(TimeSpan.MaxValue, fakeDatabus.TTBRUsed); + Assert.That(fakeDatabus.TTBRUsed, Is.EqualTo(TimeSpan.MaxValue)); } [Test] @@ -52,7 +52,7 @@ public async Task Serializer_header_should_be_set() await sendBehavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(serializer.ContentType, context.Headers[Headers.DataBusConfigContentType]); + Assert.That(context.Headers[Headers.DataBusConfigContentType], Is.EqualTo(serializer.ContentType)); } [Test] @@ -74,7 +74,7 @@ public async Task Time_to_live_should_be_passed_on_the_databus() await sendBehavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(TimeSpan.FromMinutes(1), fakeDatabus.TTBRUsed); + Assert.That(fakeDatabus.TTBRUsed, Is.EqualTo(TimeSpan.FromMinutes(1))); } class FakeDataBus : IDataBus diff --git a/src/NServiceBus.Core.Tests/DateTimeExtensionsTests.cs b/src/NServiceBus.Core.Tests/DateTimeExtensionsTests.cs index d0a4fc862f7..00328ca0276 100644 --- a/src/NServiceBus.Core.Tests/DateTimeExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/DateTimeExtensionsTests.cs @@ -14,7 +14,7 @@ public void When_roundtripping_constructed_date_should_be_equal() var dateString = DateTimeOffsetHelper.ToWireFormattedString(date); var result = DateTimeOffsetHelper.ToDateTimeOffset(dateString); - Assert.AreEqual(date, result); + Assert.That(result, Is.EqualTo(date)); } [Test] @@ -24,15 +24,18 @@ public void When_roundtripping_UtcNow_should_be_accurate_to_microseconds() var dateString = DateTimeOffsetHelper.ToWireFormattedString(date); var result = DateTimeOffsetHelper.ToDateTimeOffset(dateString); - Assert.AreEqual(date.Year, result.Year); - Assert.AreEqual(date.Month, result.Month); - Assert.AreEqual(date.Day, result.Day); - Assert.AreEqual(date.Hour, result.Hour); - Assert.AreEqual(date.Minute, result.Minute); - Assert.AreEqual(date.Second, result.Second); - Assert.AreEqual(date.Millisecond, result.Millisecond); - Assert.AreEqual(date.Microseconds(), result.Microseconds()); - Assert.AreEqual(date.Offset, result.Offset); + Assert.Multiple(() => + { + Assert.That(result.Year, Is.EqualTo(date.Year)); + Assert.That(result.Month, Is.EqualTo(date.Month)); + Assert.That(result.Day, Is.EqualTo(date.Day)); + Assert.That(result.Hour, Is.EqualTo(date.Hour)); + Assert.That(result.Minute, Is.EqualTo(date.Minute)); + Assert.That(result.Second, Is.EqualTo(date.Second)); + Assert.That(result.Millisecond, Is.EqualTo(date.Millisecond)); + Assert.That(result.Microseconds(), Is.EqualTo(date.Microseconds())); + Assert.That(result.Offset, Is.EqualTo(date.Offset)); + }); } [Test] @@ -42,15 +45,18 @@ public void When_converting_string_should_be_accurate_to_microseconds() var date = DateTimeOffset.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss:ffffff Z", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); var result = DateTimeOffsetHelper.ToDateTimeOffset(dateString); - Assert.AreEqual(date.Year, result.Year); - Assert.AreEqual(date.Month, result.Month); - Assert.AreEqual(date.Day, result.Day); - Assert.AreEqual(date.Hour, result.Hour); - Assert.AreEqual(date.Minute, result.Minute); - Assert.AreEqual(date.Second, result.Second); - Assert.AreEqual(date.Millisecond, result.Millisecond); - Assert.AreEqual(date.Microseconds(), result.Microseconds()); - Assert.AreEqual(date.Offset, result.Offset); + Assert.Multiple(() => + { + Assert.That(result.Year, Is.EqualTo(date.Year)); + Assert.That(result.Month, Is.EqualTo(date.Month)); + Assert.That(result.Day, Is.EqualTo(date.Day)); + Assert.That(result.Hour, Is.EqualTo(date.Hour)); + Assert.That(result.Minute, Is.EqualTo(date.Minute)); + Assert.That(result.Second, Is.EqualTo(date.Second)); + Assert.That(result.Millisecond, Is.EqualTo(date.Millisecond)); + Assert.That(result.Microseconds(), Is.EqualTo(date.Microseconds())); + Assert.That(result.Offset, Is.EqualTo(date.Offset)); + }); } [Test] @@ -59,7 +65,7 @@ public void When_converting_string_that_is_too_short_should_throw() var dateString = "201-08-16 10:06:20:123456 Z"; var exception = Assert.Throws(() => DateTimeOffsetHelper.ToDateTimeOffset(dateString)); - Assert.AreEqual(exception.Message, "String was not recognized as a valid DateTime."); + Assert.That(exception.Message, Is.EqualTo("String was not recognized as a valid DateTime.")); } [Test] @@ -68,6 +74,6 @@ public void When_converting_string_with_invalid_characters_should_throw() var dateString = "201j-08-16 10:06:20:123456 Z"; var exception = Assert.Throws(() => DateTimeOffsetHelper.ToDateTimeOffset(dateString)); - Assert.AreEqual(exception.Message, "String was not recognized as a valid DateTime."); + Assert.That(exception.Message, Is.EqualTo("String was not recognized as a valid DateTime.")); } } diff --git a/src/NServiceBus.Core.Tests/DelayedDelivery/DelayedDeliveryOptionExtensionsTests.cs b/src/NServiceBus.Core.Tests/DelayedDelivery/DelayedDeliveryOptionExtensionsTests.cs index 6f418e60bc9..5aaad9d9b4d 100644 --- a/src/NServiceBus.Core.Tests/DelayedDelivery/DelayedDeliveryOptionExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/DelayedDelivery/DelayedDeliveryOptionExtensionsTests.cs @@ -13,7 +13,7 @@ public void GetDeliveryDelayShouldReturnTheConfiguredDelayTimeSpan() var delay = TimeSpan.FromMinutes(42); options.DelayDeliveryWith(delay); - Assert.AreEqual(delay, options.GetDeliveryDelay()); + Assert.That(options.GetDeliveryDelay(), Is.EqualTo(delay)); } [Test] @@ -21,7 +21,7 @@ public void GetDeliveryDelayShouldReturnNullWhenNoDelayConfigured() { var options = new SendOptions(); - Assert.IsNull(options.GetDeliveryDelay()); + Assert.That(options.GetDeliveryDelay(), Is.Null); } [Test] @@ -31,7 +31,7 @@ public void GetDeliveryDateShouldReturnTheConfiguredDeliveryDate() var deliveryDate = new DateTimeOffset(2012, 12, 12, 12, 12, 12, TimeSpan.Zero); options.DoNotDeliverBefore(deliveryDate); - Assert.AreEqual(deliveryDate, options.GetDeliveryDate()); + Assert.That(options.GetDeliveryDate(), Is.EqualTo(deliveryDate)); } [Test] @@ -39,7 +39,7 @@ public void GetDeliveryDateShouldReturnNullWhenNoDateConfigured() { var options = new SendOptions(); - Assert.IsNull(options.GetDeliveryDate()); + Assert.That(options.GetDeliveryDate(), Is.Null); } [Test] diff --git a/src/NServiceBus.Core.Tests/Fakes/TestableMessageHandlerContextTests.cs b/src/NServiceBus.Core.Tests/Fakes/TestableMessageHandlerContextTests.cs index bb5f15083c6..506d3930322 100644 --- a/src/NServiceBus.Core.Tests/Fakes/TestableMessageHandlerContextTests.cs +++ b/src/NServiceBus.Core.Tests/Fakes/TestableMessageHandlerContextTests.cs @@ -17,9 +17,12 @@ public async Task Send_ShouldContainMessageInSentMessages() await context.Send(messageInstance, sendOptions); - Assert.AreEqual(1, context.SentMessages.Length); - Assert.AreSame(messageInstance, context.SentMessages[0].Message); - Assert.AreSame(sendOptions, context.SentMessages[0].Options); + Assert.That(context.SentMessages, Has.Length.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(context.SentMessages[0].Message, Is.SameAs(messageInstance)); + Assert.That(context.SentMessages[0].Options, Is.SameAs(sendOptions)); + }); } [Test] @@ -29,7 +32,7 @@ public async Task Send_ShouldInvokeMessageInitializer() await context.Send(m => m.Value = "initialized value"); - Assert.AreEqual("initialized value", context.SentMessages[0].Message().Value); + Assert.That(context.SentMessages[0].Message().Value, Is.EqualTo("initialized value")); } [Test] @@ -41,9 +44,12 @@ public async Task Publish_ShouldContainMessageInPublishedMessages() await context.Publish(messageInstance, publishOptions); - Assert.AreEqual(1, context.PublishedMessages.Length); - Assert.AreSame(messageInstance, context.PublishedMessages[0].Message); - Assert.AreSame(publishOptions, context.PublishedMessages[0].Options); + Assert.That(context.PublishedMessages, Has.Length.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(context.PublishedMessages[0].Message, Is.SameAs(messageInstance)); + Assert.That(context.PublishedMessages[0].Options, Is.SameAs(publishOptions)); + }); } [Test] @@ -53,7 +59,7 @@ public async Task Publish_ShouldInvokeMessageInitializer() await context.Publish(m => m.Value = "initialized value"); - Assert.AreEqual("initialized value", context.PublishedMessages[0].Message().Value); + Assert.That(context.PublishedMessages[0].Message().Value, Is.EqualTo("initialized value")); } [Test] @@ -65,9 +71,12 @@ public async Task Reply_ShouldContainMessageInRepliedMessages() await context.Reply(messageInstance, publishOptions); - Assert.AreEqual(1, context.RepliedMessages.Length); - Assert.AreSame(messageInstance, context.RepliedMessages[0].Message); - Assert.AreSame(publishOptions, context.RepliedMessages[0].Options); + Assert.That(context.RepliedMessages, Has.Length.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(context.RepliedMessages[0].Message, Is.SameAs(messageInstance)); + Assert.That(context.RepliedMessages[0].Options, Is.SameAs(publishOptions)); + }); } [Test] @@ -77,7 +86,7 @@ public async Task Reply_ShouldInvokeMessageInitializer() await context.Reply(m => m.Value = "initialized value"); - Assert.AreEqual("initialized value", context.RepliedMessages[0].Message().Value); + Assert.That(context.RepliedMessages[0].Message().Value, Is.EqualTo("initialized value")); } [Test] @@ -88,8 +97,8 @@ public async Task ForwardCurrentMessageTo_ShouldContainDestinationsInForwardDest await context.ForwardCurrentMessageTo("destination1"); await context.ForwardCurrentMessageTo("destination2"); - Assert.Contains("destination1", context.ForwardedMessages); - Assert.Contains("destination2", context.ForwardedMessages); + Assert.That(context.ForwardedMessages, Does.Contain("destination1")); + Assert.That(context.ForwardedMessages, Does.Contain("destination2")); } [Test] @@ -97,7 +106,7 @@ public void DoNotContinueDispatchingCurrentMessageToHandlers_WhenNotCalled_Shoul { var context = new TestableMessageHandlerContext(); - Assert.IsFalse(context.DoNotContinueDispatchingCurrentMessageToHandlersWasCalled); + Assert.That(context.DoNotContinueDispatchingCurrentMessageToHandlersWasCalled, Is.False); } [Test] @@ -107,7 +116,7 @@ public void DoNotContinueDispatchingCurrentMessageToHandlers_WhenCalled_ShouldIn context.DoNotContinueDispatchingCurrentMessageToHandlers(); - Assert.IsTrue(context.DoNotContinueDispatchingCurrentMessageToHandlersWasCalled); + Assert.That(context.DoNotContinueDispatchingCurrentMessageToHandlersWasCalled, Is.True); } [Test] diff --git a/src/NServiceBus.Core.Tests/Fakes/TestableMessageSessionTests.cs b/src/NServiceBus.Core.Tests/Fakes/TestableMessageSessionTests.cs index 9444848349d..f32109295df 100644 --- a/src/NServiceBus.Core.Tests/Fakes/TestableMessageSessionTests.cs +++ b/src/NServiceBus.Core.Tests/Fakes/TestableMessageSessionTests.cs @@ -14,9 +14,12 @@ public async System.Threading.Tasks.Task Subscribe_ShouldTrackSubscriptionsAsync await session.Subscribe(typeof(MyEvent), options); - Assert.AreEqual(1, session.Subscriptions.Length); - Assert.AreSame(options, session.Subscriptions[0].Options); - Assert.AreEqual(typeof(MyEvent), session.Subscriptions[0].Message); + Assert.That(session.Subscriptions, Has.Length.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(session.Subscriptions[0].Options, Is.SameAs(options)); + Assert.That(session.Subscriptions[0].Message, Is.EqualTo(typeof(MyEvent))); + }); } [Test] @@ -27,9 +30,12 @@ public async System.Threading.Tasks.Task Unsubscribe_ShouldTrackUnsubscriptionsA await session.Unsubscribe(typeof(MyEvent), options); - Assert.AreEqual(1, session.Unsubscription.Length); - Assert.AreSame(options, session.Unsubscription[0].Options); - Assert.AreEqual(typeof(MyEvent), session.Unsubscription[0].Message); + Assert.That(session.Unsubscription, Has.Length.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(session.Unsubscription[0].Options, Is.SameAs(options)); + Assert.That(session.Unsubscription[0].Message, Is.EqualTo(typeof(MyEvent))); + }); } class MyEvent diff --git a/src/NServiceBus.Core.Tests/Features/FeatureDefaultsTests.cs b/src/NServiceBus.Core.Tests/Features/FeatureDefaultsTests.cs index defd30752aa..850b35477c2 100644 --- a/src/NServiceBus.Core.Tests/Features/FeatureDefaultsTests.cs +++ b/src/NServiceBus.Core.Tests/Features/FeatureDefaultsTests.cs @@ -56,7 +56,7 @@ public void Feature_enabled_by_later_feature_should_have_default_called() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(featureThatIsEnabledByAnother.DefaultCalled, "FeatureThatIsEnabledByAnother wasn't activated"); + Assert.That(featureThatIsEnabledByAnother.DefaultCalled, Is.True, "FeatureThatIsEnabledByAnother wasn't activated"); } [Test] @@ -88,15 +88,18 @@ public void Should_enable_features_in_defaults() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(level1.IsActive, "Activate1 wasn't activated"); - Assert.True(level2.IsActive, "Activate2 wasn't activated"); - Assert.True(level3.IsActive, "Activate3 wasn't activated"); + Assert.Multiple(() => + { + Assert.That(level1.IsActive, Is.True, "Activate1 wasn't activated"); + Assert.That(level2.IsActive, Is.True, "Activate2 wasn't activated"); + Assert.That(level3.IsActive, Is.True, "Activate3 wasn't activated"); - Assert.IsInstanceOf(defaultsOrder[0], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(defaultsOrder[1], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(defaultsOrder[2], "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder[0], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder[1], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder[2], Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); - CollectionAssert.AreEqual(defaultsOrder, activatedOrder); + Assert.That(activatedOrder, Is.EqualTo(defaultsOrder).AsCollection); } [Test] @@ -120,9 +123,12 @@ public void Should_activate_upstream_dependencies_first() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(dependingFeature.IsActive); + Assert.Multiple(() => + { + Assert.That(dependingFeature.IsActive, Is.True); - Assert.IsInstanceOf(defaultsOrder.First(), "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder.First(), Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); } [Test] @@ -158,11 +164,14 @@ public void Should_activate_all_upstream_dependencies_first() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(dependingFeature.IsActive); + Assert.Multiple(() => + { + Assert.That(dependingFeature.IsActive, Is.True); - Assert.IsInstanceOf(defaultsOrder[0], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(defaultsOrder[1], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(defaultsOrder[2], "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder[0], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder[1], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder[2], Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); } [Test] @@ -190,13 +199,16 @@ public void Should_activate_all_upstream_dependencies_when_chain_deep() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(level1.IsActive, "Level1 wasn't activated"); - Assert.True(level2.IsActive, "Level2 wasn't activated"); - Assert.True(level3.IsActive, "Level3 wasn't activated"); - - Assert.IsInstanceOf(defaultsOrder[0], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(defaultsOrder[1], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(defaultsOrder[2], "Upstream dependencies should be activated first"); + Assert.Multiple(() => + { + Assert.That(level1.IsActive, Is.True, "Level1 wasn't activated"); + Assert.That(level2.IsActive, Is.True, "Level2 wasn't activated"); + Assert.That(level3.IsActive, Is.True, "Level3 wasn't activated"); + + Assert.That(defaultsOrder[0], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder[1], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(defaultsOrder[2], Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); } public class Level1 : TestFeature diff --git a/src/NServiceBus.Core.Tests/Features/FeatureDependencyTests.cs b/src/NServiceBus.Core.Tests/Features/FeatureDependencyTests.cs index cae11800731..0be0e0ec40a 100644 --- a/src/NServiceBus.Core.Tests/Features/FeatureDependencyTests.cs +++ b/src/NServiceBus.Core.Tests/Features/FeatureDependencyTests.cs @@ -61,7 +61,7 @@ public void Should_only_activate_features_if_dependencies_are_met(FeatureCombina featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.AreEqual(setup.ShouldBeActive, dependingFeature.IsActive); + Assert.That(dependingFeature.IsActive, Is.EqualTo(setup.ShouldBeActive)); } [Test] @@ -88,9 +88,12 @@ public void Should_activate_upstream_dependencies_first() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(dependingFeature.IsActive); + Assert.Multiple(() => + { + Assert.That(dependingFeature.IsActive, Is.True); - Assert.IsInstanceOf(order.First(), "Upstream dependencies should be activated first"); + Assert.That(order.First(), Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); } [Test] @@ -117,8 +120,11 @@ public void Should_activate_named_dependency_first() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(dependingFeature.IsActive); - Assert.IsInstanceOf(order.First(), "Upstream dependencies should be activated first"); + Assert.Multiple(() => + { + Assert.That(dependingFeature.IsActive, Is.True); + Assert.That(order.First(), Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); } [Test] @@ -143,8 +149,11 @@ public void Should_not_activate_feature_when_named_dependency_disabled() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.False(dependingFeature.IsActive); - Assert.IsEmpty(order); + Assert.Multiple(() => + { + Assert.That(dependingFeature.IsActive, Is.False); + Assert.That(order, Is.Empty); + }); } [Test] @@ -183,11 +192,14 @@ public void Should_activate_all_upstream_dependencies_first() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(dependingFeature.IsActive); + Assert.Multiple(() => + { + Assert.That(dependingFeature.IsActive, Is.True); - Assert.IsInstanceOf(order[0], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(order[1], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(order[2], "Upstream dependencies should be activated first"); + Assert.That(order[0], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(order[1], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(order[2], Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); } [Test] @@ -219,14 +231,16 @@ public void Should_activate_all_upstream_dependencies_when_chain_deep() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - - Assert.True(level1.IsActive, "Level1 wasn't activated"); - Assert.True(level2.IsActive, "Level2 wasn't activated"); - Assert.True(level3.IsActive, "Level3 wasn't activated"); - - Assert.IsInstanceOf(order[0], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(order[1], "Upstream dependencies should be activated first"); - Assert.IsInstanceOf(order[2], "Upstream dependencies should be activated first"); + Assert.Multiple(() => + { + Assert.That(level1.IsActive, Is.True, "Level1 wasn't activated"); + Assert.That(level2.IsActive, Is.True, "Level2 wasn't activated"); + Assert.That(level3.IsActive, Is.True, "Level3 wasn't activated"); + + Assert.That(order[0], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(order[1], Is.InstanceOf(), "Upstream dependencies should be activated first"); + Assert.That(order[2], Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); } [Test] diff --git a/src/NServiceBus.Core.Tests/Features/FeatureDifferingOnlyByNamespaceTests.cs b/src/NServiceBus.Core.Tests/Features/FeatureDifferingOnlyByNamespaceTests.cs index 3f30f5f4412..812e074e272 100644 --- a/src/NServiceBus.Core.Tests/Features/FeatureDifferingOnlyByNamespaceTests.cs +++ b/src/NServiceBus.Core.Tests/Features/FeatureDifferingOnlyByNamespaceTests.cs @@ -33,9 +33,12 @@ public void Should_activate_upstream_dependencies_first() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(dependingFeature.IsActive); + Assert.Multiple(() => + { + Assert.That(dependingFeature.IsActive, Is.True); - Assert.IsInstanceOf(order.First(), "Upstream dependencies should be activated first"); + Assert.That(order.First(), Is.InstanceOf(), "Upstream dependencies should be activated first"); + }); } } } diff --git a/src/NServiceBus.Core.Tests/Features/FeatureSettingsTests.cs b/src/NServiceBus.Core.Tests/Features/FeatureSettingsTests.cs index 6836a8f87e6..d723f504fa5 100644 --- a/src/NServiceBus.Core.Tests/Features/FeatureSettingsTests.cs +++ b/src/NServiceBus.Core.Tests/Features/FeatureSettingsTests.cs @@ -30,10 +30,13 @@ public void Should_check_prerequisites() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(featureWithTrueCondition.IsActive); - Assert.False(featureWithFalseCondition.IsActive); - Assert.AreEqual("The description", - featureSettings.Status.Single(s => s.Name == featureWithFalseCondition.Name).PrerequisiteStatus.Reasons.First()); + Assert.Multiple(() => + { + Assert.That(featureWithTrueCondition.IsActive, Is.True); + Assert.That(featureWithFalseCondition.IsActive, Is.False); + Assert.That(featureSettings.Status.Single(s => s.Name == featureWithFalseCondition.Name).PrerequisiteStatus.Reasons.First(), + Is.EqualTo("The description")); + }); } [Test] @@ -43,7 +46,7 @@ public void Should_register_defaults_if_feature_is_activated() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.True(settings.HasSetting("Test1")); + Assert.That(settings.HasSetting("Test1"), Is.True); } [Test] @@ -55,8 +58,11 @@ public void Should_not_register_defaults_if_feature_is_not_activated() featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); - Assert.False(settings.HasSetting("Test1")); - Assert.False(settings.HasSetting("Test2")); + Assert.Multiple(() => + { + Assert.That(settings.HasSetting("Test1"), Is.False); + Assert.That(settings.HasSetting("Test2"), Is.False); + }); } diff --git a/src/NServiceBus.Core.Tests/Features/FeatureStartupTests.cs b/src/NServiceBus.Core.Tests/Features/FeatureStartupTests.cs index 531582463aa..70b33a09df7 100644 --- a/src/NServiceBus.Core.Tests/Features/FeatureStartupTests.cs +++ b/src/NServiceBus.Core.Tests/Features/FeatureStartupTests.cs @@ -30,8 +30,11 @@ public async Task Should_start_and_stop_features() await featureSettings.StartFeatures(null, null); await featureSettings.StopFeatures(); - Assert.True(feature.TaskStarted); - Assert.True(feature.TaskStopped); + Assert.Multiple(() => + { + Assert.That(feature.TaskStarted, Is.True); + Assert.That(feature.TaskStopped, Is.True); + }); } [Test] @@ -53,7 +56,7 @@ public async Task Should_start_and_stop_features_in_dependency_order() expectedOrderBuilder.AppendLine("FeatureWithStartupThatAnotherFeatureDependsOn.Stop"); expectedOrderBuilder.AppendLine("FeatureWithStartupTaskWithDependency.Stop"); - Assert.AreEqual(expectedOrderBuilder.ToString(), orderBuilder.ToString()); + Assert.That(orderBuilder.ToString(), Is.EqualTo(expectedOrderBuilder.ToString())); } [Test] @@ -68,7 +71,7 @@ public async Task Should_dispose_feature_startup_tasks_when_they_implement_IDisp await featureSettings.StartFeatures(null, null); await featureSettings.StopFeatures(); - Assert.True(feature.TaskDisposed); + Assert.That(feature.TaskDisposed, Is.True); } [Test] @@ -85,13 +88,16 @@ public void Should_throw_when_feature_task_fails_on_start_and_should_stop_previo featureSettings.SetupFeatures(new FakeFeatureConfigurationContext()); var exception = Assert.ThrowsAsync(async () => await featureSettings.StartFeatures(null, null)); - Assert.AreEqual("feature2", exception.Message); - - Assert.True(feature1.TaskStarted, "Feature 1 should have been started."); - Assert.True(feature2.TaskStartCalled, "An attempt should have been made to start feature 2."); - Assert.True(feature1.TaskStopCalled, "An attempt should have been made to stop feature 1."); - Assert.False(feature2.TaskStopCalled, "No attempt should have been made to stop feature 2."); - Assert.False(feature3.TaskStartCalled, "No attempt should have been made to start feature 3."); + Assert.Multiple(() => + { + Assert.That(exception.Message, Is.EqualTo("feature2")); + + Assert.That(feature1.TaskStarted, Is.True, "Feature 1 should have been started."); + Assert.That(feature2.TaskStartCalled, Is.True, "An attempt should have been made to start feature 2."); + Assert.That(feature1.TaskStopCalled, Is.True, "An attempt should have been made to stop feature 1."); + Assert.That(feature2.TaskStopCalled, Is.False, "No attempt should have been made to stop feature 2."); + Assert.That(feature3.TaskStartCalled, Is.False, "No attempt should have been made to start feature 3."); + }); } [Test] @@ -109,8 +115,11 @@ public async Task Should_not_throw_when_feature_task_fails_on_stop_and_should_no Assert.DoesNotThrowAsync(async () => await featureSettings.StopFeatures()); - Assert.True(feature1.TaskStarted && feature1.TaskStopped); - Assert.True(feature2.TaskStarted && !feature2.TaskStopped); + Assert.Multiple(() => + { + Assert.That(feature1.TaskStarted && feature1.TaskStopped, Is.True); + Assert.That(feature2.TaskStarted && !feature2.TaskStopped, Is.True); + }); } [Test] @@ -124,7 +133,7 @@ public async Task Should_dispose_feature_task_even_when_stop_throws() await featureSettings.StartFeatures(null, null); await featureSettings.StopFeatures(); - Assert.True(feature.TaskDisposed); + Assert.That(feature.TaskDisposed, Is.True); } FeatureActivator featureSettings; diff --git a/src/NServiceBus.Core.Tests/Features/FeatureTests.cs b/src/NServiceBus.Core.Tests/Features/FeatureTests.cs index 4e4df830420..0892508f2ca 100644 --- a/src/NServiceBus.Core.Tests/Features/FeatureTests.cs +++ b/src/NServiceBus.Core.Tests/Features/FeatureTests.cs @@ -10,7 +10,7 @@ public void Should_be_disabled_be_default() { var feature = new MyFeature(); - Assert.False(feature.IsEnabledByDefault); + Assert.That(feature.IsEnabledByDefault, Is.False); } [Test] @@ -18,7 +18,7 @@ public void Should_be_allow_features_to_request_being_enabled_by_default() { var feature = new MyEnabledByDefaultFeature(); - Assert.True(feature.IsEnabledByDefault); + Assert.That(feature.IsEnabledByDefault, Is.True); } diff --git a/src/NServiceBus.Core.Tests/Handlers/MessageHandlerRegistryTests.cs b/src/NServiceBus.Core.Tests/Handlers/MessageHandlerRegistryTests.cs index 38746d0a719..0985c1ff09f 100644 --- a/src/NServiceBus.Core.Tests/Handlers/MessageHandlerRegistryTests.cs +++ b/src/NServiceBus.Core.Tests/Handlers/MessageHandlerRegistryTests.cs @@ -32,31 +32,37 @@ public async Task ShouldIndicateWhetherAHandlerIsATimeoutHandler() var handlers = registry.GetHandlersFor(typeof(MyMessage)); - Assert.AreEqual(2, handlers.Count); + Assert.That(handlers.Count, Is.EqualTo(2)); var timeoutHandler = handlers.SingleOrDefault(h => h.IsTimeoutHandler); - Assert.NotNull(timeoutHandler, "Timeout handler should be marked as such"); + Assert.That(timeoutHandler, Is.Not.Null, "Timeout handler should be marked as such"); var timeoutInstance = new SagaWithTimeoutOfMessage(); timeoutHandler.Instance = timeoutInstance; await timeoutHandler.Invoke(new MyMessage(), new TestableInvokeHandlerContext()); - Assert.True(timeoutInstance.TimeoutCalled); - Assert.False(timeoutInstance.HandlerCalled); + Assert.Multiple(() => + { + Assert.That(timeoutInstance.TimeoutCalled, Is.True); + Assert.That(timeoutInstance.HandlerCalled, Is.False); + }); var regularHandler = handlers.SingleOrDefault(h => !h.IsTimeoutHandler); - Assert.NotNull(regularHandler, "Regular handler should be marked as timeout handler"); + Assert.That(regularHandler, Is.Not.Null, "Regular handler should be marked as timeout handler"); var regularInstance = new SagaWithTimeoutOfMessage(); regularHandler.Instance = regularInstance; await regularHandler.Invoke(new MyMessage(), new TestableInvokeHandlerContext()); - Assert.False(regularInstance.TimeoutCalled); - Assert.True(regularInstance.HandlerCalled); + Assert.Multiple(() => + { + Assert.That(regularInstance.TimeoutCalled, Is.False); + Assert.That(regularInstance.HandlerCalled, Is.True); + }); } class HandlerWithIMessageSessionProperty : IHandleMessages diff --git a/src/NServiceBus.Core.Tests/Hosting/HostInfoSettingsTests.cs b/src/NServiceBus.Core.Tests/Hosting/HostInfoSettingsTests.cs index c7d86a38e48..3b6e9a31ed4 100644 --- a/src/NServiceBus.Core.Tests/Hosting/HostInfoSettingsTests.cs +++ b/src/NServiceBus.Core.Tests/Hosting/HostInfoSettingsTests.cs @@ -16,7 +16,7 @@ public void It_overrides_the_host_id() busConfig.UniquelyIdentifyRunningInstance().UsingCustomIdentifier(requestedId); var configuredId = busConfig.Settings.Get().HostId; - Assert.AreEqual(requestedId, configuredId); + Assert.That(configuredId, Is.EqualTo(requestedId)); } [Test] @@ -27,7 +27,7 @@ public void It_allows_to_generate_a_deterministic_id_using_instance_and_host_nam busConfig.UniquelyIdentifyRunningInstance().UsingNames("Instance", "Host"); var configuredId = busConfig.Settings.Get().HostId; - Assert.AreEqual(DeterministicGuid.Create("Instance", "Host"), configuredId); + Assert.That(configuredId, Is.EqualTo(DeterministicGuid.Create("Instance", "Host"))); } [Test] @@ -38,6 +38,6 @@ public void It_overrides_the_machine_name() busConfig.UniquelyIdentifyRunningInstance().UsingHostName("overridenhostname"); var hostName = RuntimeEnvironment.MachineName; - Assert.AreEqual("overridenhostname", hostName); + Assert.That(hostName, Is.EqualTo("overridenhostname")); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Hosting/HostTests.cs b/src/NServiceBus.Core.Tests/Hosting/HostTests.cs index 4618a63006c..05e591cd6f4 100644 --- a/src/NServiceBus.Core.Tests/Hosting/HostTests.cs +++ b/src/NServiceBus.Core.Tests/Hosting/HostTests.cs @@ -12,6 +12,6 @@ public void When_not_running_ASP_NET_should_choose_BaseDirectory_as_output_direc { var directory = Host.GetOutputDirectory(); - Assert.AreEqual(AppDomain.CurrentDomain.BaseDirectory, directory); + Assert.That(directory, Is.EqualTo(AppDomain.CurrentDomain.BaseDirectory)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Hosting/PathUtilities_Tests.cs b/src/NServiceBus.Core.Tests/Hosting/PathUtilities_Tests.cs index 1e5359aa4a9..a10a46ea45e 100644 --- a/src/NServiceBus.Core.Tests/Hosting/PathUtilities_Tests.cs +++ b/src/NServiceBus.Core.Tests/Hosting/PathUtilities_Tests.cs @@ -10,7 +10,7 @@ public void Parse_from_path_without_spaces_but_with_quotes() { var path = PathUtilities.SanitizedPath("\"pathto\\my.exe\" somevar"); - Assert.AreEqual("pathto\\my.exe", path); + Assert.That(path, Is.EqualTo("pathto\\my.exe")); } [Test] @@ -18,7 +18,7 @@ public void Parse_from_path_without_spaces_but_without_quotes() { var path = PathUtilities.SanitizedPath("pathto\\my.exe somevar"); - Assert.AreEqual("pathto\\my.exe", path); + Assert.That(path, Is.EqualTo("pathto\\my.exe")); } [Test] @@ -27,7 +27,7 @@ public void Paths_without_spaces_are_equal() var path1 = PathUtilities.SanitizedPath("\"pathto\\my.exe\" somevar"); var path2 = PathUtilities.SanitizedPath("pathto\\my.exe somevar"); - Assert.AreEqual(path1, path2); + Assert.That(path2, Is.EqualTo(path1)); } [Test] @@ -35,7 +35,7 @@ public void Parse_from_path_with_spaces_having_a_parameter_with_spaces() { var path = PathUtilities.SanitizedPath("\"pathto\\mysuper duper.exe\" \"somevar with spaces\""); - Assert.AreEqual("pathto\\mysuper duper.exe", path); + Assert.That(path, Is.EqualTo("pathto\\mysuper duper.exe")); } [Test] @@ -43,7 +43,7 @@ public void Parse_from_path_with_spaces_having_a_parameter_without_spaces() { var path = PathUtilities.SanitizedPath("\"pathto\\mysuper duper.exe\" somevar"); - Assert.AreEqual("pathto\\mysuper duper.exe", path); + Assert.That(path, Is.EqualTo("pathto\\mysuper duper.exe")); } [Test] @@ -52,6 +52,6 @@ public void Both_paths_with_spaces_are_equal() var path1 = PathUtilities.SanitizedPath("\"pathto\\mysuper duper.exe\" \"somevar with spaces\""); var path2 = PathUtilities.SanitizedPath("\"pathto\\mysuper duper.exe\" somevar"); - Assert.AreEqual(path1, path2); + Assert.That(path2, Is.EqualTo(path1)); } } diff --git a/src/NServiceBus.Core.Tests/IdGeneration/IdGenerationTests.cs b/src/NServiceBus.Core.Tests/IdGeneration/IdGenerationTests.cs index 240ba57b626..ec795e213b4 100644 --- a/src/NServiceBus.Core.Tests/IdGeneration/IdGenerationTests.cs +++ b/src/NServiceBus.Core.Tests/IdGeneration/IdGenerationTests.cs @@ -13,7 +13,7 @@ public void Should_return_same_result_for_same_input(Guid guid, DateTime now) var oldCombGuid = LocalCopyOfCombGuid.GenerateOld(guid, now); var improvedCombGuid = CombGuid.Generate(guid, now); - Assert.AreEqual(oldCombGuid, improvedCombGuid); + Assert.That(improvedCombGuid, Is.EqualTo(oldCombGuid)); } static readonly Random Random = new Random(); diff --git a/src/NServiceBus.Core.Tests/Licensing/LicenseManagerTests.cs b/src/NServiceBus.Core.Tests/Licensing/LicenseManagerTests.cs index c9c91e70697..4226d8931e9 100644 --- a/src/NServiceBus.Core.Tests/Licensing/LicenseManagerTests.cs +++ b/src/NServiceBus.Core.Tests/Licensing/LicenseManagerTests.cs @@ -16,7 +16,7 @@ public void ShouldLogNoStatusMessageWhenLicenseIsValid() LicenseManager.LogLicenseStatus(LicenseStatus.Valid, logger, new License(), "fake-url"); - Assert.AreEqual(0, logger.Logs.Count); + Assert.That(logger.Logs.Count, Is.EqualTo(0)); } [Test] @@ -26,9 +26,12 @@ public void WhenSubscriptionLicenseExpired() LicenseManager.LogLicenseStatus(LicenseStatus.InvalidDueToExpiredSubscription, logger, new License(), "fake-url"); - Assert.AreEqual(1, logger.Logs.Count); - Assert.AreEqual(LogLevel.Error, logger.Logs[0].level); - Assert.AreEqual("License expired. Contact us to renew your license: contact@particular.net", logger.Logs[0].message); + Assert.That(logger.Logs.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(logger.Logs[0].level, Is.EqualTo(LogLevel.Error)); + Assert.That(logger.Logs[0].message, Is.EqualTo("License expired. Contact us to renew your license: contact@particular.net")); + }); } [Test] @@ -38,9 +41,12 @@ public void WhenUpgradeProtectionExpiredForThisRelease() LicenseManager.LogLicenseStatus(LicenseStatus.InvalidDueToExpiredUpgradeProtection, logger, new License(), "fake-url"); - Assert.AreEqual(1, logger.Logs.Count); - Assert.AreEqual(LogLevel.Error, logger.Logs[0].level); - Assert.AreEqual("Upgrade protection expired. In order for us to continue to provide you with support and new versions of the Particular Service Platform, contact us to renew your license: contact@particular.net", logger.Logs[0].message); + Assert.That(logger.Logs.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(logger.Logs[0].level, Is.EqualTo(LogLevel.Error)); + Assert.That(logger.Logs[0].message, Is.EqualTo("Upgrade protection expired. In order for us to continue to provide you with support and new versions of the Particular Service Platform, contact us to renew your license: contact@particular.net")); + }); } [TestCase(false, "Trial license expired. Get your free development license at fake-url")] @@ -52,9 +58,12 @@ public void WhenTrialLicenseExpired(bool isDevLicenseRenewal, string expectedMes LicenseManager.LogLicenseStatus(LicenseStatus.InvalidDueToExpiredTrial, logger, license, "fake-url"); - Assert.AreEqual(1, logger.Logs.Count); - Assert.AreEqual(LogLevel.Error, logger.Logs[0].level); - Assert.AreEqual(expectedMessage, logger.Logs[0].message); + Assert.That(logger.Logs.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(logger.Logs[0].level, Is.EqualTo(LogLevel.Error)); + Assert.That(logger.Logs[0].message, Is.EqualTo(expectedMessage)); + }); } [TestCase(3, false, "Trial license expiring in 3 days. Get your free development license at fake-url")] @@ -77,9 +86,12 @@ public void WhenTrialLicenseAboutToExpire(int daysRemaining, bool isDevLicenseRe LicenseManager.LogLicenseStatus(LicenseStatus.ValidWithExpiringTrial, logger, license, "fake-url"); - Assert.AreEqual(1, logger.Logs.Count); - Assert.AreEqual(LogLevel.Warn, logger.Logs[0].level); - Assert.AreEqual(expectedMessage, logger.Logs[0].message); + Assert.That(logger.Logs.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(logger.Logs[0].level, Is.EqualTo(LogLevel.Warn)); + Assert.That(logger.Logs[0].message, Is.EqualTo(expectedMessage)); + }); } [TestCase(3, "License expiring in 3 days. Contact us to renew your license: contact@particular.net")] @@ -98,9 +110,12 @@ public void WhenSubscriptionAboutToExpire(int daysRemaining, string expectedMess LicenseManager.LogLicenseStatus(LicenseStatus.ValidWithExpiringSubscription, logger, license, "fake-url"); - Assert.AreEqual(1, logger.Logs.Count); - Assert.AreEqual(LogLevel.Warn, logger.Logs[0].level); - Assert.AreEqual(expectedMessage, logger.Logs[0].message); + Assert.That(logger.Logs.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(logger.Logs[0].level, Is.EqualTo(LogLevel.Warn)); + Assert.That(logger.Logs[0].message, Is.EqualTo(expectedMessage)); + }); } [TestCase(3, "Upgrade protection expiring in 3 days. Contact us to renew your license: contact@particular.net")] @@ -119,9 +134,12 @@ public void WhenUpgradeProtectionAboutToExpire(int daysRemaining, string expecte LicenseManager.LogLicenseStatus(LicenseStatus.ValidWithExpiringUpgradeProtection, logger, license, "fake-url"); - Assert.AreEqual(1, logger.Logs.Count); - Assert.AreEqual(LogLevel.Warn, logger.Logs[0].level); - Assert.AreEqual(expectedMessage, logger.Logs[0].message); + Assert.That(logger.Logs.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(logger.Logs[0].level, Is.EqualTo(LogLevel.Warn)); + Assert.That(logger.Logs[0].message, Is.EqualTo(expectedMessage)); + }); } [Test] @@ -139,9 +157,12 @@ public void WhenUpgradeProtectionExpiredForFutureVersions() LicenseManager.LogLicenseStatus(LicenseStatus.ValidWithExpiredUpgradeProtection, logger, license, "fake-url"); - Assert.AreEqual(1, logger.Logs.Count); - Assert.AreEqual(LogLevel.Warn, logger.Logs[0].level); - Assert.AreEqual("Upgrade protection expired. In order for us to continue to provide you with support and new versions of the Particular Service Platform, contact us to renew your license: contact@particular.net", logger.Logs[0].message); + Assert.That(logger.Logs.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(logger.Logs[0].level, Is.EqualTo(LogLevel.Warn)); + Assert.That(logger.Logs[0].message, Is.EqualTo("Upgrade protection expired. In order for us to continue to provide you with support and new versions of the Particular Service Platform, contact us to renew your license: contact@particular.net")); + }); } class TestableLogger : ILog diff --git a/src/NServiceBus.Core.Tests/Logging/DefaultFactoryTests.cs b/src/NServiceBus.Core.Tests/Logging/DefaultFactoryTests.cs index 4ad04c45d7b..a73c1a2251b 100644 --- a/src/NServiceBus.Core.Tests/Logging/DefaultFactoryTests.cs +++ b/src/NServiceBus.Core.Tests/Logging/DefaultFactoryTests.cs @@ -13,7 +13,7 @@ public void When_directory_is_bad_should_throw() { var defaultFactory = new DefaultFactory(); var nonExistingDirectoryException = Assert.Throws(() => defaultFactory.Directory("baddir")); - Assert.AreEqual("Could not find logging directory: 'baddir'", nonExistingDirectoryException.Message); + Assert.That(nonExistingDirectoryException.Message, Is.EqualTo("Could not find logging directory: 'baddir'")); Assert.Throws(() => defaultFactory.Directory(null)); Assert.Throws(() => defaultFactory.Directory("")); Assert.Throws(() => defaultFactory.Directory(" ")); diff --git a/src/NServiceBus.Core.Tests/Logging/RollingLoggerTests.cs b/src/NServiceBus.Core.Tests/Logging/RollingLoggerTests.cs index 36422ff0337..50e13d0e88d 100644 --- a/src/NServiceBus.Core.Tests/Logging/RollingLoggerTests.cs +++ b/src/NServiceBus.Core.Tests/Logging/RollingLoggerTests.cs @@ -22,16 +22,22 @@ public void When_file_already_exists_that_file_is_written_to() }; logger1.WriteLine("Foo"); var files1 = tempPath.GetFiles(); - Assert.AreEqual(1, files1.Count); - Assert.AreEqual($"Foo{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(files1.First())); + Assert.Multiple(() => + { + Assert.That(files1.Count, Is.EqualTo(1)); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(files1.First()), Is.EqualTo($"Foo{Environment.NewLine}")); + }); var logger2 = new RollingLogger(tempPath.TempDirectory) { GetDate = () => dateTime }; logger2.WriteLine("Bar"); var files2 = tempPath.GetFiles(); - Assert.AreEqual(1, files2.Count); - Assert.AreEqual($"Foo{Environment.NewLine}Bar{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(files2.First())); + Assert.Multiple(() => + { + Assert.That(files2.Count, Is.EqualTo(1)); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(files2.First()), Is.EqualTo($"Foo{Environment.NewLine}Bar{Environment.NewLine}")); + }); } } @@ -48,7 +54,7 @@ public void When_file_is_deleted_underneath_continues_to_write_afterwards() var single = tempPath.GetSingle(); File.Delete(single); logger.WriteLine("Bar"); - Assert.AreEqual($"Bar{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(single)); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(single), Is.EqualTo($"Bar{Environment.NewLine}")); } } @@ -67,7 +73,7 @@ public void When_file_is_locked_exception_is_swallowed() { logger.WriteLine("Bar"); } - Assert.AreEqual($"Foo{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(single)); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(single), Is.EqualTo($"Foo{Environment.NewLine}")); } } @@ -89,7 +95,7 @@ public void When_file_is_deleted_underneath_immediately_before_write() var singleFile = tempPath.GetSingle(); File.Delete(singleFile); logger.WriteLine("Bar"); - Assert.AreEqual($"Bar{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(singleFile)); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(singleFile), Is.EqualTo($"Bar{Environment.NewLine}")); } } @@ -127,15 +133,21 @@ public void When_file_already_exists_and_is_too_large_a_new_sequence_file_is_wri logger2.WriteLine("Bar"); var files = tempPath.GetFiles(); - Assert.AreEqual(2, files.Count); + Assert.That(files.Count, Is.EqualTo(2)); var first = files[0]; - Assert.AreEqual("nsb_log_2010-10-01_0.txt", Path.GetFileName(first)); - Assert.AreEqual($"Some long text{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(files.First())); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(first), Is.EqualTo("nsb_log_2010-10-01_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(files.First()), Is.EqualTo($"Some long text{Environment.NewLine}")); + }); var second = files[1]; - Assert.AreEqual("nsb_log_2010-10-01_1.txt", Path.GetFileName(second)); - Assert.AreEqual($"Bar{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(second)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(second), Is.EqualTo("nsb_log_2010-10-01_1.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(second), Is.EqualTo($"Bar{Environment.NewLine}")); + }); } } @@ -156,15 +168,21 @@ public void When_file_already_exists_with_wrong_date_a_file_is_written() logger2.WriteLine("Bar"); var files = tempPath.GetFiles(); - Assert.AreEqual(2, files.Count); + Assert.That(files.Count, Is.EqualTo(2)); var first = files[0]; - Assert.AreEqual("nsb_log_2010-10-01_0.txt", Path.GetFileName(first)); - Assert.AreEqual($"Foo{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(files.First())); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(first), Is.EqualTo("nsb_log_2010-10-01_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(files.First()), Is.EqualTo($"Foo{Environment.NewLine}")); + }); var second = files[1]; - Assert.AreEqual("nsb_log_2010-10-02_0.txt", Path.GetFileName(second)); - Assert.AreEqual($"Bar{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(second)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(second), Is.EqualTo("nsb_log_2010-10-02_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(second), Is.EqualTo($"Bar{Environment.NewLine}")); + }); } } @@ -176,7 +194,7 @@ public void When_line_is_write_line_appears_in_file() var logger = new RollingLogger(tempPath.TempDirectory); logger.WriteLine("Foo"); var singleFile = tempPath.GetSingle(); - Assert.AreEqual($"Foo{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(singleFile)); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(singleFile), Is.EqualTo($"Foo{Environment.NewLine}")); } } @@ -189,7 +207,7 @@ public void When_multiple_lines_are_written_lines_appears_in_file() logger.WriteLine("Foo"); logger.WriteLine("Bar"); var singleFile = tempPath.GetSingle(); - Assert.AreEqual($"Foo{Environment.NewLine}Bar{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(singleFile)); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(singleFile), Is.EqualTo($"Foo{Environment.NewLine}Bar{Environment.NewLine}")); } } @@ -206,15 +224,21 @@ public void When_max_file_size_is_exceeded_sequence_number_is_added() logger.WriteLine("Some long text"); logger.WriteLine("Bar"); var files = tempPath.GetFiles(); - Assert.AreEqual(2, files.Count); + Assert.That(files.Count, Is.EqualTo(2)); var first = files[0]; - Assert.AreEqual("nsb_log_2010-10-01_0.txt", Path.GetFileName(first)); - Assert.AreEqual($"Some long text{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(first)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(first), Is.EqualTo("nsb_log_2010-10-01_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(first), Is.EqualTo($"Some long text{Environment.NewLine}")); + }); var second = files[1]; - Assert.AreEqual("nsb_log_2010-10-01_1.txt", Path.GetFileName(second)); - Assert.AreEqual($"Bar{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(second)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(second), Is.EqualTo("nsb_log_2010-10-01_1.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(second), Is.EqualTo($"Bar{Environment.NewLine}")); + }); } } @@ -230,7 +254,7 @@ public void When_many_sequence_files_are_written_the_max_is_not_exceeded() for (var i = 0; i < 100; i++) { logger.WriteLine("Some long text"); - Assert.LessOrEqual(tempPath.GetFiles().Count, 11); + Assert.That(tempPath.GetFiles().Count, Is.LessThanOrEqualTo(11)); } } } @@ -244,7 +268,7 @@ public void When_new_write_causes_overlap_of_file_size_line_is_written_to_curren logger.WriteLine("Foo"); logger.WriteLine("Some long text"); var singleFile = tempPath.GetSingle(); - Assert.AreEqual($"Foo{Environment.NewLine}Some long text{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(singleFile)); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(singleFile), Is.EqualTo($"Foo{Environment.NewLine}Some long text{Environment.NewLine}")); } } @@ -261,15 +285,21 @@ public void When_date_changes_new_file_is_written() logger.GetDate = () => new DateTimeOffset(2010, 10, 2, 0, 0, 0, TimeSpan.Zero); logger.WriteLine("Bar"); var files = tempPath.GetFiles(); - Assert.AreEqual(2, files.Count); + Assert.That(files.Count, Is.EqualTo(2)); var first = files[0]; - Assert.AreEqual("nsb_log_2010-10-01_0.txt", Path.GetFileName(first)); - Assert.AreEqual($"Foo{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(first)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(first), Is.EqualTo("nsb_log_2010-10-01_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(first), Is.EqualTo($"Foo{Environment.NewLine}")); + }); var second = files[1]; - Assert.AreEqual("nsb_log_2010-10-02_0.txt", Path.GetFileName(second)); - Assert.AreEqual($"Bar{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(second)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(second), Is.EqualTo("nsb_log_2010-10-02_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(second), Is.EqualTo($"Bar{Environment.NewLine}")); + }); } } @@ -291,7 +321,7 @@ public void When_getting_todays_log_file_sequence_number_is_used_in_sorting() }, }; var logFile = RollingLogger.GetTodaysNewest(logFiles, today); - Assert.AreEqual(2, logFile.SequenceNumber); + Assert.That(logFile.SequenceNumber, Is.EqualTo(2)); } [Test] @@ -329,7 +359,7 @@ public void When_getting_todays_log_file_only_today_is_respected() }, }; var logFile = RollingLogger.GetTodaysNewest(logFiles, today); - Assert.AreEqual(0, logFile.SequenceNumber); + Assert.That(logFile.SequenceNumber, Is.EqualTo(0)); } [Test] @@ -348,19 +378,28 @@ public void When_many_files_written_over_size_old_files_are_deleted() logger.WriteLine("Long text3"); logger.WriteLine("Long text4"); var files = tempPath.GetFiles(); - Assert.AreEqual(3, files.Count, "Should be numberOfArchiveFilesToKeep + 1 (the current file) "); + Assert.That(files.Count, Is.EqualTo(3), "Should be numberOfArchiveFilesToKeep + 1 (the current file) "); var first = files[0]; - Assert.AreEqual("nsb_log_2010-10-01_2.txt", Path.GetFileName(first)); - Assert.AreEqual($"Long text2{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(first)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(first), Is.EqualTo("nsb_log_2010-10-01_2.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(first), Is.EqualTo($"Long text2{Environment.NewLine}")); + }); var second = files[1]; - Assert.AreEqual("nsb_log_2010-10-01_3.txt", Path.GetFileName(second)); - Assert.AreEqual($"Long text3{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(second)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(second), Is.EqualTo("nsb_log_2010-10-01_3.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(second), Is.EqualTo($"Long text3{Environment.NewLine}")); + }); var third = files[2]; - Assert.AreEqual("nsb_log_2010-10-01_4.txt", Path.GetFileName(third)); - Assert.AreEqual($"Long text4{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(third)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(third), Is.EqualTo("nsb_log_2010-10-01_4.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(third), Is.EqualTo($"Long text4{Environment.NewLine}")); + }); } } @@ -383,19 +422,28 @@ public void When_many_files_written_over_dates_old_files_are_deleted() logger.GetDate = () => new DateTimeOffset(2010, 10, 5, 0, 0, 0, TimeSpan.Zero); logger.WriteLine("Foo5"); var files = tempPath.GetFiles(); - Assert.AreEqual(3, files.Count, "Should be numberOfArchiveFilesToKeep + 1 (the current file) "); + Assert.That(files.Count, Is.EqualTo(3), "Should be numberOfArchiveFilesToKeep + 1 (the current file) "); var first = files[0]; - Assert.AreEqual("nsb_log_2010-10-03_0.txt", Path.GetFileName(first)); - Assert.AreEqual($"Foo3{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(first)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(first), Is.EqualTo("nsb_log_2010-10-03_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(first), Is.EqualTo($"Foo3{Environment.NewLine}")); + }); var second = files[1]; - Assert.AreEqual("nsb_log_2010-10-04_0.txt", Path.GetFileName(second)); - Assert.AreEqual($"Foo4{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(second)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(second), Is.EqualTo("nsb_log_2010-10-04_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(second), Is.EqualTo($"Foo4{Environment.NewLine}")); + }); var third = files[2]; - Assert.AreEqual("nsb_log_2010-10-05_0.txt", Path.GetFileName(third)); - Assert.AreEqual($"Foo5{Environment.NewLine}", NonLockingFileReader.ReadAllTextWithoutLocking(third)); + Assert.Multiple(() => + { + Assert.That(Path.GetFileName(third), Is.EqualTo("nsb_log_2010-10-05_0.txt")); + Assert.That(NonLockingFileReader.ReadAllTextWithoutLocking(third), Is.EqualTo($"Foo5{Environment.NewLine}")); + }); } } @@ -410,7 +458,7 @@ public void When_line_is_write_file_has_correct_name() }; logger.WriteLine("Foo"); var singleFile = tempPath.GetSingle(); - Assert.AreEqual("nsb_log_2010-10-01_0.txt", Path.GetFileName(singleFile)); + Assert.That(Path.GetFileName(singleFile), Is.EqualTo("nsb_log_2010-10-01_0.txt")); } } class TempPath : IDisposable diff --git a/src/NServiceBus.Core.Tests/MessageConventionSpecs.cs b/src/NServiceBus.Core.Tests/MessageConventionSpecs.cs index 4622a6510da..94d44f77bae 100644 --- a/src/NServiceBus.Core.Tests/MessageConventionSpecs.cs +++ b/src/NServiceBus.Core.Tests/MessageConventionSpecs.cs @@ -17,10 +17,10 @@ public void Should_cache_the_message_convention() return false; }); conventions.IsMessageType(GetType()); - Assert.AreEqual(1, timesCalled); + Assert.That(timesCalled, Is.EqualTo(1)); conventions.IsMessageType(GetType()); - Assert.AreEqual(1, timesCalled); + Assert.That(timesCalled, Is.EqualTo(1)); } } @@ -40,10 +40,10 @@ public void Should_cache_the_message_convention() }); conventions.IsEventType(GetType()); - Assert.AreEqual(1, timesCalled); + Assert.That(timesCalled, Is.EqualTo(1)); conventions.IsEventType(GetType()); - Assert.AreEqual(1, timesCalled); + Assert.That(timesCalled, Is.EqualTo(1)); } } @@ -63,10 +63,10 @@ public void Should_cache_the_message_convention() }); conventions.IsCommandType(GetType()); - Assert.AreEqual(1, timesCalled); + Assert.That(timesCalled, Is.EqualTo(1)); conventions.IsCommandType(GetType()); - Assert.AreEqual(1, timesCalled); + Assert.That(timesCalled, Is.EqualTo(1)); } } diff --git a/src/NServiceBus.Core.Tests/MessageMapper/MessageMapperTests.cs b/src/NServiceBus.Core.Tests/MessageMapper/MessageMapperTests.cs index beabb8bc77d..79502b0e3d7 100644 --- a/src/NServiceBus.Core.Tests/MessageMapper/MessageMapperTests.cs +++ b/src/NServiceBus.Core.Tests/MessageMapper/MessageMapperTests.cs @@ -109,7 +109,7 @@ public void Should_fail_for_interface_message_with_illegal_interface_property() var mapper = new MessageMapper(); var ex = Assert.Throws(() => mapper.Initialize(new[] { typeof(IInterfaceMessageWithIllegalInterfaceProperty) })); - StringAssert.Contains($"Cannot generate a concrete implementation for '{typeof(IIllegalProperty).FullName}' because it contains methods. Ensure that all interfaces used as messages do not contain methods.", ex.Message); + Assert.That(ex.Message, Does.Contain($"Cannot generate a concrete implementation for '{typeof(IIllegalProperty).FullName}' because it contains methods. Ensure that all interfaces used as messages do not contain methods.")); } [Test] @@ -118,7 +118,7 @@ public void Should_fail_for_non_public_interface_message() var mapper = new MessageMapper(); var ex = Assert.Throws(() => mapper.Initialize(new[] { typeof(IPrivateInterfaceMessage) })); - StringAssert.Contains($"Cannot generate a concrete implementation for '{typeof(IPrivateInterfaceMessage).FullName}' because it is not public. Ensure that all interfaces used as messages are public.", ex.Message); + Assert.That(ex.Message, Does.Contain($"Cannot generate a concrete implementation for '{typeof(IPrivateInterfaceMessage).FullName}' because it is not public. Ensure that all interfaces used as messages are public.")); } [Test] @@ -128,8 +128,8 @@ public void CreateInstance_should_initialize_interface_message_type_on_demand() var messageInstance = mapper.CreateInstance(); - Assert.IsNotNull(messageInstance); - Assert.IsInstanceOf(messageInstance); + Assert.That(messageInstance, Is.Not.Null); + Assert.That(messageInstance, Is.InstanceOf()); } [Test] @@ -139,9 +139,12 @@ public void CreateInstance_should_initialize_message_type_on_demand() var messageInstance = mapper.CreateInstance(); - Assert.IsNotNull(messageInstance); - Assert.AreEqual(typeof(SampleMessageClass), messageInstance.GetType()); - Assert.IsTrue(messageInstance.CtorInvoked); + Assert.That(messageInstance, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(messageInstance.GetType(), Is.EqualTo(typeof(SampleMessageClass))); + Assert.That(messageInstance.CtorInvoked, Is.True); + }); } [Test] @@ -152,8 +155,8 @@ public void CreateInstance_should_not_initialize_message_type_implementing_IEnum var messageInstance = mapper.CreateInstance>(); - Assert.IsNotNull(messageInstance); - Assert.IsFalse(messageInstance.CtorInvoked); + Assert.That(messageInstance, Is.Not.Null); + Assert.That(messageInstance.CtorInvoked, Is.False); } [Test] @@ -163,8 +166,7 @@ public void Should_create_structs() var messageInstance = mapper.CreateInstance(); - Assert.IsNotNull(messageInstance); - Assert.AreEqual(typeof(SampleMessageStruct), messageInstance.GetType()); + Assert.That(messageInstance.GetType(), Is.EqualTo(typeof(SampleMessageStruct))); } [Test] @@ -174,7 +176,7 @@ public void Should_map_structs() var mappedType = mapper.GetMappedTypeFor(typeof(SampleMessageStruct)); - Assert.AreEqual(typeof(SampleMessageStruct), mappedType); + Assert.That(mappedType, Is.EqualTo(typeof(SampleMessageStruct))); } [Test] @@ -184,7 +186,7 @@ public void Should_handle_interfaces_that_have_attributes_with_nullable_properti var messageInstance = mapper.CreateInstance(); - Assert.IsNotNull(messageInstance); + Assert.That(messageInstance, Is.Not.Null); } public class SampleMessageClass diff --git a/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_ienumerable_implementations.cs b/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_ienumerable_implementations.cs index cf7a0b5a31b..d51d169d57e 100644 --- a/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_ienumerable_implementations.cs +++ b/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_ienumerable_implementations.cs @@ -18,7 +18,7 @@ public void Class_implementing_iEnumerable_string_should_be_mapped() typeof(ClassImplementingIEnumerable) }); - Assert.NotNull(mapper.GetMappedTypeFor(typeof(ClassImplementingIEnumerable))); + Assert.That(mapper.GetMappedTypeFor(typeof(ClassImplementingIEnumerable)), Is.Not.Null); } [Test] @@ -30,7 +30,7 @@ public void Class_implementing_iEnumerable_string_and_iReturnMyself_should_be_ma typeof(ClassImplementingIEnumerableAndIReturnMyself) }); - Assert.NotNull(mapper.GetMappedTypeFor(typeof(ClassImplementingIEnumerableAndIReturnMyself))); + Assert.That(mapper.GetMappedTypeFor(typeof(ClassImplementingIEnumerableAndIReturnMyself)), Is.Not.Null); } class ClassImplementingIEnumerableAndIReturnMyself : IEnumerable, IReturnMyself> { @@ -60,7 +60,7 @@ public void Class_implementing_iEnumerable_returnMyself_should_be_mapped() typeof(ClassImplementingIEnumerable) }); - Assert.NotNull(mapper.GetMappedTypeFor(typeof(ClassImplementingIEnumerable))); + Assert.That(mapper.GetMappedTypeFor(typeof(ClassImplementingIEnumerable)), Is.Not.Null); } [Test] @@ -72,7 +72,7 @@ public void Class_inheriting_from_iEnumerable_returnMyself_implementation_should typeof(DerivedReturnMyselfCollectionObject) }); - Assert.NotNull(mapper.GetMappedTypeFor(typeof(DerivedReturnMyselfCollectionObject))); + Assert.That(mapper.GetMappedTypeFor(typeof(DerivedReturnMyselfCollectionObject)), Is.Not.Null); } class DerivedReturnMyselfCollectionObject : ClassImplementingIEnumerable @@ -88,7 +88,7 @@ public void Class_implementing_returnMyself_inheriting_from_iEnumerable_returnMy typeof(DerivedReturnMyselfCollectionImplementingIReturnMyself) }); - Assert.NotNull(mapper.GetMappedTypeFor(typeof(DerivedReturnMyselfCollectionImplementingIReturnMyself))); + Assert.That(mapper.GetMappedTypeFor(typeof(DerivedReturnMyselfCollectionImplementingIReturnMyself)), Is.Not.Null); } class DerivedReturnMyselfCollectionImplementingIReturnMyself : ClassImplementingIEnumerable, IReturnMyself @@ -109,7 +109,7 @@ public void Class_implementing_base_returnMyself_inheriting_from_iEnumerable_ret typeof(DerivedReturnMyselfCollectionImplementingBaseIReturnMyself) }); - Assert.NotNull(mapper.GetMappedTypeFor(typeof(DerivedReturnMyselfCollectionImplementingBaseIReturnMyself))); + Assert.That(mapper.GetMappedTypeFor(typeof(DerivedReturnMyselfCollectionImplementingBaseIReturnMyself)), Is.Not.Null); } class DerivedReturnMyselfCollectionImplementingBaseIReturnMyself : ClassImplementingIEnumerable, IReturnMyself> diff --git a/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_interfaces.cs b/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_interfaces.cs index bf419c138c3..78ff62f6799 100644 --- a/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_interfaces.cs +++ b/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_interfaces.cs @@ -14,7 +14,7 @@ public void Interfaces_with_only_properties_should_be_mapped() var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IInterfaceWithOnlyProperties) }); - Assert.NotNull(mapper.GetMappedTypeFor(typeof(IInterfaceWithOnlyProperties))); + Assert.That(mapper.GetMappedTypeFor(typeof(IInterfaceWithOnlyProperties)), Is.Not.Null); } public interface IInterfaceWithOnlyProperties : IMessage @@ -30,7 +30,7 @@ public void Interface_should_be_created() var result = mapper.CreateInstance(null); - Assert.IsNotNull(result); + Assert.That(result, Is.Not.Null); } public interface IInterface : IMessage @@ -59,10 +59,13 @@ public void Attributes_on_properties_should_be_mapped() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IInterfaceWithPropertiesAndAttributes) }); - Assert.IsTrue(PropertyContainsAttribute("SomeProperty", typeof(SomeAttribute), mapper.CreateInstance(typeof(IInterfaceWithPropertiesAndAttributes)))); + Assert.Multiple(() => + { + Assert.That(PropertyContainsAttribute("SomeProperty", typeof(SomeAttribute), mapper.CreateInstance(typeof(IInterfaceWithPropertiesAndAttributes))), Is.True); - // Doesn't affect properties without attributes - Assert.IsFalse(PropertyContainsAttribute("SomeOtherProperty", typeof(SomeAttribute), mapper.CreateInstance(typeof(IInterfaceWithPropertiesAndAttributes)))); + // Doesn't affect properties without attributes + Assert.That(PropertyContainsAttribute("SomeOtherProperty", typeof(SomeAttribute), mapper.CreateInstance(typeof(IInterfaceWithPropertiesAndAttributes))), Is.False); + }); } public interface IInterfaceWithPropertiesAndAttributes @@ -86,7 +89,7 @@ public void Accept_Attributes_with_no_default_ctor_as_long_as_the_parameter_in_c var instance = mapper.CreateInstance(typeof(IInterfaceWithCustomAttributeThatHasNoDefaultConstructor)); var attributes = instance.GetType().GetProperty("SomeProperty").GetCustomAttributes(typeof(NoDefaultConstructorAttribute), true); var attr = (NoDefaultConstructorAttribute)attributes[0]; - Assert.AreEqual(attr.Name, "Blah"); + Assert.That(attr.Name, Is.EqualTo("Blah")); } public interface IInterfaceWithCustomAttributeThatHasNoDefaultConstructor @@ -113,7 +116,7 @@ public void Accept_Attributes_with_no_default_ctor_while_ctor_parameters_are_dif var instance = mapper.CreateInstance(typeof(IInterfaceWithCustomAttributeThatHasNoDefaultConstructorAndNoMatchingParameters)); var attributes = instance.GetType().GetProperty("SomeProperty").GetCustomAttributes(typeof(NoDefaultConstructorAndNoMatchingParametersAttribute), true); var attr = (NoDefaultConstructorAndNoMatchingParametersAttribute)attributes[0]; - Assert.AreEqual(attr.Name, "Blah"); + Assert.That(attr.Name, Is.EqualTo("Blah")); } public interface IInterfaceWithCustomAttributeThatHasNoDefaultConstructorAndNoMatchingParameters { @@ -142,7 +145,7 @@ public void Generated_type_should_preserve_namespace_to_make_it_easier_for_users var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IInterfaceToGenerate) }); - Assert.AreEqual(typeof(IInterfaceToGenerate).Namespace, mapper.CreateInstance(typeof(IInterfaceToGenerate)).GetType().Namespace); + Assert.That(mapper.CreateInstance(typeof(IInterfaceToGenerate)).GetType().Namespace, Is.EqualTo(typeof(IInterfaceToGenerate).Namespace)); } public interface IInterfaceToGenerate : IMessage @@ -158,10 +161,10 @@ public void Accept_attributes_with_value_attribute() var instance = mapper.CreateInstance(typeof(IMyEventWithAttributeWithBoolProperty)); var attributes = instance.GetType().GetProperty("EventId").GetCustomAttributes(typeof(ValuePropertiesAttribute), true); var attr = attributes[0] as ValuePropertiesAttribute; - Assert.AreEqual(attr != null && attr.FlagIsSet, true); + Assert.That(attr != null && attr.FlagIsSet, Is.EqualTo(true)); if (attr != null) { - Assert.AreEqual(attr.MyAge, 21); + Assert.That(attr.MyAge, Is.EqualTo(21)); } } diff --git a/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_usinggenerics.cs b/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_usinggenerics.cs index 1670c6fc14d..215c0fe68d9 100644 --- a/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_usinggenerics.cs +++ b/src/NServiceBus.Core.Tests/MessageMapper/When_mapping_usinggenerics.cs @@ -14,7 +14,7 @@ public void Class_abstract_generic_with_only_properties_generic_should_not_be_ma var mapper = new MessageMapper(); var genericClassType = typeof(GenericAbstractCommand<>); mapper.Initialize(new[] { genericClassType }); - Assert.Null(mapper.GetMappedTypeFor(genericClassType)); + Assert.That(mapper.GetMappedTypeFor(genericClassType), Is.Null); } public abstract class GenericAbstractCommand : IMessage where T : Data { @@ -27,7 +27,7 @@ public void Class_generic_with_only_properties_generic_should_not_be_mapped() var mapper = new MessageMapper(); var abstractClassType = typeof(GenericCommand<>); mapper.Initialize(new[] { abstractClassType }); - Assert.Null(mapper.GetMappedTypeFor(abstractClassType)); + Assert.That(mapper.GetMappedTypeFor(abstractClassType), Is.Null); } public class GenericCommand : IMessage where T : Data @@ -42,7 +42,7 @@ public void Class_derived_from_generic_with_only_properties_generic_should_be_ma var mapper = new MessageMapper(); var abstractClassType = typeof(DerivedGenericCommand); mapper.Initialize(new[] { abstractClassType }); - Assert.NotNull(mapper.GetMappedTypeFor(abstractClassType)); + Assert.That(mapper.GetMappedTypeFor(abstractClassType), Is.Not.Null); } public abstract class GenericBaseCommand : IMessage where T : Data { @@ -59,7 +59,7 @@ public void Class_concrete_generic_with_only_properties_generic_should_be_mapped var mapper = new MessageMapper(); var abstractClassType = typeof(GenericCommand); mapper.Initialize(new[] { abstractClassType }); - Assert.NotNull(mapper.GetMappedTypeFor(abstractClassType)); + Assert.That(mapper.GetMappedTypeFor(abstractClassType), Is.Not.Null); } [Test] @@ -68,7 +68,7 @@ public void Class_abstract_with_only_properties_should_be_mapped() var mapper = new MessageMapper(); var abstractClassType = typeof(SimpleAbstractClass); mapper.Initialize(new[] { abstractClassType }); - Assert.NotNull(mapper.GetMappedTypeFor(abstractClassType)); + Assert.That(mapper.GetMappedTypeFor(abstractClassType), Is.Not.Null); } public abstract class SimpleAbstractClass : IMessage { @@ -84,7 +84,7 @@ public void Class_abstract_with_methods_should_not_be_mapped() var mapper = new MessageMapper(); var abstractClassType = typeof(SimpleAbstractClassWithMethods); mapper.Initialize(new[] { abstractClassType }); - Assert.Null(mapper.GetMappedTypeFor(abstractClassType)); + Assert.That(mapper.GetMappedTypeFor(abstractClassType), Is.Null); } public abstract class SimpleAbstractClassWithMethods : IMessage { @@ -100,7 +100,7 @@ public void Interfaces_generic_with_only_properties_should_not_be_mapped() var mapper = new MessageMapper(); var genericInterfaceType = typeof(IInterfaceGenericWithProperties<>); mapper.Initialize(new[] { genericInterfaceType }); - Assert.Null(mapper.GetMappedTypeFor(genericInterfaceType)); + Assert.That(mapper.GetMappedTypeFor(genericInterfaceType), Is.Null); } public interface IInterfaceGenericWithProperties : IMessage where T : Data @@ -115,7 +115,7 @@ public void Interfaces_generic_with_methods_should_not_be_mapped() var mapper = new MessageMapper(); var genericInterfaceType = typeof(IInterfaceGenericWithMethods<>); mapper.Initialize(new[] { genericInterfaceType }); - Assert.Null(mapper.GetMappedTypeFor(genericInterfaceType)); + Assert.That(mapper.GetMappedTypeFor(genericInterfaceType), Is.Null); } public interface IInterfaceGenericWithMethods : IMessage where T : Data { @@ -129,7 +129,7 @@ public void Interfaces_with_only_properties_should_be_mapped() var mapper = new MessageMapper(); var simpleInterfaceType = typeof(IInterfaceWithOnlyProperties); mapper.Initialize(new[] { simpleInterfaceType }); - Assert.NotNull(mapper.GetMappedTypeFor(simpleInterfaceType)); + Assert.That(mapper.GetMappedTypeFor(simpleInterfaceType), Is.Not.Null); } public interface IInterfaceWithOnlyProperties : IMessage @@ -143,7 +143,7 @@ public void Interfaces_with_inheritance_and_property_overload_should_be_mapped() var mapper = new MessageMapper(); var genericInterfaceType = typeof(IInterfaceWithGenericProperty); mapper.Initialize(new[] { genericInterfaceType }); - Assert.NotNull(mapper.GetMappedTypeFor(genericInterfaceType)); + Assert.That(mapper.GetMappedTypeFor(genericInterfaceType), Is.Not.Null); } public interface IInterfaceWithGenericProperty diff --git a/src/NServiceBus.Core.Tests/MessageMutators/MutateInstanceMessage/MutateIncomingMessageBehaviorTests.cs b/src/NServiceBus.Core.Tests/MessageMutators/MutateInstanceMessage/MutateIncomingMessageBehaviorTests.cs index aca903a8557..066f624466b 100644 --- a/src/NServiceBus.Core.Tests/MessageMutators/MutateInstanceMessage/MutateIncomingMessageBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/MessageMutators/MutateInstanceMessage/MutateIncomingMessageBehaviorTests.cs @@ -23,8 +23,11 @@ public async Task Should_invoke_all_explicit_mutators() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(mutator.MutateIncomingCalled); - Assert.True(otherMutator.MutateIncomingCalled); + Assert.Multiple(() => + { + Assert.That(mutator.MutateIncomingCalled, Is.True); + Assert.That(otherMutator.MutateIncomingCalled, Is.True); + }); } [Test] @@ -40,8 +43,11 @@ public async Task Should_invoke_both_explicit_and_container_provided_mutators() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(explicitMutator.MutateIncomingCalled); - Assert.True(containerMutator.MutateIncomingCalled); + Assert.Multiple(() => + { + Assert.That(explicitMutator.MutateIncomingCalled, Is.True); + Assert.That(containerMutator.MutateIncomingCalled, Is.True); + }); } [Test] @@ -58,7 +64,7 @@ public async Task Should_not_call_MutateIncoming_when_hasIncomingMessageMutators await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.IsFalse(mutator.MutateIncomingCalled); + Assert.That(mutator.MutateIncomingCalled, Is.False); } [Test] @@ -89,7 +95,7 @@ public async Task When_no_mutator_updates_the_body_should_not_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.False(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.False); } [Test] @@ -103,7 +109,7 @@ public async Task When_no_mutator_available_should_not_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.False(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.False); } [Test] @@ -117,7 +123,7 @@ public async Task When_mutator_modifies_the_body_should_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.True); } class InterceptUpdateMessageIncomingLogicalMessageContext : TestableIncomingLogicalMessageContext diff --git a/src/NServiceBus.Core.Tests/MessageMutators/MutateInstanceMessage/MutateOutgoingMessageBehaviorTests.cs b/src/NServiceBus.Core.Tests/MessageMutators/MutateInstanceMessage/MutateOutgoingMessageBehaviorTests.cs index 0b113a5858c..474f21a22b8 100644 --- a/src/NServiceBus.Core.Tests/MessageMutators/MutateInstanceMessage/MutateOutgoingMessageBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/MessageMutators/MutateInstanceMessage/MutateOutgoingMessageBehaviorTests.cs @@ -23,8 +23,11 @@ public async Task Should_invoke_all_explicit_mutators() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(mutator.MutateOutgoingCalled); - Assert.True(otherMutator.MutateOutgoingCalled); + Assert.Multiple(() => + { + Assert.That(mutator.MutateOutgoingCalled, Is.True); + Assert.That(otherMutator.MutateOutgoingCalled, Is.True); + }); } [Test] @@ -40,8 +43,11 @@ public async Task Should_invoke_both_explicit_and_container_provided_mutators() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(explicitMutator.MutateOutgoingCalled); - Assert.True(containerMutator.MutateOutgoingCalled); + Assert.Multiple(() => + { + Assert.That(explicitMutator.MutateOutgoingCalled, Is.True); + Assert.That(containerMutator.MutateOutgoingCalled, Is.True); + }); } [Test] @@ -58,7 +64,7 @@ public async Task Should_not_call_MutateOutgoing_when_hasOutgoingMessageMutators await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.IsFalse(mutator.MutateOutgoingCalled); + Assert.That(mutator.MutateOutgoingCalled, Is.False); } [Test] @@ -85,7 +91,7 @@ public async Task When_no_mutator_updates_the_body_should_not_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.False(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.False); } [Test] @@ -99,7 +105,7 @@ public async Task When_no_mutator_available_should_not_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.False(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.False); } [Test] @@ -113,7 +119,7 @@ public async Task When_mutator_modifies_the_body_should_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.True); } class InterceptUpdateMessageOutgoingLogicalMessageContext : TestableOutgoingLogicalMessageContext diff --git a/src/NServiceBus.Core.Tests/MessageMutators/MutateTransportMessage/MutateIncomingTransportMessageBehaviorTests.cs b/src/NServiceBus.Core.Tests/MessageMutators/MutateTransportMessage/MutateIncomingTransportMessageBehaviorTests.cs index 9063ea46675..c8255d6d5b3 100644 --- a/src/NServiceBus.Core.Tests/MessageMutators/MutateTransportMessage/MutateIncomingTransportMessageBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/MessageMutators/MutateTransportMessage/MutateIncomingTransportMessageBehaviorTests.cs @@ -22,8 +22,11 @@ public async Task Should_invoke_all_explicit_mutators() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(mutator.MutateIncomingCalled); - Assert.True(otherMutator.MutateIncomingCalled); + Assert.Multiple(() => + { + Assert.That(mutator.MutateIncomingCalled, Is.True); + Assert.That(otherMutator.MutateIncomingCalled, Is.True); + }); } [Test] @@ -39,8 +42,11 @@ public async Task Should_invoke_both_explicit_and_container_provided_mutators() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(explicitMutator.MutateIncomingCalled); - Assert.True(containerMutator.MutateIncomingCalled); + Assert.Multiple(() => + { + Assert.That(explicitMutator.MutateIncomingCalled, Is.True); + Assert.That(containerMutator.MutateIncomingCalled, Is.True); + }); } [Test] @@ -57,7 +63,7 @@ public async Task Should_not_call_MutateIncoming_when_hasIncomingTransportMessag await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.IsFalse(mutator.MutateIncomingCalled); + Assert.That(mutator.MutateIncomingCalled, Is.False); } [Test] @@ -83,7 +89,7 @@ public async Task When_no_mutator_updates_the_body_should_not_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.False(context.UpdateMessageBodyCalled); + Assert.That(context.UpdateMessageBodyCalled, Is.False); } [Test] @@ -97,7 +103,7 @@ public async Task When_no_mutator_available_should_not_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.False(context.UpdateMessageBodyCalled); + Assert.That(context.UpdateMessageBodyCalled, Is.False); } [Test] @@ -111,7 +117,7 @@ public async Task When_mutator_modifies_the_body_should_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(context.UpdateMessageBodyCalled); + Assert.That(context.UpdateMessageBodyCalled, Is.True); } class InterceptUpdateMessageIncomingPhysicalMessageContext : TestableIncomingPhysicalMessageContext diff --git a/src/NServiceBus.Core.Tests/MessageMutators/MutateTransportMessage/MutateOutgoingTransportMessageBehaviorTests.cs b/src/NServiceBus.Core.Tests/MessageMutators/MutateTransportMessage/MutateOutgoingTransportMessageBehaviorTests.cs index 9308e7cc01c..8af6929e045 100644 --- a/src/NServiceBus.Core.Tests/MessageMutators/MutateTransportMessage/MutateOutgoingTransportMessageBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/MessageMutators/MutateTransportMessage/MutateOutgoingTransportMessageBehaviorTests.cs @@ -24,8 +24,11 @@ public async Task Should_invoke_all_explicit_mutators() await behavior.Invoke(physicalContext, ctx => Task.CompletedTask); - Assert.True(mutator.MutateOutgoingCalled); - Assert.True(otherMutator.MutateOutgoingCalled); + Assert.Multiple(() => + { + Assert.That(mutator.MutateOutgoingCalled, Is.True); + Assert.That(otherMutator.MutateOutgoingCalled, Is.True); + }); } [Test] @@ -42,8 +45,11 @@ public async Task Should_invoke_both_explicit_and_container_provided_mutators() await behavior.Invoke(physicalContext, ctx => Task.CompletedTask); - Assert.True(explicitMutator.MutateOutgoingCalled); - Assert.True(containerMutator.MutateOutgoingCalled); + Assert.Multiple(() => + { + Assert.That(explicitMutator.MutateOutgoingCalled, Is.True); + Assert.That(containerMutator.MutateOutgoingCalled, Is.True); + }); } [Test] @@ -61,7 +67,7 @@ public async Task Should_not_call_MutateOutgoing_when_hasOutgoingTransportMessag await behavior.Invoke(physicalContext, ctx => Task.CompletedTask); - Assert.IsFalse(mutator.MutateOutgoingCalled); + Assert.That(mutator.MutateOutgoingCalled, Is.False); } [Test] @@ -88,7 +94,7 @@ public async Task When_no_mutator_updates_the_body_should_not_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.False(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.False); } [Test] @@ -103,7 +109,7 @@ public async Task When_no_mutator_available_should_not_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.False(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.False); } [Test] @@ -118,7 +124,7 @@ public async Task When_mutator_modifies_the_body_should_update_the_body() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.True(context.UpdateMessageCalled); + Assert.That(context.UpdateMessageCalled, Is.True); } class InterceptUpdateMessageOutgoingPhysicalMessageContext : TestableOutgoingPhysicalMessageContext diff --git a/src/NServiceBus.Core.Tests/MessageMutators/MutatorRegistrationExtensionsTests.cs b/src/NServiceBus.Core.Tests/MessageMutators/MutatorRegistrationExtensionsTests.cs index d2434eda306..a2f14b34717 100644 --- a/src/NServiceBus.Core.Tests/MessageMutators/MutatorRegistrationExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/MessageMutators/MutatorRegistrationExtensionsTests.cs @@ -14,9 +14,9 @@ public void Should_throw_ArgumentException_when_registering_non_mutator_type() var endpointConfiguration = new EndpointConfiguration("test"); var exception = Assert.Throws(() => endpointConfiguration.RegisterMessageMutator(new object())); - StringAssert.Contains( - "The given instance is not a valid message mutator. Implement one of the following mutator interfaces: NServiceBus.MessageMutator.IMutateIncomingMessages, NServiceBus.MessageMutator.IMutateIncomingTransportMessages, NServiceBus.MessageMutator.IMutateOutgoingMessages or NServiceBus.MessageMutator.IMutateOutgoingTransportMessages", - exception.Message); + Assert.That( + exception.Message, + Does.Contain("The given instance is not a valid message mutator. Implement one of the following mutator interfaces: NServiceBus.MessageMutator.IMutateIncomingMessages, NServiceBus.MessageMutator.IMutateIncomingTransportMessages, NServiceBus.MessageMutator.IMutateOutgoingMessages or NServiceBus.MessageMutator.IMutateOutgoingTransportMessages")); } [TestCase(typeof(IncomingMessageMutator))] @@ -47,22 +47,22 @@ public void Should_only_invoke_instances_once_even_if_registered_multiple_times( if (mutatorType == typeof(IncomingMessageMutator)) { - Assert.AreEqual(1, registry.IncomingMessage.Count); + Assert.That(registry.IncomingMessage.Count, Is.EqualTo(1)); } if (mutatorType == typeof(IncomingTransportMessageMutator)) { - Assert.AreEqual(1, registry.IncomingTransportMessage.Count); + Assert.That(registry.IncomingTransportMessage.Count, Is.EqualTo(1)); } if (mutatorType == typeof(OutgoingMessageMutator)) { - Assert.AreEqual(1, registry.OutgoingMessage.Count); + Assert.That(registry.OutgoingMessage.Count, Is.EqualTo(1)); } if (mutatorType == typeof(OutgoingTransportMessageMutator)) { - Assert.AreEqual(1, registry.OutgoingTransportMessage.Count); + Assert.That(registry.OutgoingTransportMessage.Count, Is.EqualTo(1)); } } diff --git a/src/NServiceBus.Core.Tests/MessageSessionTests.cs b/src/NServiceBus.Core.Tests/MessageSessionTests.cs index 9896d4cfb60..26ad11081af 100644 --- a/src/NServiceBus.Core.Tests/MessageSessionTests.cs +++ b/src/NServiceBus.Core.Tests/MessageSessionTests.cs @@ -32,7 +32,7 @@ public async Task Should_not_share_root_context_across_operations() await session.Send(new object()); await session.Send(new object()); - Assert.IsEmpty(readValues, "writes should not leak to other pipeline invocations"); + Assert.That(readValues, Is.Empty, "writes should not leak to other pipeline invocations"); } [Test] diff --git a/src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj b/src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj index 2c4e56c6907..b37d418dadc 100644 --- a/src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj +++ b/src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj @@ -16,6 +16,7 @@ + diff --git a/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityDecoratorTests.cs b/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityDecoratorTests.cs index 99d39465462..a18be0f0eb8 100644 --- a/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityDecoratorTests.cs +++ b/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityDecoratorTests.cs @@ -52,8 +52,11 @@ public void PromoteHeadersToTags_should_promote_promotable_headers_to_tags() var tags = activity.Tags.ToImmutableDictionary(); - Assert.AreEqual(2, tags.Count, "should only contain approved NServiceBus headers"); - Assert.AreEqual(headers[Headers.MessageId], tags["nservicebus.message_id"]); - Assert.AreEqual(headers[Headers.ControlMessageHeader], tags["nservicebus.control_message"]); + Assert.That(tags.Count, Is.EqualTo(2), "should only contain approved NServiceBus headers"); + Assert.Multiple(() => + { + Assert.That(tags["nservicebus.message_id"], Is.EqualTo(headers[Headers.MessageId])); + Assert.That(tags["nservicebus.control_message"], Is.EqualTo(headers[Headers.ControlMessageHeader])); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityExtensionsTests.cs b/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityExtensionsTests.cs index f737e4f4987..a0549ba7db6 100644 --- a/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityExtensionsTests.cs @@ -14,8 +14,11 @@ public void TryGetRecordingPipelineActivity_should_return_false_when_key_not_fou ambientActivity.Start(); var contextBag = new ContextBag(); - Assert.IsFalse(contextBag.TryGetRecordingOutgoingPipelineActivity(out var activity)); - Assert.IsNull(activity); + Assert.Multiple(() => + { + Assert.That(contextBag.TryGetRecordingOutgoingPipelineActivity(out var activity), Is.False); + Assert.That(activity, Is.Null); + }); } [Test] @@ -27,8 +30,11 @@ public void TryGetRecordingPipelineActivity_should_return_false_when_value_null( var contextBag = new ContextBag(); contextBag.SetOutgoingPipelineActitvity(null); - Assert.IsFalse(contextBag.TryGetRecordingOutgoingPipelineActivity(out var activity)); - Assert.IsNull(activity); + Assert.Multiple(() => + { + Assert.That(contextBag.TryGetRecordingOutgoingPipelineActivity(out var activity), Is.False); + Assert.That(activity, Is.Null); + }); } [Test] @@ -43,7 +49,10 @@ public void TryGetRecordingPipelineActivity_should_return_false_when_not_recordi var contextBag = new ContextBag(); contextBag.SetOutgoingPipelineActitvity(recordingActivity); - Assert.IsTrue(contextBag.TryGetRecordingOutgoingPipelineActivity(out var activity)); - Assert.AreEqual(recordingActivity, activity); + Assert.Multiple(() => + { + Assert.That(contextBag.TryGetRecordingOutgoingPipelineActivity(out var activity), Is.True); + Assert.That(activity, Is.EqualTo(recordingActivity)); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityFactoryTests.cs b/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityFactoryTests.cs index dca19ddcd12..73d5d97a7ae 100644 --- a/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityFactoryTests.cs +++ b/src/NServiceBus.Core.Tests/OpenTelemetry/ActivityFactoryTests.cs @@ -44,9 +44,12 @@ public void Should_attach_to_context_activity_when_activity_on_context() var activity = activityFactory.StartIncomingPipelineActivity(CreateMessageContext(contextBag: contextBag)); - Assert.NotNull(activity, "should create activity for receive pipeline"); - Assert.AreEqual(contextActivity.Id, activity.ParentId, "should use context activity as parent"); - Assert.AreEqual(0, activity.Links.Count(), "should not link to logical send span"); + Assert.That(activity, Is.Not.Null, "should create activity for receive pipeline"); + Assert.Multiple(() => + { + Assert.That(activity.ParentId, Is.EqualTo(contextActivity.Id), "should use context activity as parent"); + Assert.That(activity.Links.Count(), Is.EqualTo(0), "should not link to logical send span"); + }); } [Test] @@ -62,11 +65,14 @@ public void Should_attach_to_context_activity_when_activity_on_context_and_trace var activity = activityFactory.StartIncomingPipelineActivity(CreateMessageContext(messageHeaders, contextBag)); - Assert.NotNull(activity, "should create activity for receive pipeline"); - Assert.AreEqual(contextActivity.Id, activity.ParentId, "should use context activity as parent"); - Assert.AreEqual(1, activity.Links.Count(), "should link to logical send span"); - Assert.AreEqual(sendActivity.TraceId, activity.Links.Single().Context.TraceId); - Assert.AreEqual(sendActivity.SpanId, activity.Links.Single().Context.SpanId); + Assert.That(activity, Is.Not.Null, "should create activity for receive pipeline"); + Assert.Multiple(() => + { + Assert.That(activity.ParentId, Is.EqualTo(contextActivity.Id), "should use context activity as parent"); + Assert.That(activity.Links.Count(), Is.EqualTo(1), "should link to logical send span"); + Assert.That(activity.Links.Single().Context.TraceId, Is.EqualTo(sendActivity.TraceId)); + Assert.That(activity.Links.Single().Context.SpanId, Is.EqualTo(sendActivity.SpanId)); + }); } [Test] @@ -77,28 +83,31 @@ public void Should_attach_to_context_activity_when_activity_on_context_and_ambie contextBag.Set(contextActivity); using var ambientActivity = ActivitySources.Main.StartActivity("ambient activity"); - Assert.AreEqual(ambientActivity, Activity.Current); + Assert.That(Activity.Current, Is.EqualTo(ambientActivity)); var activity = activityFactory.StartIncomingPipelineActivity(CreateMessageContext(contextBag: contextBag)); - Assert.NotNull(activity, "should create activity for receive pipeline"); - Assert.AreEqual(contextActivity.Id, activity.ParentId, "should use context activity as parent"); + Assert.That(activity, Is.Not.Null, "should create activity for receive pipeline"); + Assert.That(activity.ParentId, Is.EqualTo(contextActivity.Id), "should use context activity as parent"); } [Test] public void Should_start_new_trace_when_activity_on_context_uses_legacy_id_format() { using var contextActivity = CreateCompletedActivity("transport receive activity", ActivityIdFormat.Hierarchical); - Assert.AreEqual(ActivityIdFormat.Hierarchical, contextActivity.IdFormat); + Assert.That(contextActivity.IdFormat, Is.EqualTo(ActivityIdFormat.Hierarchical)); var contextBag = new ContextBag(); contextBag.Set(contextActivity); var activity = activityFactory.StartIncomingPipelineActivity(CreateMessageContext(contextBag: contextBag)); - Assert.NotNull(activity, "should create activity for receive pipeline"); - Assert.IsNull(activity.ParentId, "should create a new trace"); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); + Assert.That(activity, Is.Not.Null, "should create activity for receive pipeline"); + Assert.Multiple(() => + { + Assert.That(activity.ParentId, Is.Null, "should create a new trace"); + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + }); } [Test] @@ -110,9 +119,12 @@ public void Should_attach_to_header_trace_when_no_activity_on_context_and_trace_ var activity = activityFactory.StartIncomingPipelineActivity(CreateMessageContext(messageHeaders)); - Assert.NotNull(activity, "should create activity for receive pipeline"); - Assert.AreEqual(sendActivity.Id, activity.ParentId); - Assert.AreEqual(0, activity.Links.Count(), "should not link to logical send span"); + Assert.That(activity, Is.Not.Null, "should create activity for receive pipeline"); + Assert.Multiple(() => + { + Assert.That(activity.ParentId, Is.EqualTo(sendActivity.Id)); + Assert.That(activity.Links.Count(), Is.EqualTo(0), "should not link to logical send span"); + }); } [TestCase(ActivityIdFormat.W3C)] @@ -125,9 +137,12 @@ public void Should_attach_to_ambient_trace_when_no_activity_on_context_and_no_tr var activity = activityFactory.StartIncomingPipelineActivity(CreateMessageContext()); - Assert.NotNull(activity, "should create activity for receive pipeline"); - Assert.AreEqual(ambientActivity.Id, activity.ParentId, "should attach to ambient activity"); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); + Assert.That(activity, Is.Not.Null, "should create activity for receive pipeline"); + Assert.Multiple(() => + { + Assert.That(activity.ParentId, Is.EqualTo(ambientActivity.Id), "should attach to ambient activity"); + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + }); } [Test] @@ -135,9 +150,12 @@ public void Should_start_new_trace_when_no_activity_on_context_and_no_trace_mess { var activity = activityFactory.StartIncomingPipelineActivity(CreateMessageContext()); - Assert.NotNull(activity, "should create activity for receive pipeline"); - Assert.IsNull(activity.ParentId, "should start a new trace"); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); + Assert.That(activity, Is.Not.Null, "should create activity for receive pipeline"); + Assert.Multiple(() => + { + Assert.That(activity.ParentId, Is.Null, "should start a new trace"); + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + }); } [Test] @@ -147,9 +165,12 @@ public void Should_start_new_trace_when_trace_header_contains_invalid_data() var activity = activityFactory.StartIncomingPipelineActivity(CreateMessageContext(messageHeaders)); - Assert.NotNull(activity, "should create activity for receive pipeline"); - Assert.IsNull(activity.ParentId, "should start new trace"); - Assert.AreEqual(0, activity.Links.Count(), "should not link to logical send span"); + Assert.That(activity, Is.Not.Null, "should create activity for receive pipeline"); + Assert.Multiple(() => + { + Assert.That(activity.ParentId, Is.Null, "should start new trace"); + Assert.That(activity.Links.Count(), Is.EqualTo(0), "should not link to logical send span"); + }); } [Test] @@ -159,7 +180,7 @@ public void Should_add_native_message_id_tag() var activity = activityFactory.StartIncomingPipelineActivity(messageContext); - Assert.AreEqual(messageContext.NativeMessageId, activity.Tags.ToImmutableDictionary()["nservicebus.native_message_id"]); + Assert.That(activity.Tags.ToImmutableDictionary()["nservicebus.native_message_id"], Is.EqualTo(messageContext.NativeMessageId)); } static Activity CreateCompletedActivity(string activityName, ActivityIdFormat idFormat = ActivityIdFormat.W3C) @@ -193,7 +214,7 @@ public void Should_attach_ambient_activity() var activity = activityFactory.StartOutgoingPipelineActivity("activityName", "activityDisplayName", new FakeRootContext()); - Assert.AreEqual(ambientActivity.Id, activity.ParentId); + Assert.That(activity.ParentId, Is.EqualTo(ambientActivity.Id)); } [Test] @@ -205,8 +226,11 @@ public void Should_always_create_a_w3c_id() var activity = activityFactory.StartOutgoingPipelineActivity("activityName", "activityDisplayName", new FakeRootContext()); - Assert.AreEqual(ambientActivity.Id, activity.ParentId); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); + Assert.Multiple(() => + { + Assert.That(activity.ParentId, Is.EqualTo(ambientActivity.Id)); + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + }); } [Test] @@ -215,7 +239,7 @@ public void Should_set_activity_in_context() var context = new FakeRootContext(); activityFactory.StartOutgoingPipelineActivity("activityName", "activityDisplayName", context); - Assert.IsNotNull(context.Extensions.Get(ActivityExtensions.OutgoingActivityKey)); + Assert.That(context.Extensions.Get(ActivityExtensions.OutgoingActivityKey), Is.Not.Null); } } @@ -227,7 +251,7 @@ public void Should_not_start_activity_when_no_parent_activity_exists() Type handlerType = typeof(StartHandlerActivity); var activity = activityFactory.StartHandlerActivity(new MessageHandler((_, _, _) => Task.CompletedTask, handlerType), null); - Assert.IsNull(activity, "should not start handler activity when no parent activity exists"); + Assert.That(activity, Is.Null, "should not start handler activity when no parent activity exists"); } [Test] @@ -240,9 +264,9 @@ public void Should_set_handler_type_as_tag() var activity = activityFactory.StartHandlerActivity(new MessageHandler((_, _, _) => Task.CompletedTask, handlerType), null); - Assert.IsNotNull(activity); + Assert.That(activity, Is.Not.Null); var tags = activity.Tags.ToImmutableDictionary(); - Assert.AreEqual(handlerType.FullName, tags[ActivityTags.HandlerType]); + Assert.That(tags[ActivityTags.HandlerType], Is.EqualTo(handlerType.FullName)); } [Test] @@ -255,10 +279,10 @@ public void Should_set_saga_id_when_saga() var activity = activityFactory.StartHandlerActivity(new MessageHandler((_, _, _) => Task.CompletedTask, typeof(StartHandlerActivity)), sagaInstance); - Assert.IsNotNull(activity); + Assert.That(activity, Is.Not.Null); var tags = activity.Tags.ToImmutableDictionary(); - Assert.AreEqual(sagaInstance.SagaId, tags[ActivityTags.HandlerSagaId]); + Assert.That(tags[ActivityTags.HandlerSagaId], Is.EqualTo(sagaInstance.SagaId)); } } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/OpenTelemetry/ContextPropagationTests.cs b/src/NServiceBus.Core.Tests/OpenTelemetry/ContextPropagationTests.cs index 57bf9d3e73c..cdefaac5700 100644 --- a/src/NServiceBus.Core.Tests/OpenTelemetry/ContextPropagationTests.cs +++ b/src/NServiceBus.Core.Tests/OpenTelemetry/ContextPropagationTests.cs @@ -22,7 +22,7 @@ public void Propagate_activity_id_to_header() ContextPropagation.PropagateContextToHeaders(activity, headers, new ContextBag()); - Assert.AreEqual(headers[Headers.DiagnosticsTraceParent], activity.Id); + Assert.That(activity.Id, Is.EqualTo(headers[Headers.DiagnosticsTraceParent])); } [Test] @@ -32,7 +32,7 @@ public void Should_not_set_header_without_activity() ContextPropagation.PropagateContextToHeaders(null, headers, new ContextBag()); - Assert.IsEmpty(headers); + Assert.That(headers, Is.Empty); } [Test] @@ -47,8 +47,11 @@ public void Should_set_start_new_trace_header_when_adding_trace_parent_header() contextBag.Set(Headers.StartNewTrace, bool.TrueString); ContextPropagation.PropagateContextToHeaders(activity, headers, contextBag); - Assert.IsTrue(headers.ContainsKey(Headers.StartNewTrace), bool.TrueString); - Assert.AreEqual(headers[Headers.StartNewTrace], bool.TrueString); + Assert.Multiple(() => + { + Assert.That(headers.ContainsKey(Headers.StartNewTrace), Is.True, bool.TrueString); + Assert.That(bool.TrueString, Is.EqualTo(headers[Headers.StartNewTrace])); + }); } [Test] @@ -59,7 +62,7 @@ public void Should_not_set_start_new_trace_header_when_no_trace_parent_header_is contextBag.Set(Headers.StartNewTrace, bool.TrueString); ContextPropagation.PropagateContextToHeaders(null, headers, contextBag); - Assert.IsFalse(headers.ContainsKey(Headers.StartNewTrace)); + Assert.That(headers.ContainsKey(Headers.StartNewTrace), Is.False); } [Test] @@ -76,13 +79,13 @@ public void Overwrites_existing_propagation_header() ContextPropagation.PropagateContextToHeaders(activity, headers, new ContextBag()); - Assert.AreEqual(headers[Headers.DiagnosticsTraceParent], activity.Id); + Assert.That(activity.Id, Is.EqualTo(headers[Headers.DiagnosticsTraceParent])); } [TestCaseSource(nameof(TestCases))] public void Can_propagate_baggage_from_header_to_activity(ContextPropagationTestCase testCase) { - TestContext.WriteLine($"Baggage header: {testCase.BaggageHeaderValue}"); + TestContext.Out.WriteLine($"Baggage header: {testCase.BaggageHeaderValue}"); var headers = new Dictionary(); @@ -99,15 +102,15 @@ public void Can_propagate_baggage_from_header_to_activity(ContextPropagationTest { var key = baggageItem.Key; var actualValue = activity.GetBaggageItem(key); - Assert.IsNotNull(actualValue, $"Baggage is missing item with key |{key}|"); - Assert.AreEqual(baggageItem.Value, actualValue, $"Baggage item |{key}| has the wrong value"); + Assert.That(actualValue, Is.Not.Null, $"Baggage is missing item with key |{key}|"); + Assert.That(actualValue, Is.EqualTo(baggageItem.Value), $"Baggage item |{key}| has the wrong value"); } } [TestCaseSource(nameof(TestCases))] public void Can_propagate_baggage_from_activity_to_header(ContextPropagationTestCase testCase) { - TestContext.WriteLine($"Baggage header: {testCase.BaggageHeaderValue}"); + TestContext.Out.WriteLine($"Baggage header: {testCase.BaggageHeaderValue}"); var headers = new Dictionary(); @@ -124,20 +127,23 @@ public void Can_propagate_baggage_from_activity_to_header(ContextPropagationTest if (testCase.HasBaggage) { - Assert.IsTrue(baggageHeaderSet, "Should have a baggage header if there is baggage"); + Assert.Multiple(() => + { + Assert.That(baggageHeaderSet, Is.True, "Should have a baggage header if there is baggage"); - Assert.AreEqual(testCase.BaggageHeaderValueWithoutOptionalWhitespace, baggageValue, "baggage header is set but is not correct"); + Assert.That(baggageValue, Is.EqualTo(testCase.BaggageHeaderValueWithoutOptionalWhitespace), "baggage header is set but is not correct"); + }); } else { - Assert.IsFalse(baggageHeaderSet, "baggage header should not be set if there is no baggage"); + Assert.That(baggageHeaderSet, Is.False, "baggage header should not be set if there is no baggage"); } } [TestCaseSource(nameof(TestCases))] public void Can_roundtrip_baggage(ContextPropagationTestCase testCase) { - TestContext.WriteLine($"Baggage header: {testCase.BaggageHeaderValue}"); + TestContext.Out.WriteLine($"Baggage header: {testCase.BaggageHeaderValue}"); var outgoingHeaders = new Dictionary(); var outgoingActivity = new Activity(ActivityNames.OutgoingMessageActivityName); @@ -159,8 +165,8 @@ public void Can_roundtrip_baggage(ContextPropagationTestCase testCase) { var key = baggageItem.Key; var actualValue = incomingActivity.GetBaggageItem(key); - Assert.IsNotNull(actualValue, $"Baggage is missing item with key |{key}|"); - Assert.AreEqual(baggageItem.Value, actualValue, $"Baggage item |{key}| has the wrong value"); + Assert.That(actualValue, Is.Not.Null, $"Baggage is missing item with key |{key}|"); + Assert.That(actualValue, Is.EqualTo(baggageItem.Value), $"Baggage item |{key}| has the wrong value"); } } diff --git a/src/NServiceBus.Core.Tests/OpenTelemetry/Helpers/TestingMetricListener.cs b/src/NServiceBus.Core.Tests/OpenTelemetry/Helpers/TestingMetricListener.cs index a03c8ff6cd1..0268b0aaa25 100644 --- a/src/NServiceBus.Core.Tests/OpenTelemetry/Helpers/TestingMetricListener.cs +++ b/src/NServiceBus.Core.Tests/OpenTelemetry/Helpers/TestingMetricListener.cs @@ -22,7 +22,7 @@ public TestingMetricListener(string sourceName) { if (instrument.Meter.Name == sourceName) { - TestContext.WriteLine($"Subscribing to {instrument.Meter.Name}\\{instrument.Name}"); + TestContext.Out.WriteLine($"Subscribing to {instrument.Meter.Name}\\{instrument.Name}"); listener.EnableMeasurementEvents(instrument); metrics.Add(instrument); version = instrument.Meter.Version; @@ -36,7 +36,7 @@ public TestingMetricListener(string sourceName) ReadOnlySpan> t, object _) => { - TestContext.WriteLine($"{instrument.Meter.Name}\\{instrument.Name}:{measurement}"); + TestContext.Out.WriteLine($"{instrument.Meter.Name}\\{instrument.Name}:{measurement}"); var tags = t.ToArray(); ReportedMeters.AddOrUpdate(instrument.Name, measurement, (_, val) => val + measurement); @@ -63,12 +63,15 @@ public void AssertMetric(string metricName, long expected) { if (expected == 0) { - Assert.False(ReportedMeters.ContainsKey(metricName), $"Should not have '{metricName}' metric reported."); + Assert.That(ReportedMeters.ContainsKey(metricName), Is.False, $"Should not have '{metricName}' metric reported."); } else { - Assert.True(ReportedMeters.ContainsKey(metricName), $"'{metricName}' metric was not reported."); - Assert.AreEqual(expected, ReportedMeters[metricName]); + Assert.Multiple(() => + { + Assert.That(ReportedMeters.ContainsKey(metricName), Is.True, $"'{metricName}' metric was not reported."); + Assert.That(ReportedMeters[metricName], Is.EqualTo(expected)); + }); } } diff --git a/src/NServiceBus.Core.Tests/OpenTelemetry/MessageOperationsTests.cs b/src/NServiceBus.Core.Tests/OpenTelemetry/MessageOperationsTests.cs index 9ab8cd6b7e5..0c5621cb3ae 100644 --- a/src/NServiceBus.Core.Tests/OpenTelemetry/MessageOperationsTests.cs +++ b/src/NServiceBus.Core.Tests/OpenTelemetry/MessageOperationsTests.cs @@ -37,15 +37,18 @@ public async Task Send_should_create_span() await operations.Send(new FakeRootContext(), new object(), new SendOptions()); - Assert.IsNotNull(activity); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); - Assert.AreEqual(ActivityStatusCode.Ok, activity.Status); - Assert.AreEqual(activity.RootId, activity.TraceId.ToString()); + Assert.That(activity, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + Assert.That(activity.Status, Is.EqualTo(ActivityStatusCode.Ok)); + Assert.That(activity.TraceId.ToString(), Is.EqualTo(activity.RootId)); - Assert.AreEqual(ActivityNames.OutgoingMessageActivityName, activity.OperationName); - Assert.AreEqual("send message", activity.DisplayName); + Assert.That(activity.OperationName, Is.EqualTo(ActivityNames.OutgoingMessageActivityName)); + Assert.That(activity.DisplayName, Is.EqualTo("send message")); - Assert.AreEqual(activity, operations.SendPipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey)); + Assert.That(operations.SendPipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey), Is.EqualTo(activity)); + }); } [Test] @@ -60,15 +63,18 @@ public async Task Publish_should_create_span() await operations.Publish(new FakeRootContext(), new object(), new PublishOptions()); - Assert.IsNotNull(activity); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); - Assert.AreEqual(ActivityStatusCode.Ok, activity.Status); - Assert.AreEqual(activity.RootId, activity.TraceId.ToString()); + Assert.That(activity, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + Assert.That(activity.Status, Is.EqualTo(ActivityStatusCode.Ok)); + Assert.That(activity.TraceId.ToString(), Is.EqualTo(activity.RootId)); - Assert.AreEqual(ActivityNames.OutgoingEventActivityName, activity.OperationName); - Assert.AreEqual("publish event", activity.DisplayName); + Assert.That(activity.OperationName, Is.EqualTo(ActivityNames.OutgoingEventActivityName)); + Assert.That(activity.DisplayName, Is.EqualTo("publish event")); - Assert.AreEqual(activity, operations.PublishPipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey)); + Assert.That(operations.PublishPipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey), Is.EqualTo(activity)); + }); } [Test] @@ -83,15 +89,18 @@ public async Task Reply_should_create_span() await operations.Reply(new FakeRootContext(), new object(), new ReplyOptions()); - Assert.IsNotNull(activity); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); - Assert.AreEqual(ActivityStatusCode.Ok, activity.Status); - Assert.AreEqual(activity.RootId, activity.TraceId.ToString()); + Assert.That(activity, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + Assert.That(activity.Status, Is.EqualTo(ActivityStatusCode.Ok)); + Assert.That(activity.TraceId.ToString(), Is.EqualTo(activity.RootId)); - Assert.AreEqual(ActivityNames.OutgoingMessageActivityName, activity.OperationName); - Assert.AreEqual("reply", activity.DisplayName); + Assert.That(activity.OperationName, Is.EqualTo(ActivityNames.OutgoingMessageActivityName)); + Assert.That(activity.DisplayName, Is.EqualTo("reply")); - Assert.AreEqual(activity, operations.ReplyPipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey)); + Assert.That(operations.ReplyPipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey), Is.EqualTo(activity)); + }); } [Test] @@ -106,15 +115,18 @@ public async Task Subscribe_should_create_span() await operations.Subscribe(new FakeRootContext(), typeof(object), new SubscribeOptions()); - Assert.IsNotNull(activity); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); - Assert.AreEqual(ActivityStatusCode.Ok, activity.Status); - Assert.AreEqual(activity.RootId, activity.TraceId.ToString()); + Assert.That(activity, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + Assert.That(activity.Status, Is.EqualTo(ActivityStatusCode.Ok)); + Assert.That(activity.TraceId.ToString(), Is.EqualTo(activity.RootId)); - Assert.AreEqual(ActivityNames.SubscribeActivityName, activity.OperationName); - Assert.AreEqual("subscribe event", activity.DisplayName); + Assert.That(activity.OperationName, Is.EqualTo(ActivityNames.SubscribeActivityName)); + Assert.That(activity.DisplayName, Is.EqualTo("subscribe event")); - Assert.AreEqual(activity, operations.SubscribePipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey)); + Assert.That(operations.SubscribePipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey), Is.EqualTo(activity)); + }); } [Test] @@ -129,15 +141,18 @@ public async Task Unsubscribe_should_create_span() await operations.Unsubscribe(new FakeRootContext(), typeof(object), new UnsubscribeOptions()); - Assert.IsNotNull(activity); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); - Assert.AreEqual(ActivityStatusCode.Ok, activity.Status); - Assert.AreEqual(activity.RootId, activity.TraceId.ToString()); + Assert.That(activity, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + Assert.That(activity.Status, Is.EqualTo(ActivityStatusCode.Ok)); + Assert.That(activity.TraceId.ToString(), Is.EqualTo(activity.RootId)); - Assert.AreEqual(ActivityNames.UnsubscribeActivityName, activity.OperationName); - Assert.AreEqual("unsubscribe event", activity.DisplayName); + Assert.That(activity.OperationName, Is.EqualTo(ActivityNames.UnsubscribeActivityName)); + Assert.That(activity.DisplayName, Is.EqualTo("unsubscribe event")); - Assert.AreEqual(activity, operations.UnsubscribePipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey)); + Assert.That(operations.UnsubscribePipeline.LastContext.Extensions.Get(ActivityExtensions.OutgoingActivityKey), Is.EqualTo(activity)); + }); } [Test] @@ -153,10 +168,13 @@ public void Should_set_span_error_state_on_failure() var ex = Assert.ThrowsAsync(async () => await operations.Send(new FakeRootContext(), new object(), new SendOptions())); - Assert.AreEqual(ActivityStatusCode.Error, activity.Status); + Assert.That(activity.Status, Is.EqualTo(ActivityStatusCode.Error)); var tags = activity.Tags.ToImmutableDictionary(); - Assert.AreEqual("ERROR", tags["otel.status_code"]); - Assert.AreEqual(ex.Message, tags["otel.status_description"]); + Assert.Multiple(() => + { + Assert.That(tags["otel.status_code"], Is.EqualTo("ERROR")); + Assert.That(tags["otel.status_description"], Is.EqualTo(ex.Message)); + }); } [Test] @@ -172,13 +190,16 @@ public async Task Should_always_create_w3c_id_span() using var ambientActivity = new Activity("ambient activity"); ambientActivity.SetIdFormat(ActivityIdFormat.Hierarchical); ambientActivity.Start(); - Assert.AreEqual(ambientActivity.IdFormat, ActivityIdFormat.Hierarchical); + Assert.That(ambientActivity.IdFormat, Is.EqualTo(ActivityIdFormat.Hierarchical)); await operations.Send(new FakeRootContext(), new object(), new SendOptions()); - Assert.IsNotNull(activity); - Assert.AreEqual(ActivityIdFormat.W3C, activity.IdFormat); - Assert.AreEqual(ambientActivity.Id, activity.ParentId); - Assert.AreNotEqual(ambientActivity.TraceId, activity.TraceId); + Assert.That(activity, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(activity.IdFormat, Is.EqualTo(ActivityIdFormat.W3C)); + Assert.That(activity.ParentId, Is.EqualTo(ambientActivity.Id)); + Assert.That(activity.TraceId, Is.Not.EqualTo(ambientActivity.TraceId)); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/OpenTelemetry/TracingExtensionsTests.cs b/src/NServiceBus.Core.Tests/OpenTelemetry/TracingExtensionsTests.cs index 6b2c06ee34f..19b81ef54ea 100644 --- a/src/NServiceBus.Core.Tests/OpenTelemetry/TracingExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/OpenTelemetry/TracingExtensionsTests.cs @@ -23,7 +23,7 @@ public async Task Invoke_should_invoke_pipeline_when_activity_null() await pipeline.Invoke(new FakeRootContext(), null); - Assert.IsTrue(invokedPipeline); + Assert.That(invokedPipeline, Is.True); } [Test] @@ -35,7 +35,7 @@ public async Task Invoke_should_set_success_status_when_no_exception() await pipeline.Invoke(new FakeRootContext(), activity); - Assert.AreEqual(ActivityStatusCode.Ok, activity.Status); + Assert.That(activity.Status, Is.EqualTo(ActivityStatusCode.Ok)); } [Test] @@ -48,14 +48,17 @@ public void Invoke_should_set_error_status_and_tags_when_exception() Assert.ThrowsAsync(() => pipeline.Invoke(new FakeRootContext(), activity)); - Assert.AreEqual(ActivityStatusCode.Error, activity.Status); + Assert.That(activity.Status, Is.EqualTo(ActivityStatusCode.Error)); var tags = activity.Tags.ToImmutableDictionary(); - Assert.AreEqual("ERROR", tags["otel.status_code"]); - Assert.AreEqual(exception.Message, tags["otel.status_description"]); + Assert.Multiple(() => + { + Assert.That(tags["otel.status_code"], Is.EqualTo("ERROR")); + Assert.That(tags["otel.status_description"], Is.EqualTo(exception.Message)); + }); var errorEvent = activity.Events.Single(); - Assert.AreEqual("exception", errorEvent.Name); + Assert.That(errorEvent.Name, Is.EqualTo("exception")); } class FakePipeline : IPipeline diff --git a/src/NServiceBus.Core.Tests/Performance/TimeToBeReceived/TimeToBeReceivedAttributeTests.cs b/src/NServiceBus.Core.Tests/Performance/TimeToBeReceived/TimeToBeReceivedAttributeTests.cs index 5410494228d..250513c0cd6 100644 --- a/src/NServiceBus.Core.Tests/Performance/TimeToBeReceived/TimeToBeReceivedAttributeTests.cs +++ b/src/NServiceBus.Core.Tests/Performance/TimeToBeReceived/TimeToBeReceivedAttributeTests.cs @@ -13,8 +13,11 @@ public void Should_use_TimeToBeReceived_from_bottom_of_tree_when_initialized() typeof(InheritedClassWithAttribute) }, TimeToBeReceivedMappings.DefaultConvention, true); - Assert.True(mappings.TryGetTimeToBeReceived(typeof(InheritedClassWithAttribute), out var timeToBeReceived)); - Assert.AreEqual(TimeSpan.FromSeconds(2), timeToBeReceived); + Assert.Multiple(() => + { + Assert.That(mappings.TryGetTimeToBeReceived(typeof(InheritedClassWithAttribute), out var timeToBeReceived), Is.True); + Assert.That(timeToBeReceived, Is.EqualTo(TimeSpan.FromSeconds(2))); + }); } [Test] @@ -25,8 +28,11 @@ public void Should_use_inherited_TimeToBeReceived_when_initialized() typeof(InheritedClassWithNoAttribute) }, TimeToBeReceivedMappings.DefaultConvention, true); - Assert.True(mappings.TryGetTimeToBeReceived(typeof(InheritedClassWithNoAttribute), out var timeToBeReceived)); - Assert.AreEqual(TimeSpan.FromSeconds(1), timeToBeReceived); + Assert.Multiple(() => + { + Assert.That(mappings.TryGetTimeToBeReceived(typeof(InheritedClassWithNoAttribute), out var timeToBeReceived), Is.True); + Assert.That(timeToBeReceived, Is.EqualTo(TimeSpan.FromSeconds(1))); + }); } [Test] @@ -43,8 +49,11 @@ public void Should_use_TimeToBeReceived_from_bottom_of_tree_when_tryget() { var mappings = new TimeToBeReceivedMappings(Array.Empty(), TimeToBeReceivedMappings.DefaultConvention, true); - Assert.True(mappings.TryGetTimeToBeReceived(typeof(InheritedClassWithAttribute), out var timeToBeReceived)); - Assert.AreEqual(TimeSpan.FromSeconds(2), timeToBeReceived); + Assert.Multiple(() => + { + Assert.That(mappings.TryGetTimeToBeReceived(typeof(InheritedClassWithAttribute), out var timeToBeReceived), Is.True); + Assert.That(timeToBeReceived, Is.EqualTo(TimeSpan.FromSeconds(2))); + }); } [Test] @@ -52,8 +61,11 @@ public void Should_use_inherited_TimeToBeReceived_when_tryget() { var mappings = new TimeToBeReceivedMappings(Array.Empty(), TimeToBeReceivedMappings.DefaultConvention, true); - Assert.True(mappings.TryGetTimeToBeReceived(typeof(InheritedClassWithNoAttribute), out var timeToBeReceived)); - Assert.AreEqual(TimeSpan.FromSeconds(1), timeToBeReceived); + Assert.Multiple(() => + { + Assert.That(mappings.TryGetTimeToBeReceived(typeof(InheritedClassWithNoAttribute), out var timeToBeReceived), Is.True); + Assert.That(timeToBeReceived, Is.EqualTo(TimeSpan.FromSeconds(1))); + }); } [Test] diff --git a/src/NServiceBus.Core.Tests/Persistence/PersistenceStartupTests.cs b/src/NServiceBus.Core.Tests/Persistence/PersistenceStartupTests.cs index e4e6b3f61cc..ebf9f69f983 100644 --- a/src/NServiceBus.Core.Tests/Persistence/PersistenceStartupTests.cs +++ b/src/NServiceBus.Core.Tests/Persistence/PersistenceStartupTests.cs @@ -16,7 +16,7 @@ public void Should_return_false_when_checking_if_persistence_supports_storage_ty var supported = PersistenceStartup.HasSupportFor(settings); - Assert.IsFalse(supported); + Assert.That(supported, Is.False); } } diff --git a/src/NServiceBus.Core.Tests/Persistence/PersistenceStorageMergerTests.cs b/src/NServiceBus.Core.Tests/Persistence/PersistenceStorageMergerTests.cs index 401f16e6303..01983883b82 100644 --- a/src/NServiceBus.Core.Tests/Persistence/PersistenceStorageMergerTests.cs +++ b/src/NServiceBus.Core.Tests/Persistence/PersistenceStorageMergerTests.cs @@ -46,10 +46,13 @@ public void Should_replace_default_storages_by_overrides() var resultedEnabledPersistences = PersistenceStorageMerger.Merge(persistences, config.Settings); - Assert.That(resultedEnabledPersistences[0].SelectedStorages, Is.EquivalentTo( - new List { typeof(StorageType.Subscriptions) })); - Assert.That(resultedEnabledPersistences[1].SelectedStorages, Is.EquivalentTo( - new List { typeof(StorageType.Sagas) })); + Assert.Multiple(() => + { + Assert.That(resultedEnabledPersistences[0].SelectedStorages, Is.EquivalentTo( + new List { typeof(StorageType.Subscriptions) })); + Assert.That(resultedEnabledPersistences[1].SelectedStorages, Is.EquivalentTo( + new List { typeof(StorageType.Sagas) })); + }); } class FakePersistence2 : PersistenceDefinition @@ -84,7 +87,7 @@ public void Should_not_use_other_supported_storages() var resultedEnabledPersistences = PersistenceStorageMerger.Merge(persistences, config.Settings); - Assert.IsFalse(resultedEnabledPersistences.Any(p => p.SelectedStorages.Contains(typeof(StorageType.Subscriptions)))); + Assert.That(resultedEnabledPersistences.Any(p => p.SelectedStorages.Contains(typeof(StorageType.Subscriptions))), Is.False); } class FakePersistence : PersistenceDefinition diff --git a/src/NServiceBus.Core.Tests/Pipeline/BehaviorRegistrationsCoordinatorTests.cs b/src/NServiceBus.Core.Tests/Pipeline/BehaviorRegistrationsCoordinatorTests.cs index 372c9c581ae..905e2edbb4e 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/BehaviorRegistrationsCoordinatorTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/BehaviorRegistrationsCoordinatorTests.cs @@ -32,7 +32,7 @@ public void Registrations_Count() var model = coordinator.BuildPipelineModelFor(); - Assert.AreEqual(3, model.Count); + Assert.That(model.Count, Is.EqualTo(3)); } [Test] @@ -44,9 +44,12 @@ public void Registrations_Order() var model = coordinator.BuildPipelineModelFor().ToList(); - Assert.AreEqual("1", model[0].StepId); - Assert.AreEqual("2", model[1].StepId); - Assert.AreEqual("3", model[2].StepId); + Assert.Multiple(() => + { + Assert.That(model[0].StepId, Is.EqualTo("1")); + Assert.That(model[1].StepId, Is.EqualTo("2")); + Assert.That(model[2].StepId, Is.EqualTo("3")); + }); } [Test] @@ -61,9 +64,12 @@ public void Registrations_Replace() var model = coordinator.BuildPipelineModelFor().ToList(); - Assert.AreEqual(typeof(ReplacedBehavior).FullName, model[0].BehaviorType.FullName); - Assert.AreEqual("new", model[0].Description); - Assert.AreEqual("2", model[1].Description); + Assert.Multiple(() => + { + Assert.That(model[0].BehaviorType.FullName, Is.EqualTo(typeof(ReplacedBehavior).FullName)); + Assert.That(model[0].Description, Is.EqualTo("new")); + Assert.That(model[1].Description, Is.EqualTo("2")); + }); } [Test] @@ -73,9 +79,12 @@ public void Registrations_AddOrReplace_WhenDoesNotExist() var model = coordinator.BuildPipelineModelFor().ToList(); - Assert.AreEqual(1, model.Count); - Assert.AreEqual(typeof(ReplacedBehavior).FullName, model[0].BehaviorType.FullName); - Assert.AreEqual("new", model[0].Description); + Assert.That(model.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(model[0].BehaviorType.FullName, Is.EqualTo(typeof(ReplacedBehavior).FullName)); + Assert.That(model[0].Description, Is.EqualTo("new")); + }); } [Test] @@ -87,9 +96,12 @@ public void Registrations_AddOrReplace_WhenExists() var model = coordinator.BuildPipelineModelFor().ToList(); - Assert.AreEqual(1, model.Count); - Assert.AreEqual(typeof(ReplacedBehavior).FullName, model[0].BehaviorType.FullName); - Assert.AreEqual("new", model[0].Description); + Assert.That(model.Count, Is.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(model[0].BehaviorType.FullName, Is.EqualTo(typeof(ReplacedBehavior).FullName)); + Assert.That(model[0].Description, Is.EqualTo("new")); + }); } [Test] @@ -105,12 +117,15 @@ public void Registrations_Order_with_befores_and_afters() var model = coordinator.BuildPipelineModelFor().ToList(); - Assert.AreEqual("1", model[0].StepId); - Assert.AreEqual("1.5", model[1].StepId); - Assert.AreEqual("2", model[2].StepId); - Assert.AreEqual("2.5", model[3].StepId); - Assert.AreEqual("3", model[4].StepId); - Assert.AreEqual("3.5", model[5].StepId); + Assert.Multiple(() => + { + Assert.That(model[0].StepId, Is.EqualTo("1")); + Assert.That(model[1].StepId, Is.EqualTo("1.5")); + Assert.That(model[2].StepId, Is.EqualTo("2")); + Assert.That(model[3].StepId, Is.EqualTo("2.5")); + Assert.That(model[4].StepId, Is.EqualTo("3")); + Assert.That(model[5].StepId, Is.EqualTo("3.5")); + }); } [Test] @@ -125,11 +140,14 @@ public void Registrations_Order_with_befores_only() var model = coordinator.BuildPipelineModelFor().ToList(); - Assert.AreEqual("1", model[0].StepId); - Assert.AreEqual("1.5", model[1].StepId); - Assert.AreEqual("2", model[2].StepId); - Assert.AreEqual("2.5", model[3].StepId); - Assert.AreEqual("3", model[4].StepId); + Assert.Multiple(() => + { + Assert.That(model[0].StepId, Is.EqualTo("1")); + Assert.That(model[1].StepId, Is.EqualTo("1.5")); + Assert.That(model[2].StepId, Is.EqualTo("2")); + Assert.That(model[3].StepId, Is.EqualTo("2.5")); + Assert.That(model[4].StepId, Is.EqualTo("3")); + }); } [Test] @@ -145,12 +163,15 @@ public void Registrations_Order_with_multi_afters() var model = coordinator.BuildPipelineModelFor().ToList(); - Assert.AreEqual("1", model[0].StepId); - Assert.AreEqual("1.5", model[1].StepId); - Assert.AreEqual("2", model[2].StepId); - Assert.AreEqual("2.5", model[3].StepId); - Assert.AreEqual("3", model[4].StepId); - Assert.AreEqual("3.5", model[5].StepId); + Assert.Multiple(() => + { + Assert.That(model[0].StepId, Is.EqualTo("1")); + Assert.That(model[1].StepId, Is.EqualTo("1.5")); + Assert.That(model[2].StepId, Is.EqualTo("2")); + Assert.That(model[3].StepId, Is.EqualTo("2.5")); + Assert.That(model[4].StepId, Is.EqualTo("3")); + Assert.That(model[5].StepId, Is.EqualTo("3.5")); + }); } [Test] @@ -166,12 +187,15 @@ public void Registrations_Order_with_afters_only() var model = coordinator.BuildPipelineModelFor().ToList(); - Assert.AreEqual("1", model[0].StepId); - Assert.AreEqual("1.1", model[1].StepId); - Assert.AreEqual("1.5", model[2].StepId); - Assert.AreEqual("1.6", model[3].StepId); - Assert.AreEqual("2", model[4].StepId); - Assert.AreEqual("3", model[5].StepId); + Assert.Multiple(() => + { + Assert.That(model[0].StepId, Is.EqualTo("1")); + Assert.That(model[1].StepId, Is.EqualTo("1.1")); + Assert.That(model[2].StepId, Is.EqualTo("1.5")); + Assert.That(model[3].StepId, Is.EqualTo("1.6")); + Assert.That(model[4].StepId, Is.EqualTo("2")); + Assert.That(model[5].StepId, Is.EqualTo("3")); + }); } [Test] diff --git a/src/NServiceBus.Core.Tests/Pipeline/EnsureNativeBehaviors.cs b/src/NServiceBus.Core.Tests/Pipeline/EnsureNativeBehaviors.cs index 91e9fdf9509..eeed94e346d 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/EnsureNativeBehaviors.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/EnsureNativeBehaviors.cs @@ -23,7 +23,7 @@ public static void CoreBehaviorsMustNotUseAbstractClasses() Console.Error.WriteLine($"Violators of {nameof(CoreBehaviorsMustNotUseAbstractClasses)}:{Environment.NewLine}{string.Join(Environment.NewLine, violators)}"); - Assert.IsEmpty(violators, $"For performance reasons, built-in behaviors are not allowed to inherit from abstract behavior classes. Implement IBehavior directly, using the same context type for both TIn and TOut."); + Assert.That(violators, Is.Empty, $"For performance reasons, built-in behaviors are not allowed to inherit from abstract behavior classes. Implement IBehavior directly, using the same context type for both TIn and TOut."); } static bool UsesAbstractClass(Type type) diff --git a/src/NServiceBus.Core.Tests/Pipeline/HandlerTransactionScopeWrapperBehaviorTests.cs b/src/NServiceBus.Core.Tests/Pipeline/HandlerTransactionScopeWrapperBehaviorTests.cs index b54932b6af7..018100a274e 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/HandlerTransactionScopeWrapperBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/HandlerTransactionScopeWrapperBehaviorTests.cs @@ -29,7 +29,7 @@ public Task ShouldWrapInnerBehaviorsIfNoAmbientExists() return behavior.Invoke(null, ctx => { - Assert.NotNull(Transaction.Current); + Assert.That(Transaction.Current, Is.Not.Null); return Task.CompletedTask; }); } diff --git a/src/NServiceBus.Core.Tests/Pipeline/HeaderOptionExtensionsTests.cs b/src/NServiceBus.Core.Tests/Pipeline/HeaderOptionExtensionsTests.cs index ff332a45cad..d767d59a392 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/HeaderOptionExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/HeaderOptionExtensionsTests.cs @@ -14,8 +14,8 @@ public void GetHeaders_Should_Return_Configured_Headers() var result = options.GetHeaders(); - Assert.AreEqual(2, result.Count); - CollectionAssert.Contains(result.Values, "custom header value 1"); - CollectionAssert.Contains(result.Values, "custom header value 2"); + Assert.That(result.Count, Is.EqualTo(2)); + Assert.That(result.Values, Has.Member("custom header value 1")); + Assert.That(result.Values, Has.Member("custom header value 2")); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Pipeline/Incoming/InvokeHandlerTerminatorTest.cs b/src/NServiceBus.Core.Tests/Pipeline/Incoming/InvokeHandlerTerminatorTest.cs index f1715defdc7..96935f4f0d8 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Incoming/InvokeHandlerTerminatorTest.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Incoming/InvokeHandlerTerminatorTest.cs @@ -25,7 +25,7 @@ public async Task When_saga_found_and_handler_is_saga_should_invoke_handler() await terminator.Invoke(behaviorContext, _ => Task.CompletedTask); - Assert.IsTrue(handlerInvoked); + Assert.That(handlerInvoked, Is.True); } [Test] @@ -41,7 +41,7 @@ public async Task When_saga_not_found_and_handler_is_saga_should_not_invoke_hand await terminator.Invoke(behaviorContext, _ => Task.CompletedTask); - Assert.IsFalse(handlerInvoked); + Assert.That(handlerInvoked, Is.False); } [Test] @@ -56,7 +56,7 @@ public async Task When_saga_not_found_and_handler_is_not_saga_should_invoke_hand await terminator.Invoke(behaviorContext, _ => Task.CompletedTask); - Assert.IsTrue(handlerInvoked); + Assert.That(handlerInvoked, Is.True); } [Test] @@ -69,7 +69,7 @@ public async Task When_no_saga_should_invoke_handler() await terminator.Invoke(behaviorContext, _ => Task.CompletedTask); - Assert.IsTrue(handlerInvoked); + Assert.That(handlerInvoked, Is.True); } [Test] @@ -81,7 +81,7 @@ public async Task Should_invoke_handler_with_current_message() await terminator.Invoke(behaviorContext, _ => Task.CompletedTask); - Assert.AreSame(behaviorContext.MessageBeingHandled, receivedMessage); + Assert.That(receivedMessage, Is.SameAs(behaviorContext.MessageBeingHandled)); } [Test] @@ -93,11 +93,14 @@ public void Should_rethrow_exception_with_additional_data() var caughtException = Assert.ThrowsAsync(async () => await terminator.Invoke(behaviorContext, _ => Task.CompletedTask)); - Assert.AreSame(thrownException, caughtException); - Assert.AreEqual("System.Object", caughtException.Data["Message type"]); - Assert.AreEqual("NServiceBus.Core.Tests.Pipeline.Incoming.InvokeHandlerTerminatorTest+FakeMessageHandler", caughtException.Data["Handler type"]); - Assert.That(DateTimeOffsetHelper.ToDateTimeOffset((string)caughtException.Data["Handler start time"]), Is.EqualTo(DateTimeOffset.UtcNow).Within(TimeSpan.FromSeconds(5))); - Assert.That(DateTimeOffsetHelper.ToDateTimeOffset((string)caughtException.Data["Handler failure time"]), Is.EqualTo(DateTimeOffset.UtcNow).Within(TimeSpan.FromSeconds(5))); + Assert.That(caughtException, Is.SameAs(thrownException)); + Assert.Multiple(() => + { + Assert.That(caughtException.Data["Message type"], Is.EqualTo("System.Object")); + Assert.That(caughtException.Data["Handler type"], Is.EqualTo("NServiceBus.Core.Tests.Pipeline.Incoming.InvokeHandlerTerminatorTest+FakeMessageHandler")); + Assert.That(DateTimeOffsetHelper.ToDateTimeOffset((string)caughtException.Data["Handler start time"]), Is.EqualTo(DateTimeOffset.UtcNow).Within(TimeSpan.FromSeconds(5))); + Assert.That(DateTimeOffsetHelper.ToDateTimeOffset((string)caughtException.Data["Handler failure time"]), Is.EqualTo(DateTimeOffset.UtcNow).Within(TimeSpan.FromSeconds(5))); + }); } [Test] diff --git a/src/NServiceBus.Core.Tests/Pipeline/Incoming/MessageTypeEnricherTest.cs b/src/NServiceBus.Core.Tests/Pipeline/Incoming/MessageTypeEnricherTest.cs index 35309447585..a3aa90adedd 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Incoming/MessageTypeEnricherTest.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Incoming/MessageTypeEnricherTest.cs @@ -14,12 +14,15 @@ public async Task When_processing_message_without_enclosed_message_type_header_i var behavior = new InferredMessageTypeEnricherBehavior(); var context = new TestableIncomingLogicalMessageContext(); - Assert.IsFalse(context.Headers.ContainsKey(Headers.EnclosedMessageTypes)); + Assert.That(context.Headers.ContainsKey(Headers.EnclosedMessageTypes), Is.False); await behavior.Invoke(context, messageContext => Task.CompletedTask); - Assert.IsTrue(context.Headers.ContainsKey(Headers.EnclosedMessageTypes)); - Assert.AreEqual(context.Headers[Headers.EnclosedMessageTypes], typeof(object).FullName); + Assert.Multiple(() => + { + Assert.That(context.Headers.ContainsKey(Headers.EnclosedMessageTypes), Is.True); + Assert.That(typeof(object).FullName, Is.EqualTo(context.Headers[Headers.EnclosedMessageTypes])); + }); } [Test] @@ -31,8 +34,11 @@ public async Task When_processing_message_with_enclosed_message_type_header_it_i await mutator.Invoke(context, messageContext => Task.CompletedTask); - Assert.IsTrue(context.Headers.ContainsKey(Headers.EnclosedMessageTypes)); - Assert.AreEqual(context.Headers[Headers.EnclosedMessageTypes], typeof(string).FullName); + Assert.Multiple(() => + { + Assert.That(context.Headers.ContainsKey(Headers.EnclosedMessageTypes), Is.True); + Assert.That(typeof(string).FullName, Is.EqualTo(context.Headers[Headers.EnclosedMessageTypes])); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Pipeline/Incoming/SerializeMessageConnectorTests.cs b/src/NServiceBus.Core.Tests/Pipeline/Incoming/SerializeMessageConnectorTests.cs index 81d8491a7fe..a79993f3eb8 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Incoming/SerializeMessageConnectorTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Incoming/SerializeMessageConnectorTests.cs @@ -32,7 +32,7 @@ public async Task Should_set_content_type_header() await behavior.Invoke(context, c => Task.CompletedTask); - Assert.AreEqual("myContentType", context.Headers[Headers.ContentType]); + Assert.That(context.Headers[Headers.ContentType], Is.EqualTo("myContentType")); } class FakeSerializer : IMessageSerializer diff --git a/src/NServiceBus.Core.Tests/Pipeline/IncomingPipelineMetricTagsTests.cs b/src/NServiceBus.Core.Tests/Pipeline/IncomingPipelineMetricTagsTests.cs index 356863fb4e4..487e673d668 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/IncomingPipelineMetricTagsTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/IncomingPipelineMetricTagsTests.cs @@ -16,7 +16,7 @@ namespace NServiceBus.Core.Tests.Pipeline.Incoming; public class IncomingPipelineMetricTagsTests { [Test] - public async Task Should_not_fail_when_handling_more_than_one_logical_message() + public void Should_not_fail_when_handling_more_than_one_logical_message() { var registry = new MessageMetadataRegistry(new Conventions().IsMessageType, true); @@ -36,13 +36,11 @@ public async Task Should_not_fail_when_handling_more_than_one_logical_message() var messageMapper = new MessageMapper(); var behavior = new DeserializeMessageConnector(new MessageDeserializerResolver(new FakeSerializer(), []), new LogicalMessageFactory(registry, messageMapper), registry, messageMapper, false); - await behavior.Invoke(context, c => + Assert.DoesNotThrowAsync(async () => await behavior.Invoke(context, c => { c.Extensions.Get().Add("Same", "Same"); return Task.CompletedTask; - }); - - Assert.That(true, Is.True); + })); } class MyMessage : IMessage { } diff --git a/src/NServiceBus.Core.Tests/Pipeline/MainPipelineExecutorTests.cs b/src/NServiceBus.Core.Tests/Pipeline/MainPipelineExecutorTests.cs index 0b05c46af5d..d3c401e42e2 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/MainPipelineExecutorTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/MainPipelineExecutorTests.cs @@ -25,7 +25,7 @@ public async Task Should_share_message_context_extension_values() messageContext.Extensions.Set("existing value", existingValue); await executor.Invoke(messageContext); - Assert.AreEqual(existingValue, receivePipeline.LastContext.Extensions.Get("existing value")); + Assert.That(receivePipeline.LastContext.Extensions.Get("existing value"), Is.EqualTo(existingValue)); } [Test] @@ -42,7 +42,7 @@ public async Task Should_use_message_context_extensions_as_context_root() await executor.Invoke(messageContext); - Assert.AreEqual(newValue, messageContext.Extensions.Get("new value")); + Assert.That(messageContext.Extensions.Get("new value"), Is.EqualTo(newValue)); } class When_activity_listener_registered @@ -70,10 +70,13 @@ public async Task Should_start_Activity_when_invoking_pipeline() await executor.Invoke(messageContext); - Assert.NotNull(receivePipeline.PipelineAcitivty); - Assert.AreEqual(ActivityNames.IncomingMessageActivityName, receivePipeline.PipelineAcitivty.OperationName); - Assert.AreEqual("process message", receivePipeline.PipelineAcitivty.DisplayName); - Assert.AreEqual(receivePipeline.PipelineAcitivty, receivePipeline.TransportReceiveContext.Extensions.Get(ActivityExtensions.IncomingActivityKey)); + Assert.That(receivePipeline.PipelineAcitivty, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(receivePipeline.PipelineAcitivty.OperationName, Is.EqualTo(ActivityNames.IncomingMessageActivityName)); + Assert.That(receivePipeline.PipelineAcitivty.DisplayName, Is.EqualTo("process message")); + Assert.That(receivePipeline.TransportReceiveContext.Extensions.Get(ActivityExtensions.IncomingActivityKey), Is.EqualTo(receivePipeline.PipelineAcitivty)); + }); } [Test] @@ -84,7 +87,7 @@ public async Task Should_set_ok_status_on_activity_when_pipeline_successful() await executor.Invoke(CreateMessageContext()); - Assert.AreEqual(ActivityStatusCode.Ok, receivePipeline.PipelineAcitivty.Status); + Assert.That(receivePipeline.PipelineAcitivty.Status, Is.EqualTo(ActivityStatusCode.Ok)); } [Test] @@ -96,7 +99,7 @@ public void Should_set_error_status_on_activity_when_pipeline_throws_exception() Assert.ThrowsAsync(async () => await executor.Invoke(CreateMessageContext())); - Assert.AreEqual(ActivityStatusCode.Error, receivePipeline.PipelineAcitivty.Status); + Assert.That(receivePipeline.PipelineAcitivty.Status, Is.EqualTo(ActivityStatusCode.Error)); } } diff --git a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/AttachSenderRelatedInfoOnMessageTests.cs b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/AttachSenderRelatedInfoOnMessageTests.cs index 3f33f92406f..ed501bdfdfa 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/AttachSenderRelatedInfoOnMessageTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/AttachSenderRelatedInfoOnMessageTests.cs @@ -19,7 +19,7 @@ public async Task Should_set_the_time_sent_headerAsync() { var message = await InvokeBehaviorAsync(); - Assert.True(message.Headers.ContainsKey(Headers.TimeSent)); + Assert.That(message.Headers.ContainsKey(Headers.TimeSent), Is.True); } [Test] @@ -32,8 +32,11 @@ public async Task Should_not_override_the_time_sent_headerAsync() {Headers.TimeSent, timeSent} }); - Assert.True(message.Headers.ContainsKey(Headers.TimeSent)); - Assert.AreEqual(timeSent, message.Headers[Headers.TimeSent]); + Assert.Multiple(() => + { + Assert.That(message.Headers.ContainsKey(Headers.TimeSent), Is.True); + Assert.That(message.Headers[Headers.TimeSent], Is.EqualTo(timeSent)); + }); } [Test] @@ -41,7 +44,7 @@ public async Task Should_set_the_nsb_version_headerAsync() { var message = await InvokeBehaviorAsync(); - Assert.True(message.Headers.ContainsKey(Headers.NServiceBusVersion)); + Assert.That(message.Headers.ContainsKey(Headers.NServiceBusVersion), Is.True); } [Test] @@ -53,8 +56,11 @@ public async Task Should_not_override_nsb_version_headerAsync() {Headers.NServiceBusVersion, nsbVersion} }); - Assert.True(message.Headers.ContainsKey(Headers.NServiceBusVersion)); - Assert.AreEqual(nsbVersion, message.Headers[Headers.NServiceBusVersion]); + Assert.Multiple(() => + { + Assert.That(message.Headers.ContainsKey(Headers.NServiceBusVersion), Is.True); + Assert.That(message.Headers[Headers.NServiceBusVersion], Is.EqualTo(nsbVersion)); + }); } [Test] @@ -65,7 +71,7 @@ public async Task Should_set_deliver_At_header_when_delay_delivery_with_setAsync DelayDeliveryWith = new DelayDeliveryWith(TimeSpan.FromSeconds(2)) }); - Assert.True(message.Headers.ContainsKey(Headers.DeliverAt)); + Assert.That(message.Headers.ContainsKey(Headers.DeliverAt), Is.True); } [Test] @@ -77,8 +83,11 @@ public async Task Should_set_deliver_at_header_when_do_not_deliver_before_is_set DoNotDeliverBefore = new DoNotDeliverBefore(doNotDeliverBefore) }); - Assert.True(message.Headers.ContainsKey(Headers.DeliverAt)); - Assert.AreEqual(DateTimeOffsetHelper.ToWireFormattedString(doNotDeliverBefore), message.Headers[Headers.DeliverAt]); + Assert.Multiple(() => + { + Assert.That(message.Headers.ContainsKey(Headers.DeliverAt), Is.True); + Assert.That(message.Headers[Headers.DeliverAt], Is.EqualTo(DateTimeOffsetHelper.ToWireFormattedString(doNotDeliverBefore))); + }); } [Test] @@ -93,8 +102,11 @@ public async Task Should_not_override_deliver_at_headerAsync() DelayDeliveryWith = new DelayDeliveryWith(TimeSpan.FromSeconds(2)) }); - Assert.True(message.Headers.ContainsKey(Headers.DeliverAt)); - Assert.AreEqual(DateTimeOffsetHelper.ToWireFormattedString(doNotDeliverBefore), message.Headers[Headers.DeliverAt]); + Assert.Multiple(() => + { + Assert.That(message.Headers.ContainsKey(Headers.DeliverAt), Is.True); + Assert.That(message.Headers[Headers.DeliverAt], Is.EqualTo(DateTimeOffsetHelper.ToWireFormattedString(doNotDeliverBefore))); + }); } static async Task InvokeBehaviorAsync(Dictionary headers = null, DispatchProperties dispatchProperties = null, CancellationToken cancellationToken = default) diff --git a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/ImmediateDispatchOptionExtensionsTests.cs b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/ImmediateDispatchOptionExtensionsTests.cs index fa10abca3b0..9b47fbc8586 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/ImmediateDispatchOptionExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/ImmediateDispatchOptionExtensionsTests.cs @@ -10,7 +10,7 @@ public void RequiresImmediateDispatch_Should_Return_False_When_No_Immediate_Disp { var options = new SendOptions(); - Assert.IsFalse(options.IsImmediateDispatchSet()); + Assert.That(options.IsImmediateDispatchSet(), Is.False); } [Test] @@ -19,6 +19,6 @@ public void RequiresImmediateDispatch_Should_Return_True_When_Immediate_Dispatch var options = new SendOptions(); options.RequireImmediateDispatch(); - Assert.IsTrue(options.IsImmediateDispatchSet()); + Assert.That(options.IsImmediateDispatchSet(), Is.True); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/MessageIdExtensionsTests.cs b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/MessageIdExtensionsTests.cs index 73e2d29ce50..f3b04bf346c 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/MessageIdExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/MessageIdExtensionsTests.cs @@ -10,7 +10,7 @@ public void GetMessageId_Should_Return_Generated_Id_When_No_Id_Specified() { var options = new SendOptions(); - Assert.IsNotEmpty(options.GetMessageId()); + Assert.That(options.GetMessageId(), Is.Not.Empty); } [Test] @@ -20,6 +20,6 @@ public void GetMessageId_Should_Return_Defined_Id() var options = new PublishOptions(); options.SetMessageId(expectedMessageID); - Assert.AreEqual(expectedMessageID, options.GetMessageId()); + Assert.That(options.GetMessageId(), Is.EqualTo(expectedMessageID)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingLogicalMessageContextTests.cs b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingLogicalMessageContextTests.cs index ec2e73d4e09..db1a96492c7 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingLogicalMessageContextTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingLogicalMessageContextTests.cs @@ -28,8 +28,11 @@ public void Updating_the_message_proxy_instance_with_a_new_property_value_should context.UpdateMessage(newMessage); - Assert.AreEqual(typeof(IMyMessage), context.Message.MessageType); - Assert.AreEqual(newMessageId, ((IMyMessage)context.Message.Instance).Id); + Assert.Multiple(() => + { + Assert.That(context.Message.MessageType, Is.EqualTo(typeof(IMyMessage))); + Assert.That(((IMyMessage)context.Message.Instance).Id, Is.EqualTo(newMessageId)); + }); } [Test] @@ -47,7 +50,7 @@ public void Updating_the_message_to_a_new_type_should_update_the_MessageType() context.UpdateMessage(differentMessage); - Assert.AreEqual(typeof(MyDifferentMessage), context.Message.MessageType); + Assert.That(context.Message.MessageType, Is.EqualTo(typeof(MyDifferentMessage))); } class MyDifferentMessage diff --git a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingPublishContextTests.cs b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingPublishContextTests.cs index c6ba7d03ed9..1ff90a93a67 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingPublishContextTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingPublishContextTests.cs @@ -18,12 +18,18 @@ public void ShouldShallowCloneContext() testee.Extensions.Set("someKey", "updatedValue"); testee.Extensions.Set("anotherKey", "anotherValue"); options.Context.TryGet("someKey", out string value); - Assert.AreEqual("someValue", value); - Assert.IsFalse(options.Context.TryGet("anotherKey", out string _)); + Assert.Multiple(() => + { + Assert.That(value, Is.EqualTo("someValue")); + Assert.That(options.Context.TryGet("anotherKey", out string _), Is.False); + }); testee.Extensions.TryGet("someKey", out string updatedValue); testee.Extensions.TryGet("anotherKey", out string anotherValue2); - Assert.AreEqual("updatedValue", updatedValue); - Assert.AreEqual("anotherValue", anotherValue2); + Assert.Multiple(() => + { + Assert.That(updatedValue, Is.EqualTo("updatedValue")); + Assert.That(anotherValue2, Is.EqualTo("anotherValue")); + }); } [Test] @@ -39,7 +45,7 @@ public void ShouldNotMergeOptionsToParentContext() var valueFound = parentContext.TryGet("someKey", out string _); - Assert.IsFalse(valueFound); + Assert.That(valueFound, Is.False); } [Test] @@ -53,7 +59,7 @@ public void ShouldExposePublishOptionsExtensionsAsOperationProperties() var publishContext = new OutgoingPublishContext(message, "message-id", [], options, parentContext); var operationProperties = publishContext.GetOperationProperties(); - Assert.AreEqual("some value", operationProperties.Get("some key")); + Assert.That(operationProperties.Get("some key"), Is.EqualTo("some value")); } [Test] @@ -70,13 +76,19 @@ public void ShouldNotLeakParentsOperationProperties() var innerContext = new OutgoingPublishContext(new OutgoingLogicalMessage(typeof(object), new object()), "message-id", [], innerOptions, parentContext); var innerOperationProperties = innerContext.GetOperationProperties(); - Assert.AreEqual("inner value", innerOperationProperties.Get("inner key")); - Assert.AreEqual("inner shared value", innerOperationProperties.Get("shared key")); - Assert.IsFalse(innerOperationProperties.TryGet("outer key", out string _)); + Assert.Multiple(() => + { + Assert.That(innerOperationProperties.Get("inner key"), Is.EqualTo("inner value")); + Assert.That(innerOperationProperties.Get("shared key"), Is.EqualTo("inner shared value")); + Assert.That(innerOperationProperties.TryGet("outer key", out string _), Is.False); + }); var outerOperationProperties = parentContext.GetOperationProperties(); - Assert.AreEqual("outer value", outerOperationProperties.Get("outer key")); - Assert.AreEqual("outer shared value", outerOperationProperties.Get("shared key")); - Assert.IsFalse(outerOperationProperties.TryGet("inner key", out string _)); + Assert.Multiple(() => + { + Assert.That(outerOperationProperties.Get("outer key"), Is.EqualTo("outer value")); + Assert.That(outerOperationProperties.Get("shared key"), Is.EqualTo("outer shared value")); + Assert.That(outerOperationProperties.TryGet("inner key", out string _), Is.False); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingReplyContextTests.cs b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingReplyContextTests.cs index 5d834b84c97..741894ea7d5 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingReplyContextTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingReplyContextTests.cs @@ -19,12 +19,18 @@ public void ShouldShallowCloneContext() testee.Extensions.Set("anotherKey", "anotherValue"); options.Context.TryGet("someKey", out string value); - Assert.AreEqual("someValue", value); - Assert.IsFalse(options.Context.TryGet("anotherKey", out string _)); + Assert.Multiple(() => + { + Assert.That(value, Is.EqualTo("someValue")); + Assert.That(options.Context.TryGet("anotherKey", out string _), Is.False); + }); testee.Extensions.TryGet("someKey", out string updatedValue); testee.Extensions.TryGet("anotherKey", out string anotherValue2); - Assert.AreEqual("updatedValue", updatedValue); - Assert.AreEqual("anotherValue", anotherValue2); + Assert.Multiple(() => + { + Assert.That(updatedValue, Is.EqualTo("updatedValue")); + Assert.That(anotherValue2, Is.EqualTo("anotherValue")); + }); } [Test] @@ -40,7 +46,7 @@ public void ShouldNotMergeOptionsToParentContext() var valueFound = parentContext.TryGet("someKey", out string _); - Assert.IsFalse(valueFound); + Assert.That(valueFound, Is.False); } [Test] @@ -54,7 +60,7 @@ public void ShouldExposeSendOptionsExtensionsAsOperationProperties() var context = new OutgoingReplyContext(message, "message-id", [], options, parentContext); var operationProperties = context.GetOperationProperties(); - Assert.AreEqual("some value", operationProperties.Get("some key")); + Assert.That(operationProperties.Get("some key"), Is.EqualTo("some value")); } [Test] @@ -71,13 +77,19 @@ public void ShouldNotLeakParentsOperationProperties() var innerContext = new OutgoingReplyContext(new OutgoingLogicalMessage(typeof(object), new object()), "message-id", [], innerOptions, parentContext); var innerOperationProperties = innerContext.GetOperationProperties(); - Assert.AreEqual("inner value", innerOperationProperties.Get("inner key")); - Assert.AreEqual("inner shared value", innerOperationProperties.Get("shared key")); - Assert.IsFalse(innerOperationProperties.TryGet("outer key", out string _)); + Assert.Multiple(() => + { + Assert.That(innerOperationProperties.Get("inner key"), Is.EqualTo("inner value")); + Assert.That(innerOperationProperties.Get("shared key"), Is.EqualTo("inner shared value")); + Assert.That(innerOperationProperties.TryGet("outer key", out string _), Is.False); + }); var outerOperationProperties = parentContext.GetOperationProperties(); - Assert.AreEqual("outer value", outerOperationProperties.Get("outer key")); - Assert.AreEqual("outer shared value", outerOperationProperties.Get("shared key")); - Assert.IsFalse(outerOperationProperties.TryGet("inner key", out string _)); + Assert.Multiple(() => + { + Assert.That(outerOperationProperties.Get("outer key"), Is.EqualTo("outer value")); + Assert.That(outerOperationProperties.Get("shared key"), Is.EqualTo("outer shared value")); + Assert.That(outerOperationProperties.TryGet("inner key", out string _), Is.False); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingSendContextTests.cs b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingSendContextTests.cs index 55392ea29f5..01093664f79 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingSendContextTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/Outgoing/OutgoingSendContextTests.cs @@ -18,12 +18,18 @@ public void ShouldShallowCloneContext() testee.Extensions.Set("someKey", "updatedValue"); testee.Extensions.Set("anotherKey", "anotherValue"); options.Context.TryGet("someKey", out string value); - Assert.AreEqual("someValue", value); - Assert.IsFalse(options.Context.TryGet("anotherKey", out string _)); + Assert.Multiple(() => + { + Assert.That(value, Is.EqualTo("someValue")); + Assert.That(options.Context.TryGet("anotherKey", out string _), Is.False); + }); testee.Extensions.TryGet("someKey", out string updatedValue); testee.Extensions.TryGet("anotherKey", out string anotherValue2); - Assert.AreEqual("updatedValue", updatedValue); - Assert.AreEqual("anotherValue", anotherValue2); + Assert.Multiple(() => + { + Assert.That(updatedValue, Is.EqualTo("updatedValue")); + Assert.That(anotherValue2, Is.EqualTo("anotherValue")); + }); } [Test] @@ -39,7 +45,7 @@ public void ShouldNotMergeOptionsToParentContext() var valueFound = parentContext.TryGet("someKey", out string _); - Assert.IsFalse(valueFound); + Assert.That(valueFound, Is.False); } [Test] @@ -53,7 +59,7 @@ public void ShouldExposeSendOptionsExtensionsAsOperationProperties() var context = new OutgoingSendContext(message, "message-id", [], options, parentContext); var operationProperties = context.GetOperationProperties(); - Assert.AreEqual("some value", operationProperties.Get("some key")); + Assert.That(operationProperties.Get("some key"), Is.EqualTo("some value")); } [Test] @@ -70,13 +76,19 @@ public void ShouldNotLeakParentsOperationProperties() var innerContext = new OutgoingSendContext(new OutgoingLogicalMessage(typeof(object), new object()), "message-id", [], innerOptions, parentContext); var innerOperationProperties = innerContext.GetOperationProperties(); - Assert.AreEqual("inner value", innerOperationProperties.Get("inner key")); - Assert.AreEqual("inner shared value", innerOperationProperties.Get("shared key")); - Assert.IsFalse(innerOperationProperties.TryGet("outer key", out string _)); + Assert.Multiple(() => + { + Assert.That(innerOperationProperties.Get("inner key"), Is.EqualTo("inner value")); + Assert.That(innerOperationProperties.Get("shared key"), Is.EqualTo("inner shared value")); + Assert.That(innerOperationProperties.TryGet("outer key", out string _), Is.False); + }); var outerOperationProperties = parentContext.GetOperationProperties(); - Assert.AreEqual("outer value", outerOperationProperties.Get("outer key")); - Assert.AreEqual("outer shared value", outerOperationProperties.Get("shared key")); - Assert.IsFalse(outerOperationProperties.TryGet("inner key", out string _)); + Assert.Multiple(() => + { + Assert.That(outerOperationProperties.Get("outer key"), Is.EqualTo("outer value")); + Assert.That(outerOperationProperties.Get("shared key"), Is.EqualTo("outer shared value")); + Assert.That(outerOperationProperties.TryGet("inner key", out string _), Is.False); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Pipeline/PipelineModelBuilderTests.cs b/src/NServiceBus.Core.Tests/Pipeline/PipelineModelBuilderTests.cs index b3bbc84a0fd..e048540180a 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/PipelineModelBuilderTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/PipelineModelBuilderTests.cs @@ -19,7 +19,7 @@ public void ShouldDetectConflictingStepRegistrations() var ex = Assert.Throws(() => builder.Build()); - Assert.AreEqual("Step registration with id 'Root1' is already registered for 'NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+RootBehavior'.", ex.Message); + Assert.That(ex.Message, Is.EqualTo("Step registration with id 'Root1' is already registered for 'NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+RootBehavior'.")); } [Test] @@ -32,7 +32,7 @@ public void ShouldOnlyAllowReplacementOfExistingRegistrations() var ex = Assert.Throws(() => builder.Build()); - Assert.AreEqual("Multiple replacements of the same pipeline behaviour is not supported. Make sure that you only register a single replacement for 'DoesNotExist'.", ex.Message); + Assert.That(ex.Message, Is.EqualTo("Multiple replacements of the same pipeline behaviour is not supported. Make sure that you only register a single replacement for 'DoesNotExist'.")); } [Test] @@ -77,7 +77,7 @@ public void ShouldDetectMissingBehaviorForRootContext() var ex = Assert.Throws(() => builder.Build()); - Assert.AreEqual("Can't find any behaviors/connectors for the root context (NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+IParentContext)", ex.Message); + Assert.That(ex.Message, Is.EqualTo("Can't find any behaviors/connectors for the root context (NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+IParentContext)")); } [Test] @@ -91,7 +91,7 @@ public void ShouldDetectConflictingStageConnectors() var ex = Assert.Throws(() => builder.Build()); - Assert.AreEqual("Multiple stage connectors found for stage 'NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+IParentContext'. Remove one of: 'NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+ParentContextToChildContextConnector', 'NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+ParentContextToChildContextNotInheritedFromParentContextConnector'", ex.Message); + Assert.That(ex.Message, Is.EqualTo("Multiple stage connectors found for stage 'NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+IParentContext'. Remove one of: 'NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+ParentContextToChildContextConnector', 'NServiceBus.Core.Tests.Pipeline.PipelineModelBuilderTests+ParentContextToChildContextNotInheritedFromParentContextConnector'")); } [Test] @@ -109,7 +109,7 @@ public void ShouldDetectNonExistingInsertAfterRegistrations() var ex = Assert.Throws(() => builder.Build()); - Assert.AreEqual("Registration 'DoesNotExist' specified in the insertafter of the 'AnotherBehaviorOfParentContext' step does not exist. Current StepIds: 'SomeBehaviorOfParentContext', 'AnotherBehaviorOfParentContext'", ex.Message); + Assert.That(ex.Message, Is.EqualTo("Registration 'DoesNotExist' specified in the insertafter of the 'AnotherBehaviorOfParentContext' step does not exist. Current StepIds: 'SomeBehaviorOfParentContext', 'AnotherBehaviorOfParentContext'")); } [Test] @@ -127,7 +127,7 @@ public void ShouldDetectNonExistingInsertBeforeRegistrations() var ex = Assert.Throws(() => builder.Build()); - Assert.AreEqual("Registration 'DoesNotExist' specified in the insertbefore of the 'AnotherBehaviorOfParentContext' step does not exist. Current StepIds: 'SomeBehaviorOfParentContext', 'AnotherBehaviorOfParentContext'", ex.Message); + Assert.That(ex.Message, Is.EqualTo("Registration 'DoesNotExist' specified in the insertbefore of the 'AnotherBehaviorOfParentContext' step does not exist. Current StepIds: 'SomeBehaviorOfParentContext', 'AnotherBehaviorOfParentContext'")); } [Test] @@ -141,7 +141,7 @@ public void ShouldDetectRegistrationsWithContextsReachableFromTheRootContext() var model = builder.Build(); - Assert.AreEqual(3, model.Count); + Assert.That(model.Count, Is.EqualTo(3)); } [Test] @@ -155,7 +155,7 @@ public void ShouldDetectRegistrationsWithContextsNotReachableFromTheRootContext( var model = builder.Build(); - Assert.AreEqual(2, model.Count); + Assert.That(model.Count, Is.EqualTo(2)); } [Test] @@ -170,7 +170,7 @@ public void ShouldHandleTheTerminator() var model = builder.Build(); - Assert.AreEqual(3, model.Count); + Assert.That(model.Count, Is.EqualTo(3)); } class ConfigurePipelineModelBuilder diff --git a/src/NServiceBus.Core.Tests/Pipeline/RegisterStepTests.cs b/src/NServiceBus.Core.Tests/Pipeline/RegisterStepTests.cs index 2ac2bf68396..5094e57c052 100644 --- a/src/NServiceBus.Core.Tests/Pipeline/RegisterStepTests.cs +++ b/src/NServiceBus.Core.Tests/Pipeline/RegisterStepTests.cs @@ -25,7 +25,7 @@ public void Replace_ShouldReplaceBehaviorType() registerStep.Replace(replacement); - Assert.AreEqual(typeof(BehaviorB), registerStep.BehaviorType); + Assert.That(registerStep.BehaviorType, Is.EqualTo(typeof(BehaviorB))); } [Test] @@ -37,7 +37,7 @@ public void Replace_WhenReplacementContainsNoDescription_ShouldKeepOriginalDescr registerStep.Replace(replacement); - Assert.AreEqual(originalDescription, registerStep.Description); + Assert.That(registerStep.Description, Is.EqualTo(originalDescription)); } [Test] @@ -49,7 +49,7 @@ public void Replace_WhenReplacementContainsEmptyDescription_ShouldKeepOriginalDe registerStep.Replace(replacement); - Assert.AreEqual(originalDescription, registerStep.Description); + Assert.That(registerStep.Description, Is.EqualTo(originalDescription)); } [Test] @@ -61,7 +61,7 @@ public void Replace_WhenReplacementContainsDescription_ShouldReplaceDescription( registerStep.Replace(replacement); - Assert.AreEqual(replacementDescription, registerStep.Description); + Assert.That(registerStep.Description, Is.EqualTo(replacementDescription)); } [Test] @@ -81,8 +81,11 @@ public void Replace_WhenReplacementProvidesNoFactory_ShouldBuildReplacementFromB registerStep.Replace(replacement); var behavior = registerStep.CreateBehavior(builder); - Assert.IsFalse(originalBehaviorFactoryCalled); - Assert.IsInstanceOf(behavior); + Assert.Multiple(() => + { + Assert.That(originalBehaviorFactoryCalled, Is.False); + Assert.That(behavior, Is.InstanceOf()); + }); } [Test] @@ -102,8 +105,11 @@ public void Replace_WhenReplacementProvidedFactory_ShouldBuildReplacementFromFac registerStep.Replace(replacement); var behavior = registerStep.CreateBehavior(builder); - Assert.IsTrue(replacementBehaviorFactoryCalled); - Assert.IsInstanceOf(behavior); + Assert.Multiple(() => + { + Assert.That(replacementBehaviorFactoryCalled, Is.True); + Assert.That(behavior, Is.InstanceOf()); + }); } class BehaviorA : IBehavior diff --git a/src/NServiceBus.Core.Tests/Recoverability/DefaultRecoverabilityPolicyTests.cs b/src/NServiceBus.Core.Tests/Recoverability/DefaultRecoverabilityPolicyTests.cs index 66739c35d86..98fe151cf5e 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/DefaultRecoverabilityPolicyTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/DefaultRecoverabilityPolicyTests.cs @@ -17,7 +17,7 @@ public void When_failure_is_assignable_to_custom_exception_should_move_to_error( var recoverabilityAction = policy(errorContext); - Assert.IsInstanceOf(recoverabilityAction, "Should move custom exception directly to error."); + Assert.That(recoverabilityAction, Is.InstanceOf(), "Should move custom exception directly to error."); } class MyBaseCustomException : Exception @@ -36,7 +36,7 @@ public void When_max_immediate_retries_have_not_been_reached_should_return_immed var recoverabilityAction = policy(errorContext); - Assert.IsInstanceOf(recoverabilityAction, "Should have one immediate retry left. It is second delivery attempt and we configured immediate reties to 2."); + Assert.That(recoverabilityAction, Is.InstanceOf(), "Should have one immediate retry left. It is second delivery attempt and we configured immediate reties to 2."); } [Test] @@ -47,7 +47,7 @@ public void When_max_immediate_retries_exceeded_should_return_delayed_retry() var recoverabilityAction = policy(errorContext); - Assert.IsInstanceOf(recoverabilityAction, "When max number of immediate retries exceeded should return DelayedRetry."); + Assert.That(recoverabilityAction, Is.InstanceOf(), "When max number of immediate retries exceeded should return DelayedRetry."); } [Test] @@ -58,7 +58,7 @@ public void When_max_immediate_retries_exceeded_but_delayed_retry_disabled_retur var recoverabilityAction = policy(errorContext); - Assert.IsInstanceOf(recoverabilityAction, "When max number of immediate retries exceeded and delayed retry disabled should return MoveToErrors."); + Assert.That(recoverabilityAction, Is.InstanceOf(), "When max number of immediate retries exceeded and delayed retry disabled should return MoveToErrors."); } [Test] @@ -71,8 +71,11 @@ public void When_immediate_retries_turned_off_and_delayed_retry_policy_returns_d var recoverabilityAction = policy(errorContext); var delayedRetryAction = recoverabilityAction as DelayedRetry; - Assert.IsInstanceOf(recoverabilityAction, "When immediate retries turned off and delayed retries left, recoverability policy should return DelayedRetry"); - Assert.AreEqual(deliveryDelay, delayedRetryAction.Delay); + Assert.Multiple(() => + { + Assert.That(recoverabilityAction, Is.InstanceOf(), "When immediate retries turned off and delayed retries left, recoverability policy should return DelayedRetry"); + Assert.That(delayedRetryAction.Delay, Is.EqualTo(deliveryDelay)); + }); } [Test] @@ -83,7 +86,7 @@ public void When_immediate_retries_turned_off_and_delayed_retries_turned_off_sho var recoverabilityAction = policy(errorContext); - Assert.IsInstanceOf(recoverabilityAction, "When Immediate Retries turned off and Delayed Retry turned off should return MoveToErrors"); + Assert.That(recoverabilityAction, Is.InstanceOf(), "When Immediate Retries turned off and Delayed Retry turned off should return MoveToErrors"); } [Test] @@ -94,7 +97,7 @@ public void When_immediate_retries_turned_off_and_delayed_retry_policy_returns_n var recoverabilityAction = policy(errorContext); - Assert.IsInstanceOf(recoverabilityAction, "When Immediate Retries turned off and Delayed Retries policy returns no delay should return MoveToErrors"); + Assert.That(recoverabilityAction, Is.InstanceOf(), "When Immediate Retries turned off and Delayed Retries policy returns no delay should return MoveToErrors"); } [Test] @@ -105,7 +108,7 @@ public void When_immediate_retries_turned_off_and_delayed_retry_not_available_sh var recoverabilityAction = policy(errorContext); - Assert.IsInstanceOf(recoverabilityAction, "When immediate retries turned off and delayed retries disabled should return MoveToErrors"); + Assert.That(recoverabilityAction, Is.InstanceOf(), "When immediate retries turned off and delayed retries disabled should return MoveToErrors"); } [Test] @@ -116,7 +119,7 @@ public void When_delayed_retry_counter_header_exists_recoverability_policy_shoul var recoverabilityAction = policy(errorContext); - Assert.IsInstanceOf(recoverabilityAction, "When Delayed Retries counter in headers reaches max delayed retries, policy should return MoveToErrors"); + Assert.That(recoverabilityAction, Is.InstanceOf(), "When Delayed Retries counter in headers reaches max delayed retries, policy should return MoveToErrors"); } [Test] @@ -134,9 +137,12 @@ public void ShouldRetryTheSpecifiedTimesWithIncreasedDelay() errorContext = CreateErrorContext(retryNumber: 2); var result3 = policy(errorContext); - Assert.AreEqual(baseDelay, result1.Delay); - Assert.AreEqual(TimeSpan.FromSeconds(20), result2.Delay); - Assert.IsInstanceOf(result3); + Assert.Multiple(() => + { + Assert.That(result1.Delay, Is.EqualTo(baseDelay)); + Assert.That(result2.Delay, Is.EqualTo(TimeSpan.FromSeconds(20))); + Assert.That(result3, Is.InstanceOf()); + }); } [Test] @@ -157,7 +163,7 @@ public void ShouldCapTheRetryMaxTimeTo24Hours() var result = policy(errorContext); - Assert.IsInstanceOf(result); + Assert.That(result, Is.InstanceOf()); } static ErrorContext CreateErrorContext(int numberOfDeliveryAttempts = 1, int? retryNumber = null, Dictionary headers = null, Exception exception = null) => diff --git a/src/NServiceBus.Core.Tests/Recoverability/DelayedRetryRecoverabilityActionTests.cs b/src/NServiceBus.Core.Tests/Recoverability/DelayedRetryRecoverabilityActionTests.cs index ff186993663..40be2a02638 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/DelayedRetryRecoverabilityActionTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/DelayedRetryRecoverabilityActionTests.cs @@ -23,9 +23,12 @@ public void When_delay_message_retry() var routingStrategy = routingContext.RoutingStrategies.Single() as UnicastRoutingStrategy; - Assert.AreEqual(recoverabilityContext.ReceiveAddress, (routingStrategy.Apply([]) as UnicastAddressTag).Destination); - Assert.AreEqual(delay, routingContext.Extensions.Get().DelayDeliveryWith.Delay); - Assert.AreEqual(ErrorHandleResult.Handled, delayedRetryAction.ErrorHandleResult); + Assert.Multiple(() => + { + Assert.That((routingStrategy.Apply([]) as UnicastAddressTag).Destination, Is.EqualTo(recoverabilityContext.ReceiveAddress)); + Assert.That(routingContext.Extensions.Get().DelayDeliveryWith.Delay, Is.EqualTo(delay)); + Assert.That(delayedRetryAction.ErrorHandleResult, Is.EqualTo(ErrorHandleResult.Handled)); + }); } [Test] @@ -47,14 +50,20 @@ public void Should_update_retry_headers_when_present() var outgoingMessageHeaders = routingContexts.Single().Message.Headers; - Assert.AreEqual("3", outgoingMessageHeaders[Headers.DelayedRetries]); - Assert.AreEqual(delayedDeliveriesPerformed.ToString(), incomingMessage.Headers[Headers.DelayedRetries]); + Assert.Multiple(() => + { + Assert.That(outgoingMessageHeaders[Headers.DelayedRetries], Is.EqualTo("3")); + Assert.That(incomingMessage.Headers[Headers.DelayedRetries], Is.EqualTo(delayedDeliveriesPerformed.ToString())); + }); var utcDateTime = DateTimeOffsetHelper.ToDateTimeOffset(outgoingMessageHeaders[Headers.DelayedRetriesTimestamp]); // the serialization removes precision which may lead to now being greater than the deserialized header value var adjustedNow = DateTimeOffsetHelper.ToDateTimeOffset(DateTimeOffsetHelper.ToWireFormattedString(now)); - Assert.That(utcDateTime, Is.GreaterThanOrEqualTo(adjustedNow)); - Assert.AreEqual(originalHeadersTimestamp, incomingMessage.Headers[Headers.DelayedRetriesTimestamp]); + Assert.Multiple(() => + { + Assert.That(utcDateTime, Is.GreaterThanOrEqualTo(adjustedNow)); + Assert.That(incomingMessage.Headers[Headers.DelayedRetriesTimestamp], Is.EqualTo(originalHeadersTimestamp)); + }); } [Test] @@ -67,10 +76,13 @@ public void Should_add_retry_headers_when_not_present() var outgoingMessageHeaders = routingContexts.Single().Message.Headers; - Assert.AreEqual("1", outgoingMessageHeaders[Headers.DelayedRetries]); - Assert.IsFalse(recoverabilityContext.FailedMessage.Headers.ContainsKey(Headers.DelayedRetries)); - Assert.IsTrue(outgoingMessageHeaders.ContainsKey(Headers.DelayedRetriesTimestamp)); - Assert.IsFalse(recoverabilityContext.FailedMessage.Headers.ContainsKey(Headers.DelayedRetriesTimestamp)); + Assert.Multiple(() => + { + Assert.That(outgoingMessageHeaders[Headers.DelayedRetries], Is.EqualTo("1")); + Assert.That(recoverabilityContext.FailedMessage.Headers.ContainsKey(Headers.DelayedRetries), Is.False); + Assert.That(outgoingMessageHeaders.ContainsKey(Headers.DelayedRetriesTimestamp), Is.True); + Assert.That(recoverabilityContext.FailedMessage.Headers.ContainsKey(Headers.DelayedRetriesTimestamp), Is.False); + }); } static TestableRecoverabilityContext CreateRecoverabilityContext(Dictionary headers = null, int delayedDeliveriesPerformed = 0) diff --git a/src/NServiceBus.Core.Tests/Recoverability/DiscardRecoverabilityActionTests.cs b/src/NServiceBus.Core.Tests/Recoverability/DiscardRecoverabilityActionTests.cs index a2cb8bce97b..7ab2709d8bc 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/DiscardRecoverabilityActionTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/DiscardRecoverabilityActionTests.cs @@ -15,7 +15,7 @@ public void Discard_action_should_discard_message() var routingContexts = discardAction.GetRoutingContexts(actionContext); - CollectionAssert.IsEmpty(routingContexts); - Assert.AreEqual(discardAction.ErrorHandleResult, ErrorHandleResult.Handled); + Assert.That(routingContexts, Is.Empty); + Assert.That(discardAction.ErrorHandleResult, Is.EqualTo(ErrorHandleResult.Handled)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Recoverability/ErrorContextTests.cs b/src/NServiceBus.Core.Tests/Recoverability/ErrorContextTests.cs index 8e2e1541601..ece0664acf5 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/ErrorContextTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/ErrorContextTests.cs @@ -15,6 +15,6 @@ public void Can_pass_additional_information_via_context_bag() contextBag.Set("MyKey", "MyValue"); var context = new ErrorContext(new Exception(), [], "ID", Array.Empty(), new TransportTransaction(), 0, "my-queue", contextBag); - Assert.AreEqual("MyValue", context.Extensions.Get("MyKey")); + Assert.That(context.Extensions.Get("MyKey"), Is.EqualTo("MyValue")); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Recoverability/FaultMetadataExtractorTests.cs b/src/NServiceBus.Core.Tests/Recoverability/FaultMetadataExtractorTests.cs index e9f7f84ea16..6122fd2735c 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/FaultMetadataExtractorTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/FaultMetadataExtractorTests.cs @@ -20,14 +20,17 @@ public void VerifyExceptionHeadersAreSet() var metadata = extractor.Extract(CreateErrorContext(exception)); - Assert.AreEqual("System.AggregateException", metadata["NServiceBus.ExceptionInfo.ExceptionType"]); - Assert.AreEqual(exception.ToString(), metadata["NServiceBus.ExceptionInfo.StackTrace"]); - Assert.IsTrue(metadata.ContainsKey("NServiceBus.TimeOfFailure")); - - Assert.AreEqual("System.Exception", metadata["NServiceBus.ExceptionInfo.InnerExceptionType"]); - Assert.AreEqual("A fake help link", metadata["NServiceBus.ExceptionInfo.HelpLink"]); - Assert.AreEqual("NServiceBus.Core.Tests", metadata["NServiceBus.ExceptionInfo.Source"]); - Assert.AreEqual("my-address", metadata[FaultsHeaderKeys.FailedQ]); + Assert.Multiple(() => + { + Assert.That(metadata["NServiceBus.ExceptionInfo.ExceptionType"], Is.EqualTo("System.AggregateException")); + Assert.That(metadata["NServiceBus.ExceptionInfo.StackTrace"], Is.EqualTo(exception.ToString())); + Assert.That(metadata.ContainsKey("NServiceBus.TimeOfFailure"), Is.True); + + Assert.That(metadata["NServiceBus.ExceptionInfo.InnerExceptionType"], Is.EqualTo("System.Exception")); + Assert.That(metadata["NServiceBus.ExceptionInfo.HelpLink"], Is.EqualTo("A fake help link")); + Assert.That(metadata["NServiceBus.ExceptionInfo.Source"], Is.EqualTo("NServiceBus.Core.Tests")); + Assert.That(metadata[FaultsHeaderKeys.FailedQ], Is.EqualTo("my-address")); + }); } [Test] @@ -38,7 +41,7 @@ public void ExceptionMessageIsTruncated() var metadata = extractor.Extract(CreateErrorContext(exception)); - Assert.AreEqual((int)Math.Pow(2, 14), metadata["NServiceBus.ExceptionInfo.Message"].Length); + Assert.That(metadata["NServiceBus.ExceptionInfo.Message"], Has.Length.EqualTo((int)Math.Pow(2, 14))); } [Test] @@ -48,7 +51,7 @@ public void ShouldApplyStaticMetadata() var metadata = extractor.Extract(CreateErrorContext()); - Assert.AreEqual("some value", metadata["static-key"]); + Assert.That(metadata["static-key"], Is.EqualTo("some value")); } [Test] @@ -61,7 +64,7 @@ public void ShouldApplyCustomizations() var metadata = extractor.Extract(CreateErrorContext()); - Assert.AreEqual("some other value", metadata["static-key"]); + Assert.That(metadata["static-key"], Is.EqualTo("some other value")); } static ErrorContext CreateErrorContext(Exception exception = null) => new(exception ?? GetAnException(), [], "some-id", Array.Empty(), new TransportTransaction(), 0, "my-address", new ContextBag()); diff --git a/src/NServiceBus.Core.Tests/Recoverability/MoveToErrorsExecutorTests.cs b/src/NServiceBus.Core.Tests/Recoverability/MoveToErrorsExecutorTests.cs index a7b593364e3..910df9d6098 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/MoveToErrorsExecutorTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/MoveToErrorsExecutorTests.cs @@ -24,8 +24,11 @@ public void MoveToErrorQueue_should_route_message_to_error_queue() var addressTag = (UnicastAddressTag)((UnicastRoutingStrategy)routingContext.RoutingStrategies.Single()) .Apply([]); - Assert.AreEqual(customErrorQueue, addressTag.Destination); - Assert.AreEqual(ErrorHandleResult.Handled, moveToErrorAction.ErrorHandleResult); + Assert.Multiple(() => + { + Assert.That(addressTag.Destination, Is.EqualTo(customErrorQueue)); + Assert.That(moveToErrorAction.ErrorHandleResult, Is.EqualTo(ErrorHandleResult.Handled)); + }); } [Test] @@ -78,9 +81,12 @@ public void MoveToErrorQueue_should_add_metadata_to_headers() .Single(); var outgoingMessageHeaders = transportOperation.Message.Headers; - Assert.That(outgoingMessageHeaders, Contains.Item(new KeyValuePair("staticFaultMetadataKey", "staticFaultMetadataValue"))); - // check for leaking headers - Assert.That(recoverabilityContext.FailedMessage.Headers.ContainsKey("staticFaultMetadataKey"), Is.False); + Assert.Multiple(() => + { + Assert.That(outgoingMessageHeaders, Contains.Item(new KeyValuePair("staticFaultMetadataKey", "staticFaultMetadataValue"))); + // check for leaking headers + Assert.That(recoverabilityContext.FailedMessage.Headers.ContainsKey("staticFaultMetadataKey"), Is.False); + }); } static TestableRecoverabilityContext CreateRecoverabilityContext(Exception raisedException = null, string exceptionMessage = "default-message", string messageId = "default-id", Dictionary messageHeaders = default, Dictionary metadata = default) diff --git a/src/NServiceBus.Core.Tests/Recoverability/RecoverabilityExecutorTests.cs b/src/NServiceBus.Core.Tests/Recoverability/RecoverabilityExecutorTests.cs index 3da672cde3f..a04848cea18 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/RecoverabilityExecutorTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/RecoverabilityExecutorTests.cs @@ -34,7 +34,7 @@ public async Task Should_share_error_context_extensions() await executor.Invoke(errorContext); - Assert.AreEqual(existingValue, pipelineExtensions.Get("existing value")); + Assert.That(pipelineExtensions.Get("existing value"), Is.EqualTo(existingValue)); } [Test] @@ -58,7 +58,7 @@ public async Task Should_use_error_context_extensions_as_extensions_root() await executor.Invoke(errorContext); - Assert.AreEqual(newValue, errorContext.Extensions.Get("new value")); + Assert.That(errorContext.Extensions.Get("new value"), Is.EqualTo(newValue)); } static RecoverabilityPipelineExecutor CreateRecoverabilityExecutor(TestableMessageOperations.Pipeline recoverabilityPipeline) diff --git a/src/NServiceBus.Core.Tests/Recoverability/RecoverabilitySettingsExtensionsTests.cs b/src/NServiceBus.Core.Tests/Recoverability/RecoverabilitySettingsExtensionsTests.cs index 80e1d3c8765..11e422eefa6 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/RecoverabilitySettingsExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/RecoverabilitySettingsExtensionsTests.cs @@ -16,7 +16,7 @@ public void When_no_unrecoverable_exception_present_should_add_exception_type() var result = settings.UnrecoverableExceptions(); Assert.That(result, Has.Count.EqualTo(1)); - Assert.IsTrue(result.Contains(typeof(Exception))); + Assert.That(result.Contains(typeof(Exception)), Is.True); } [Test] @@ -29,7 +29,7 @@ public void When_unrecoverable_exception_present_should_add_exception_type() var result = settings.UnrecoverableExceptions(); Assert.That(result, Has.Count.EqualTo(2)); - Assert.IsTrue(result.Contains(typeof(InvalidOperationException))); + Assert.That(result.Contains(typeof(InvalidOperationException)), Is.True); } [Test] @@ -42,6 +42,6 @@ public void When_adding_two_times_the_same_type_should_deduplicate() var result = settings.UnrecoverableExceptions(); Assert.That(result, Has.Count.EqualTo(1)); - Assert.IsTrue(result.Contains(typeof(Exception))); + Assert.That(result.Contains(typeof(Exception)), Is.True); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Recoverability/TransportCapabilityAdjustmentTests.cs b/src/NServiceBus.Core.Tests/Recoverability/TransportCapabilityAdjustmentTests.cs index 284e2e35be9..bcb29a88789 100644 --- a/src/NServiceBus.Core.Tests/Recoverability/TransportCapabilityAdjustmentTests.cs +++ b/src/NServiceBus.Core.Tests/Recoverability/TransportCapabilityAdjustmentTests.cs @@ -12,8 +12,8 @@ public void When_delayed_retries_not_supported_but_policy_demands_it_should_move var recoverabilityAction = RecoverabilityComponent.AdjustForTransportCapabilities(ErrorQueueAddress, false, false, RecoverabilityAction.DelayedRetry(TimeSpan.FromSeconds(1))); var errorAction = recoverabilityAction as MoveToError; - Assert.NotNull(errorAction); - Assert.AreEqual(ErrorQueueAddress, errorAction.ErrorQueue); + Assert.That(errorAction, Is.Not.Null); + Assert.That(errorAction.ErrorQueue, Is.EqualTo(ErrorQueueAddress)); } [Test] @@ -22,8 +22,8 @@ public void When_immediate_retries_not_supported_but_policy_demands_it_should_mo var recoverabilityAction = RecoverabilityComponent.AdjustForTransportCapabilities(ErrorQueueAddress, false, false, RecoverabilityAction.ImmediateRetry()); var errorAction = recoverabilityAction as MoveToError; - Assert.NotNull(errorAction); - Assert.AreEqual(ErrorQueueAddress, errorAction.ErrorQueue); + Assert.That(errorAction, Is.Not.Null); + Assert.That(errorAction.ErrorQueue, Is.EqualTo(ErrorQueueAddress)); } static string ErrorQueueAddress = "error-queue"; diff --git a/src/NServiceBus.Core.Tests/Reliability/Outbox/TransportReceiveToPhysicalMessageConnectorTests.cs b/src/NServiceBus.Core.Tests/Reliability/Outbox/TransportReceiveToPhysicalMessageConnectorTests.cs index 5c3e4bdd94d..618dba05b57 100644 --- a/src/NServiceBus.Core.Tests/Reliability/Outbox/TransportReceiveToPhysicalMessageConnectorTests.cs +++ b/src/NServiceBus.Core.Tests/Reliability/Outbox/TransportReceiveToPhysicalMessageConnectorTests.cs @@ -44,18 +44,21 @@ public async Task Should_honor_stored_delivery_constraints() var operationProperties = new DispatchProperties(fakeBatchPipeline.TransportOperations.First().Properties); var delayDeliveryWith = operationProperties.DelayDeliveryWith; - Assert.NotNull(delayDeliveryWith); - Assert.AreEqual(TimeSpan.FromSeconds(10), delayDeliveryWith.Delay); + Assert.That(delayDeliveryWith, Is.Not.Null); + Assert.That(delayDeliveryWith.Delay, Is.EqualTo(TimeSpan.FromSeconds(10))); var doNotDeliverBefore = operationProperties.DoNotDeliverBefore; - Assert.NotNull(doNotDeliverBefore); - Assert.AreEqual(deliverTime.ToString(), doNotDeliverBefore.At.ToString()); + Assert.That(doNotDeliverBefore, Is.Not.Null); + Assert.That(doNotDeliverBefore.At.ToString(), Is.EqualTo(deliverTime.ToString())); var discard = operationProperties.DiscardIfNotReceivedBefore; - Assert.NotNull(discard); - Assert.AreEqual(maxTime, discard.MaxTime); + Assert.That(discard, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(discard.MaxTime, Is.EqualTo(maxTime)); - Assert.Null(fakeOutbox.StoredMessage); + Assert.That(fakeOutbox.StoredMessage, Is.Null); + }); } [Test] @@ -75,9 +78,12 @@ public async Task Should_honor_stored_direct_routing() await Invoke(context); var routing = fakeBatchPipeline.TransportOperations.First().AddressTag as UnicastAddressTag; - Assert.NotNull(routing); - Assert.AreEqual("myEndpoint", routing.Destination); - Assert.Null(fakeOutbox.StoredMessage); + Assert.That(routing, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(routing.Destination, Is.EqualTo("myEndpoint")); + Assert.That(fakeOutbox.StoredMessage, Is.Null); + }); } @@ -101,9 +107,12 @@ public async Task Should_honor_stored_pubsub_routing() await Invoke(context); var routing = fakeBatchPipeline.TransportOperations.First().AddressTag as MulticastAddressTag; - Assert.NotNull(routing); - Assert.AreEqual(typeof(MyEvent), routing.MessageType); - Assert.Null(fakeOutbox.StoredMessage); + Assert.That(routing, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(routing.MessageType, Is.EqualTo(typeof(MyEvent))); + Assert.That(fakeOutbox.StoredMessage, Is.Null); + }); } [Test] @@ -119,7 +128,7 @@ public async Task Should_add_outbox_span_tag_when_deduplicating() await Invoke(context); - Assert.AreEqual(true, pipelineActivity.TagObjects.ToImmutableDictionary()["nservicebus.outbox.deduplicate-message"]); + Assert.That(pipelineActivity.TagObjects.ToImmutableDictionary()["nservicebus.outbox.deduplicate-message"], Is.EqualTo(true)); } [Test] @@ -143,10 +152,10 @@ await Invoke(context, c => return Task.CompletedTask; }); - var startDispatchErActivityEventsvent = pipelineActivity.Events.Where(e => e.Name == "Start dispatching").ToArray(); - Assert.AreEqual(1, startDispatchErActivityEventsvent.Length); - Assert.AreEqual(3, startDispatchErActivityEventsvent.Single().Tags.ToImmutableDictionary()["message-count"]); - Assert.AreEqual(1, pipelineActivity.Events.Count(e => e.Name == "Finished dispatching")); + var startDispatcherActivityEvents = pipelineActivity.Events.Where(e => e.Name == "Start dispatching").ToArray(); + Assert.That(startDispatcherActivityEvents, Has.Length.EqualTo(1)); + Assert.That(startDispatcherActivityEvents.Single().Tags.ToImmutableDictionary()["message-count"], Is.EqualTo(3)); + Assert.That(pipelineActivity.Events.Count(e => e.Name == "Finished dispatching"), Is.EqualTo(1)); } [Test] @@ -160,8 +169,11 @@ public async Task Should_not_add_batch_dispatch_events_when_no_batched_messages( await Invoke(context); - Assert.AreEqual(0, pipelineActivity.Events.Count(e => e.Name == "Start dispatching")); - Assert.AreEqual(0, pipelineActivity.Events.Count(e => e.Name == "Finished dispatching")); + Assert.Multiple(() => + { + Assert.That(pipelineActivity.Events.Count(e => e.Name == "Start dispatching"), Is.EqualTo(0)); + Assert.That(pipelineActivity.Events.Count(e => e.Name == "Finished dispatching"), Is.EqualTo(0)); + }); } static TestableTransportReceiveContext CreateContext(FakeBatchPipeline pipeline, string messageId) diff --git a/src/NServiceBus.Core.Tests/Routing/ApplyReplyToAddressBehaviorTests.cs b/src/NServiceBus.Core.Tests/Routing/ApplyReplyToAddressBehaviorTests.cs index 5e6ec0596fc..28e75fbc674 100644 --- a/src/NServiceBus.Core.Tests/Routing/ApplyReplyToAddressBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/ApplyReplyToAddressBehaviorTests.cs @@ -18,7 +18,7 @@ public async Task Should_use_public_return_address_if_specified() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual("PublicAddress", context.Headers[Headers.ReplyToAddress]); + Assert.That(context.Headers[Headers.ReplyToAddress], Is.EqualTo("PublicAddress")); } static TestableOutgoingLogicalMessageContext CreateContext(ExtendableOptions options) @@ -40,7 +40,7 @@ public async Task Should_default_to_setting_the_reply_to_header_to_this_endpoint await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual("MyEndpoint", context.Headers[Headers.ReplyToAddress]); + Assert.That(context.Headers[Headers.ReplyToAddress], Is.EqualTo("MyEndpoint")); } [Test] @@ -54,7 +54,7 @@ public async Task Should_set_the_reply_to_header_to_this_endpoint_when_requested var context = CreateContext(options); await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual("MyEndpoint", context.Headers[Headers.ReplyToAddress]); + Assert.That(context.Headers[Headers.ReplyToAddress], Is.EqualTo("MyEndpoint")); } [Test] @@ -68,7 +68,7 @@ public async Task Should_set_the_reply_to_header_to_this_instance_when_requested var context = CreateContext(options); await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual("MyInstance", context.Headers[Headers.ReplyToAddress]); + Assert.That(context.Headers[Headers.ReplyToAddress], Is.EqualTo("MyInstance")); } [Test] @@ -82,7 +82,7 @@ public async Task Should_set_the_reply_to_header_a_specified_address_when_reques var context = CreateContext(options); await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual("Destination", context.Headers[Headers.ReplyToAddress]); + Assert.That(context.Headers[Headers.ReplyToAddress], Is.EqualTo("Destination")); } [Test] diff --git a/src/NServiceBus.Core.Tests/Routing/AssemblyRouteSourceTests.cs b/src/NServiceBus.Core.Tests/Routing/AssemblyRouteSourceTests.cs index 7b97bd24265..cf13b29b605 100644 --- a/src/NServiceBus.Core.Tests/Routing/AssemblyRouteSourceTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/AssemblyRouteSourceTests.cs @@ -15,7 +15,7 @@ public void It_returns_only_message_types() var routes = source.GenerateRoutes(new Conventions()).ToArray(); var routeTypes = routes.Select(r => r.MessageType); - CollectionAssert.DoesNotContain(routeTypes, typeof(NonMessage)); + Assert.That(routeTypes, Has.No.Member(typeof(NonMessage))); } diff --git a/src/NServiceBus.Core.Tests/Routing/BestPracticesOptionExtensionsTests.cs b/src/NServiceBus.Core.Tests/Routing/BestPracticesOptionExtensionsTests.cs index 1f6129cc234..5c3210e2ef1 100644 --- a/src/NServiceBus.Core.Tests/Routing/BestPracticesOptionExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/BestPracticesOptionExtensionsTests.cs @@ -10,7 +10,7 @@ public void IgnoredBestPractices_Should_Return_False_When_Not_Disabled_Best_Prac { var options = new SendOptions(); - Assert.IsFalse(options.IgnoredBestPractices()); + Assert.That(options.IgnoredBestPractices(), Is.False); } [Test] @@ -20,6 +20,6 @@ public void IgnoredBestPractices_Should_Return_True_When_Disabled_Best_Practice_ options.DoNotEnforceBestPractices(); - Assert.IsTrue(options.IgnoredBestPractices()); + Assert.That(options.IgnoredBestPractices(), Is.True); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Routing/DetermineRouteForPublishBehaviorTests.cs b/src/NServiceBus.Core.Tests/Routing/DetermineRouteForPublishBehaviorTests.cs index 036185f4cfc..4aaf83914d9 100644 --- a/src/NServiceBus.Core.Tests/Routing/DetermineRouteForPublishBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/DetermineRouteForPublishBehaviorTests.cs @@ -26,7 +26,7 @@ await behavior.Invoke(context, _ => return Task.CompletedTask; }); - Assert.AreEqual(typeof(MyEvent), addressTag.MessageType); + Assert.That(addressTag.MessageType, Is.EqualTo(typeof(MyEvent))); } class MyEvent diff --git a/src/NServiceBus.Core.Tests/Routing/DetermineRouteForReplyBehaviorTests.cs b/src/NServiceBus.Core.Tests/Routing/DetermineRouteForReplyBehaviorTests.cs index 352f8be33f6..649e75f0a9b 100644 --- a/src/NServiceBus.Core.Tests/Routing/DetermineRouteForReplyBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/DetermineRouteForReplyBehaviorTests.cs @@ -35,7 +35,7 @@ await behavior.Invoke(context, c => return Task.CompletedTask; }); - Assert.AreEqual("ReplyAddressOfIncomingMessage", addressTag.Destination); + Assert.That(addressTag.Destination, Is.EqualTo("ReplyAddressOfIncomingMessage")); } [Test] @@ -71,7 +71,7 @@ await behavior.Invoke(context, c => return Task.CompletedTask; }); - Assert.AreEqual("CustomReplyToAddress", addressTag.Destination); + Assert.That(addressTag.Destination, Is.EqualTo("CustomReplyToAddress")); } static TestableOutgoingReplyContext CreateContext(OutgoingLogicalMessage message) diff --git a/src/NServiceBus.Core.Tests/Routing/EndpointInstanceTests.cs b/src/NServiceBus.Core.Tests/Routing/EndpointInstanceTests.cs index ab4256c8b9b..e2a55e82bab 100644 --- a/src/NServiceBus.Core.Tests/Routing/EndpointInstanceTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/EndpointInstanceTests.cs @@ -12,6 +12,6 @@ public void Two_instances_with_same_properties_are_equal() var i1 = new EndpointInstance("Endpoint").SetProperty("P1", "V1").SetProperty("P2", "V2"); var i2 = new EndpointInstance("Endpoint").SetProperty("P2", "V2").SetProperty("P1", "V1"); - Assert.IsTrue(i1.Equals(i2)); + Assert.That(i1, Is.EqualTo(i2)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Routing/EndpointInstancesTests.cs b/src/NServiceBus.Core.Tests/Routing/EndpointInstancesTests.cs index 6ea37f17707..2f95de91f80 100644 --- a/src/NServiceBus.Core.Tests/Routing/EndpointInstancesTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/EndpointInstancesTests.cs @@ -21,10 +21,10 @@ public void Should_add_instances_grouped_by_endpoint_name() ]); var salesInstances = instances.FindInstances(endpointName1); - Assert.AreEqual(1, salesInstances.Count()); + Assert.That(salesInstances.Count(), Is.EqualTo(1)); var otherInstances = instances.FindInstances(endpointName2); - Assert.AreEqual(1, otherInstances.Count()); + Assert.That(otherInstances.Count(), Is.EqualTo(1)); } [Test] @@ -39,7 +39,7 @@ public void Should_return_instances_configured_by_static_route() ]); var salesInstances = instances.FindInstances(sales); - Assert.AreEqual(2, salesInstances.Count()); + Assert.That(salesInstances.Count(), Is.EqualTo(2)); } [Test] @@ -54,7 +54,7 @@ public void Should_filter_out_duplicate_instances() ]); var salesInstances = instances.FindInstances(sales); - Assert.AreEqual(1, salesInstances.Count()); + Assert.That(salesInstances.Count(), Is.EqualTo(1)); } [Test] @@ -64,7 +64,10 @@ public void Should_default_to_single_instance_when_not_configured() var salesInstances = instances.FindInstances("Sales"); var singleInstance = salesInstances.Single(); - Assert.IsNull(singleInstance.Discriminator); - Assert.IsEmpty(singleInstance.Properties); + Assert.Multiple(() => + { + Assert.That(singleInstance.Discriminator, Is.Null); + Assert.That(singleInstance.Properties, Is.Empty); + }); } } diff --git a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscribeTerminatorTests.cs b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscribeTerminatorTests.cs index 78e19396cca..3a2c067a8f7 100644 --- a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscribeTerminatorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscribeTerminatorTests.cs @@ -35,8 +35,11 @@ public async Task Should_include_TimeSent_and_Version_headers() var unicastTransportOperations = dispatchedTransportOperation.UnicastTransportOperations; var operations = new List(unicastTransportOperations); - Assert.IsTrue(operations[0].Message.Headers.ContainsKey(Headers.TimeSent)); - Assert.IsTrue(operations[0].Message.Headers.ContainsKey(Headers.NServiceBusVersion)); + Assert.Multiple(() => + { + Assert.That(operations[0].Message.Headers.ContainsKey(Headers.TimeSent), Is.True); + Assert.That(operations[0].Message.Headers.ContainsKey(Headers.NServiceBusVersion), Is.True); + }); } } @@ -50,7 +53,7 @@ public async Task Should_Dispatch_for_all_publishers() await subscribeTerminator.Invoke(new TestableSubscribeContext(), c => Task.CompletedTask); - Assert.AreEqual(2, dispatcher.DispatchedTransportOperations.Count); + Assert.That(dispatcher.DispatchedTransportOperations.Count, Is.EqualTo(2)); } [Test] @@ -64,8 +67,11 @@ public async Task Should_Dispatch_according_to_max_retries_when_dispatch_fails() await subscribeTerminator.Invoke(context, c => Task.CompletedTask); - Assert.AreEqual(1, dispatcher.DispatchedTransportOperations.Count); - Assert.AreEqual(10, dispatcher.FailedNumberOfTimes); + Assert.Multiple(() => + { + Assert.That(dispatcher.DispatchedTransportOperations.Count, Is.EqualTo(1)); + Assert.That(dispatcher.FailedNumberOfTimes, Is.EqualTo(10)); + }); } [Test] @@ -82,8 +88,11 @@ public void Should_Throw_when_max_retries_reached() await subscribeTerminator.Invoke(context, c => Task.CompletedTask); }, Throws.InstanceOf()); - Assert.AreEqual(0, dispatcher.DispatchedTransportOperations.Count); - Assert.AreEqual(11, dispatcher.FailedNumberOfTimes); + Assert.Multiple(() => + { + Assert.That(dispatcher.DispatchedTransportOperations.Count, Is.EqualTo(0)); + Assert.That(dispatcher.FailedNumberOfTimes, Is.EqualTo(11)); + }); } [Test] @@ -95,7 +104,7 @@ public void Should_throw_when_no_publisher_for_message_found() var exception = Assert.ThrowsAsync(() => subscribeTerminator.Invoke(new TestableSubscribeContext(), c => Task.CompletedTask)); - StringAssert.Contains($"No publisher address could be found for message type '{typeof(object)}'.", exception.Message); + Assert.That(exception.Message, Does.Contain($"No publisher address could be found for message type '{typeof(object)}'.")); } [Test] @@ -116,7 +125,7 @@ public async Task Should_dispatch_to_all_publishers_for_all_events() await subscribeTerminator.Invoke(context, c => Task.CompletedTask); - Assert.AreEqual(4, dispatcher.DispatchedTransportOperations.Count); + Assert.That(dispatcher.DispatchedTransportOperations.Count, Is.EqualTo(4)); } [Test] @@ -141,9 +150,12 @@ public void When_subscribing_multiple_events_should_throw_aggregate_exception_wi var exception = Assert.ThrowsAsync(() => subscribeTerminator.Invoke(context, c => Task.CompletedTask)); - Assert.AreEqual(2, exception.InnerExceptions.Count); - Assert.IsTrue(exception.InnerExceptions.Any(e => e is QueueNotFoundException)); // exception from dispatcher - Assert.IsTrue(exception.InnerExceptions.Any(e => e.Message.Contains($"No publisher address could be found for message type '{typeof(EventB)}'"))); // exception from terminator + Assert.That(exception.InnerExceptions.Count, Is.EqualTo(2)); + Assert.Multiple(() => + { + Assert.That(exception.InnerExceptions.Any(e => e is QueueNotFoundException), Is.True); // exception from dispatcher + Assert.That(exception.InnerExceptions.Any(e => e.Message.Contains($"No publisher address could be found for message type '{typeof(EventB)}'")), Is.True); // exception from terminator + }); } diff --git a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/AssemblyPublisherSourceTests.cs b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/AssemblyPublisherSourceTests.cs index adf172d48f8..71ffbaf32ee 100644 --- a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/AssemblyPublisherSourceTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/AssemblyPublisherSourceTests.cs @@ -15,8 +15,11 @@ public void It_returns_only_event_types() var source = new AssemblyPublisherSource(Assembly.GetExecutingAssembly(), PublisherAddress.CreateFromEndpointName("Destination")); var routes = source.GenerateWithBestPracticeEnforcement(new Conventions()).ToArray(); - Assert.IsFalse(routes.Any(r => r.EventType == typeof(NonMessage))); - Assert.IsFalse(routes.Any(r => r.EventType == typeof(NonEvent))); + Assert.Multiple(() => + { + Assert.That(routes.Any(r => r.EventType == typeof(NonMessage)), Is.False); + Assert.That(routes.Any(r => r.EventType == typeof(NonEvent)), Is.False); + }); } diff --git a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/MessageDrivenSubscriptionsConfigExtensionsTests.cs b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/MessageDrivenSubscriptionsConfigExtensionsTests.cs index 0e15c27ca99..715300a31af 100644 --- a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/MessageDrivenSubscriptionsConfigExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/MessageDrivenSubscriptionsConfigExtensionsTests.cs @@ -26,7 +26,7 @@ public void WhenPassingTransportAddressForPublisherInsteadOfEndpointName_ShouldT var routingSettings = new RoutingSettings(new SettingsHolder()); var exception = Assert.Throws(() => routingSettings.RegisterPublisher(typeof(Event), "EndpointName@MyHost")); - Assert.AreEqual(expectedExceptionMessageForWrongEndpointName, exception.Message); + Assert.That(exception.Message, Is.EqualTo(expectedExceptionMessageForWrongEndpointName)); } [Test] @@ -35,7 +35,7 @@ public void WhenPassingTransportAddressForPublisherInsteadOfEndpointName_UsingAs var routingSettings = new RoutingSettings(new SettingsHolder()); var exception = Assert.Throws(() => routingSettings.RegisterPublisher(Assembly.GetExecutingAssembly(), "EndpointName@MyHost")); - Assert.AreEqual(expectedExceptionMessageForWrongEndpointName, exception.Message); + Assert.That(exception.Message, Is.EqualTo(expectedExceptionMessageForWrongEndpointName)); } [Test] @@ -44,7 +44,7 @@ public void WhenPassingTransportAddressForPublisherInsteadOfEndpointName_UsingAs var routingSettings = new RoutingSettings(new SettingsHolder()); var exception = Assert.Throws(() => routingSettings.RegisterPublisher(Assembly.GetExecutingAssembly(), nameof(EventNamespace), "EndpointName@MyHost")); - Assert.AreEqual(expectedExceptionMessageForWrongEndpointName, exception.Message); + Assert.That(exception.Message, Is.EqualTo(expectedExceptionMessageForWrongEndpointName)); } [Test] @@ -56,7 +56,7 @@ public void WhenPassingEndpointNameForPublisher_ShouldAddRouteToPublishers() var publishers = ApplyPublisherRegistrations(routingSettings); var publishersForEvent = publishers.GetPublisherFor(typeof(Event)).SingleOrDefault(); - Assert.IsNotNull(publishersForEvent); + Assert.That(publishersForEvent, Is.Not.Null); } [Test] @@ -70,8 +70,11 @@ public void WhenPassingEndpointNameForPublisher_UsingAssembly_ShouldAddAllEvents var publishersForEvent = publishers.GetPublisherFor(typeof(Event)).SingleOrDefault(); var publishersForEventWithNamespace = publishers.GetPublisherFor(typeof(EventWithNamespace)).SingleOrDefault(); - Assert.IsNotNull(publishersForEvent); - Assert.IsNotNull(publishersForEventWithNamespace); + Assert.Multiple(() => + { + Assert.That(publishersForEvent, Is.Not.Null); + Assert.That(publishersForEventWithNamespace, Is.Not.Null); + }); } [Test] @@ -85,8 +88,11 @@ public void WhenPassingEndpointNameForPublisher_UsingAssemblyAndNamespace_Should var publishersForEvent = publishers.GetPublisherFor(typeof(Event)).SingleOrDefault(); var publishersForEventWithNamespace = publishers.GetPublisherFor(typeof(EventWithNamespace)).SingleOrDefault(); - Assert.IsNull(publishersForEvent); - Assert.IsNotNull(publishersForEventWithNamespace); + Assert.Multiple(() => + { + Assert.That(publishersForEvent, Is.Null); + Assert.That(publishersForEventWithNamespace, Is.Not.Null); + }); } [Test] @@ -102,10 +108,13 @@ public void Should_register_all_types_in_assembly_when_not_specifying_namespace( var result3 = publishers.GetPublisherFor(typeof(EventWithoutNamespace)).SingleOrDefault(); var result4 = publishers.GetPublisherFor(typeof(IMessageInterface)).SingleOrDefault(); - Assert.IsNotNull(result1); - Assert.IsNotNull(result2); - Assert.IsNotNull(result3); - Assert.IsNotNull(result4); + Assert.Multiple(() => + { + Assert.That(result1, Is.Not.Null); + Assert.That(result2, Is.Not.Null); + Assert.That(result3, Is.Not.Null); + Assert.That(result4, Is.Not.Null); + }); } [Test] @@ -121,10 +130,13 @@ public void Should_only_register_types_in_specified_namespace() var result3 = publishers.GetPublisherFor(typeof(EventWithoutNamespace)).SingleOrDefault(); var result4 = publishers.GetPublisherFor(typeof(IMessageInterface)).SingleOrDefault(); - Assert.IsNotNull(result1); - Assert.IsNotNull(result4); - Assert.IsNull(result2); - Assert.IsNull(result3); + Assert.Multiple(() => + { + Assert.That(result1, Is.Not.Null); + Assert.That(result4, Is.Not.Null); + Assert.That(result2, Is.Null); + Assert.That(result3, Is.Null); + }); } [Theory] @@ -142,10 +154,13 @@ public void Should_support_empty_namespace(string eventNamespace) var result3 = publishers.GetPublisherFor(typeof(EventWithoutNamespace)).SingleOrDefault(); var result4 = publishers.GetPublisherFor(typeof(IMessageInterface)).SingleOrDefault(); - Assert.IsNotNull(result3); - Assert.IsNull(result1); - Assert.IsNull(result2); - Assert.IsNull(result4); + Assert.Multiple(() => + { + Assert.That(result3, Is.Not.Null); + Assert.That(result1, Is.Null); + Assert.That(result2, Is.Null); + Assert.That(result4, Is.Null); + }); } static Publishers ApplyPublisherRegistrations(RoutingSettings routingSettings) diff --git a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/NamespacePublisherSourceTests.cs b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/NamespacePublisherSourceTests.cs index b84adebb5a5..2f019d6267f 100644 --- a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/NamespacePublisherSourceTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/NamespacePublisherSourceTests.cs @@ -17,9 +17,9 @@ public void It_returns_only_event_types() var routes = source.GenerateWithBestPracticeEnforcement(new Conventions()); var routedTypes = routes.Select(r => r.EventType).ToArray(); - CollectionAssert.Contains(routedTypes, typeof(Event)); - CollectionAssert.DoesNotContain(routedTypes, typeof(NonMessage)); - CollectionAssert.DoesNotContain(routedTypes, typeof(NonEvent)); + Assert.That(routedTypes, Has.Member(typeof(Event))); + Assert.That(routedTypes, Has.No.Member(typeof(NonMessage))); + Assert.That(routedTypes, Has.No.Member(typeof(NonEvent))); } [Test] @@ -29,8 +29,8 @@ public void It_returns_only_types_from_specified_namespace() var routes = source.GenerateWithBestPracticeEnforcement(new Conventions()); var routedTypes = routes.Select(r => r.EventType).ToArray(); - CollectionAssert.Contains(routedTypes, typeof(Event)); - CollectionAssert.DoesNotContain(routedTypes, typeof(ExcludedEvent)); + Assert.That(routedTypes, Has.Member(typeof(Event))); + Assert.That(routedTypes, Has.No.Member(typeof(ExcludedEvent))); } [Test] @@ -40,7 +40,7 @@ public void It_matches_namespace_in_case_insensitive_way() var routes = source.GenerateWithBestPracticeEnforcement(new Conventions()).ToArray(); var routedTypes = routes.Select(r => r.EventType); - CollectionAssert.Contains(routedTypes, typeof(Event)); + Assert.That(routedTypes, Has.Member(typeof(Event))); } [Test] diff --git a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/PublishersTests.cs b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/PublishersTests.cs index 982a90c12a6..3e3125e3632 100644 --- a/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/PublishersTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/MessageDrivenSubscriptions/PublishersTests.cs @@ -20,7 +20,7 @@ public void When_group_does_not_exist_should_add_routes() ]); var retrievedPublisher = publisherTable.GetPublisherFor(typeof(MyEvent)).Single(); - Assert.AreSame(publisher, retrievedPublisher); + Assert.That(retrievedPublisher, Is.SameAs(publisher)); } [Test] @@ -40,7 +40,7 @@ public void When_group_exists_should_replace_existing_routes() ]); var retrievedPublisher = publisherTable.GetPublisherFor(typeof(MyEvent)).Single(); - Assert.AreSame(newPublisher, retrievedPublisher); + Assert.That(retrievedPublisher, Is.SameAs(newPublisher)); } [Test] @@ -62,8 +62,8 @@ public void When_multiple_publishers_exist_should_return_all_of_them() var pubs = publisherTable.GetPublisherFor(typeof(MyEvent)).ToArray(); - Assert.Contains(pub1, pubs); - Assert.Contains(pub2, pubs); + Assert.That(pubs, Does.Contain(pub1)); + Assert.That(pubs, Does.Contain(pub2)); } [Test] @@ -90,13 +90,13 @@ public void When_same_publisher_is_registered_multiple_times_should_remove_dupli var pubs = publisherTable.GetPublisherFor(typeof(MyEvent)).ToArray(); - Assert.AreEqual(3, pubs.Length); - Assert.Contains(pub1, pubs); - Assert.Contains(pub2, pubs); - Assert.Contains(pub3, pubs); - Assert.Contains(pub4, pubs); - Assert.Contains(pub5, pubs); - Assert.Contains(pub6, pubs); + Assert.That(pubs, Has.Length.EqualTo(3)); + Assert.That(pubs, Does.Contain(pub1)); + Assert.That(pubs, Does.Contain(pub2)); + Assert.That(pubs, Does.Contain(pub3)); + Assert.That(pubs, Does.Contain(pub4)); + Assert.That(pubs, Does.Contain(pub5)); + Assert.That(pubs, Does.Contain(pub6)); } class MyEvent : IEvent diff --git a/src/NServiceBus.Core.Tests/Routing/MessageDrivenUnsubscribeTerminatorTests.cs b/src/NServiceBus.Core.Tests/Routing/MessageDrivenUnsubscribeTerminatorTests.cs index 18e86069811..8bd918719ec 100644 --- a/src/NServiceBus.Core.Tests/Routing/MessageDrivenUnsubscribeTerminatorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/MessageDrivenUnsubscribeTerminatorTests.cs @@ -34,7 +34,7 @@ public async Task Should_Dispatch_for_all_publishers() { await terminator.Invoke(new TestableUnsubscribeContext(), c => Task.CompletedTask); - Assert.AreEqual(1, dispatcher.DispatchedTransportOperations.Count); + Assert.That(dispatcher.DispatchedTransportOperations.Count, Is.EqualTo(1)); } [Test] @@ -53,8 +53,11 @@ public async Task Should_Dispatch_according_to_max_retries_when_dispatch_fails() await terminator.Invoke(context, c => Task.CompletedTask); - Assert.AreEqual(1, dispatcher.DispatchedTransportOperations.Count); - Assert.AreEqual(10, dispatcher.FailedNumberOfTimes); + Assert.Multiple(() => + { + Assert.That(dispatcher.DispatchedTransportOperations.Count, Is.EqualTo(1)); + Assert.That(dispatcher.FailedNumberOfTimes, Is.EqualTo(10)); + }); } [Test] @@ -73,8 +76,11 @@ public void Should_Throw_when_max_retries_reached() Assert.That(async () => await terminator.Invoke(context, c => Task.CompletedTask), Throws.InstanceOf()); - Assert.AreEqual(0, dispatcher.DispatchedTransportOperations.Count); - Assert.AreEqual(11, dispatcher.FailedNumberOfTimes); + Assert.Multiple(() => + { + Assert.That(dispatcher.DispatchedTransportOperations.Count, Is.EqualTo(0)); + Assert.That(dispatcher.FailedNumberOfTimes, Is.EqualTo(11)); + }); } class FakeDispatcher : IMessageDispatcher diff --git a/src/NServiceBus.Core.Tests/Routing/NamespaceRouteSourceTests.cs b/src/NServiceBus.Core.Tests/Routing/NamespaceRouteSourceTests.cs index c080f55f237..a818f18c385 100644 --- a/src/NServiceBus.Core.Tests/Routing/NamespaceRouteSourceTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/NamespaceRouteSourceTests.cs @@ -16,8 +16,11 @@ public void It_returns_only_message_types() var source = new NamespaceRouteSource(Assembly.GetExecutingAssembly(), "NServiceBus.Core.Tests.Routing.NamespaceRouteSourceTest", UnicastRoute.CreateFromEndpointName("Destination")); var routes = source.GenerateRoutes(new Conventions()).ToArray(); - Assert.IsTrue(routes.Any(r => r.MessageType == typeof(Message))); - Assert.IsFalse(routes.Any(r => r.MessageType == typeof(NonMessage))); + Assert.Multiple(() => + { + Assert.That(routes.Any(r => r.MessageType == typeof(Message)), Is.True); + Assert.That(routes.Any(r => r.MessageType == typeof(NonMessage)), Is.False); + }); } [Test] @@ -26,8 +29,11 @@ public void It_returns_only_types_from_specified_namespace() var source = new NamespaceRouteSource(Assembly.GetExecutingAssembly(), "NServiceBus.Core.Tests.Routing.NamespaceRouteSourceTest", UnicastRoute.CreateFromEndpointName("Destination")); var routes = source.GenerateRoutes(new Conventions()).ToArray(); - Assert.IsTrue(routes.Any(r => r.MessageType == typeof(Message))); - Assert.IsFalse(routes.Any(r => r.MessageType == typeof(ExcludedMessage))); + Assert.Multiple(() => + { + Assert.That(routes.Any(r => r.MessageType == typeof(Message)), Is.True); + Assert.That(routes.Any(r => r.MessageType == typeof(ExcludedMessage)), Is.False); + }); } [Test] @@ -36,7 +42,7 @@ public void It_matches_namespace_in_case_insensitive_way() var source = new NamespaceRouteSource(Assembly.GetExecutingAssembly(), "NServiceBus.Core.Tests.Routing.NAMESPACErouteSOURCEtest", UnicastRoute.CreateFromEndpointName("Destination")); var routes = source.GenerateRoutes(new Conventions()).ToArray(); - Assert.IsTrue(routes.Any(r => r.MessageType == typeof(Message))); + Assert.That(routes.Any(r => r.MessageType == typeof(Message)), Is.True); } [Test] diff --git a/src/NServiceBus.Core.Tests/Routing/NativeSubscribeTerminatorTests.cs b/src/NServiceBus.Core.Tests/Routing/NativeSubscribeTerminatorTests.cs index b78591ccb50..b6af6791445 100644 --- a/src/NServiceBus.Core.Tests/Routing/NativeSubscribeTerminatorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/NativeSubscribeTerminatorTests.cs @@ -22,7 +22,7 @@ public void When_subscriptionmanager_throws_aggregateexception_on_subscribe() var exception = Assert.ThrowsAsync(() => terminator.Invoke(new TestableSubscribeContext(), _ => Task.CompletedTask)); - Assert.AreSame(innerException, exception); + Assert.That(exception, Is.SameAs(innerException)); } [Test] @@ -35,7 +35,7 @@ public void When_subscriptionmanager_throws_exception_on_subscribe() var exception = Assert.ThrowsAsync(() => terminator.Invoke(new TestableSubscribeContext(), _ => Task.CompletedTask)); - Assert.AreSame(expectedException, exception); + Assert.That(exception, Is.SameAs(expectedException)); } [Test] @@ -50,7 +50,7 @@ public void When_subscriptionmanager_throws_aggregateexception_on_subscribeAll() var exception = Assert.ThrowsAsync(() => terminator.Invoke(testableSubscribeContext, _ => Task.CompletedTask)); - Assert.AreSame(aggregateException, exception); + Assert.That(exception, Is.SameAs(aggregateException)); } [Test] @@ -65,7 +65,7 @@ public void When_subscriptionmanager_throws_exception_on_subscribeAll() var exception = Assert.ThrowsAsync(() => terminator.Invoke(testableSubscribeContext, _ => Task.CompletedTask)); - Assert.AreSame(expectedException, exception); + Assert.That(exception, Is.SameAs(expectedException)); } class FakeSubscriptionManager : ISubscriptionManager diff --git a/src/NServiceBus.Core.Tests/Routing/Routers/MulticastPublishConnectorTests.cs b/src/NServiceBus.Core.Tests/Routing/Routers/MulticastPublishConnectorTests.cs index a5f3ef9ee84..4d86d90d026 100644 --- a/src/NServiceBus.Core.Tests/Routing/Routers/MulticastPublishConnectorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/Routers/MulticastPublishConnectorTests.cs @@ -15,7 +15,7 @@ public async Task Should_set_messageintent_to_publish() await router.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(1, context.Headers.Count); - Assert.AreEqual(MessageIntent.Publish.ToString(), context.Headers[Headers.MessageIntent]); + Assert.That(context.Headers.Count, Is.EqualTo(1)); + Assert.That(context.Headers[Headers.MessageIntent], Is.EqualTo(MessageIntent.Publish.ToString())); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Routing/Routers/ReplyConnectorTests.cs b/src/NServiceBus.Core.Tests/Routing/Routers/ReplyConnectorTests.cs index 341678d2e22..b41f078b5f4 100644 --- a/src/NServiceBus.Core.Tests/Routing/Routers/ReplyConnectorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/Routers/ReplyConnectorTests.cs @@ -21,7 +21,7 @@ public async Task Should_set_messageintent_to_reply() await router.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(1, context.Headers.Count); - Assert.AreEqual(MessageIntent.Reply.ToString(), context.Headers[Headers.MessageIntent]); + Assert.That(context.Headers.Count, Is.EqualTo(1)); + Assert.That(context.Headers[Headers.MessageIntent], Is.EqualTo(MessageIntent.Reply.ToString())); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Routing/Routers/SendConnectorTests.cs b/src/NServiceBus.Core.Tests/Routing/Routers/SendConnectorTests.cs index 639cc41f12d..4e6ebbf06e2 100644 --- a/src/NServiceBus.Core.Tests/Routing/Routers/SendConnectorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/Routers/SendConnectorTests.cs @@ -24,8 +24,8 @@ public async Task Should_set_messageintent_to_send() await behavior.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(1, context.Headers.Count); - Assert.AreEqual(MessageIntent.Send.ToString(), context.Headers[Headers.MessageIntent]); + Assert.That(context.Headers.Count, Is.EqualTo(1)); + Assert.That(context.Headers[Headers.MessageIntent], Is.EqualTo(MessageIntent.Send.ToString())); } [Test] @@ -44,7 +44,7 @@ await behavior.Invoke(context, c => return Task.CompletedTask; }); - Assert.AreEqual("LogicalAddress", addressTag.Destination); + Assert.That(addressTag.Destination, Is.EqualTo("LogicalAddress")); } static TestableOutgoingSendContext CreateContext(SendOptions options = null, object message = null) diff --git a/src/NServiceBus.Core.Tests/Routing/Routers/UnicastPublishConnectorTests.cs b/src/NServiceBus.Core.Tests/Routing/Routers/UnicastPublishConnectorTests.cs index 837348c7c9f..618e6859665 100644 --- a/src/NServiceBus.Core.Tests/Routing/Routers/UnicastPublishConnectorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/Routers/UnicastPublishConnectorTests.cs @@ -19,8 +19,8 @@ public async Task Should_set_messageintent_to_publish() await router.Invoke(context, ctx => Task.CompletedTask); - Assert.AreEqual(1, context.Headers.Count); - Assert.AreEqual(MessageIntent.Publish.ToString(), context.Headers[Headers.MessageIntent]); + Assert.That(context.Headers.Count, Is.EqualTo(1)); + Assert.That(context.Headers[Headers.MessageIntent], Is.EqualTo(MessageIntent.Publish.ToString())); } class FakePublishRouter : IUnicastPublishRouter diff --git a/src/NServiceBus.Core.Tests/Routing/Routers/UnicastSendRouterTests.cs b/src/NServiceBus.Core.Tests/Routing/Routers/UnicastSendRouterTests.cs index a4720524b5f..b35e56b2c5f 100644 --- a/src/NServiceBus.Core.Tests/Routing/Routers/UnicastSendRouterTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/Routers/UnicastSendRouterTests.cs @@ -22,7 +22,7 @@ public void Should_use_explicit_route_for_sends_if_present() var context = CreateContext(options); var result = router.Route(context); - Assert.AreEqual("destination endpoint", ExtractDestination(result)); + Assert.That(ExtractDestination(result), Is.EqualTo("destination endpoint")); } @@ -38,7 +38,7 @@ public void Should_route_to_local_instance_if_requested_so() var result = router.Route(context); - Assert.AreEqual("MyInstance", ExtractDestination(result)); + Assert.That(ExtractDestination(result), Is.EqualTo("MyInstance")); } [Test] @@ -53,7 +53,7 @@ public void Should_throw_if_requested_to_route_to_local_instance_and_instance_ha var context = CreateContext(options); var exception = Assert.Throws(() => router.Route(context)); - Assert.AreEqual(exception.Message, "Cannot route to a specific instance because an endpoint instance discriminator was not configured for the destination endpoint. It can be specified via EndpointConfiguration.MakeInstanceUniquelyAddressable(string discriminator)."); + Assert.That(exception.Message, Is.EqualTo("Cannot route to a specific instance because an endpoint instance discriminator was not configured for the destination endpoint. It can be specified via EndpointConfiguration.MakeInstanceUniquelyAddressable(string discriminator).")); } @@ -70,7 +70,7 @@ public void Should_throw_if_routing_to_local_instance_when_send_only() var exception = Assert.Throws(() => router.Route(context)); - StringAssert.Contains("send-only mode", exception.Message); + Assert.That(exception.Message, Does.Contain("send-only mode")); } [Test] @@ -86,7 +86,7 @@ public void Should_throw_if_routing_to_local_endpoint_when_send_only() var exception = Assert.Throws(() => router.Route(context)); - StringAssert.Contains("send-only mode", exception.Message); + Assert.That(exception.Message, Does.Contain("send-only mode")); } [Test] @@ -101,7 +101,7 @@ public void When_routing_to_specific_instance_should_throw_when_there_is_no_rout var context = CreateContext(options); var exception = Assert.Throws(() => router.Route(context)); - StringAssert.Contains("No destination specified for message", exception.Message); + Assert.That(exception.Message, Does.Contain("No destination specified for message")); } [Test] @@ -120,7 +120,7 @@ public void When_routing_to_specific_instance_should_throw_when_route_for_given_ var context = CreateContext(options); var exception = Assert.Throws(() => router.Route(context)); - StringAssert.Contains("Routing to a specific instance is only allowed if route is defined for a logical endpoint, not for an address or instance.", exception.Message); + Assert.That(exception.Message, Does.Contain("Routing to a specific instance is only allowed if route is defined for a logical endpoint, not for an address or instance.")); } [Test] @@ -146,7 +146,7 @@ public void When_routing_to_specific_instance_should_select_appropriate_instance var context = CreateContext(options); var route = router.Route(context); - Assert.AreEqual("Endpoint-2", ExtractDestination(route)); + Assert.That(ExtractDestination(route), Is.EqualTo("Endpoint-2")); } @@ -165,7 +165,7 @@ public void When_routing_command_to_logical_endpoint_without_configured_instance var router = CreateRouter(routingTable: routingTable); var route = router.Route(context); - Assert.AreEqual(logicalEndpointName, ExtractDestination(route)); + Assert.That(ExtractDestination(route), Is.EqualTo(logicalEndpointName)); } [Test] @@ -190,7 +190,7 @@ public void When_multiple_dynamic_instances_for_logical_endpoints_should_route_m var router = CreateRouter(routingTable: routingTable, instances: endpointInstances); var route = router.Route(context); - Assert.AreEqual("Sales-1", ExtractDestination(route)); + Assert.That(ExtractDestination(route), Is.EqualTo("Sales-1")); } [Test] @@ -217,9 +217,12 @@ public void When_multiple_dynamic_instances_for_logical_endpoints_should_round_r var route2 = router.Route(context); var route3 = router.Route(context); - Assert.AreEqual("Sales-1", ExtractDestination(route1)); - Assert.AreEqual("Sales-2", ExtractDestination(route2)); - Assert.AreEqual("Sales-1", ExtractDestination(route3)); + Assert.Multiple(() => + { + Assert.That(ExtractDestination(route1), Is.EqualTo("Sales-1")); + Assert.That(ExtractDestination(route2), Is.EqualTo("Sales-2")); + Assert.That(ExtractDestination(route3), Is.EqualTo("Sales-1")); + }); } [Test] @@ -230,7 +233,7 @@ public void Should_throw_when_no_routes_found() var router = CreateRouter(); var exception = Assert.Throws(() => router.Route(context)); - StringAssert.Contains("No destination specified for message", exception.Message); + Assert.That(exception.Message, Does.Contain("No destination specified for message")); } [Test] @@ -245,7 +248,7 @@ public void Should_route_to_local_endpoint_if_requested_so() var router = CreateRouter(); var route = router.Route(context); - Assert.AreEqual("Endpoint", ExtractDestination(route)); + Assert.That(ExtractDestination(route), Is.EqualTo("Endpoint")); } [Test] @@ -267,7 +270,7 @@ public void When_multiple_dynamic_instances_for_local_endpoint_should_route_mess var router = CreateRouter(instances: endpointInstances); var route = router.Route(context); - Assert.AreEqual("Endpoint-1", ExtractDestination(route)); + Assert.That(ExtractDestination(route), Is.EqualTo("Endpoint-1")); } [Test] @@ -295,7 +298,7 @@ public void When_multiple_dynamic_instances_for_local_endpoint_and_instance_sele var router = CreateRouter(routingTable: routingTable, instances: endpointInstances); var route = router.Route(context); - Assert.AreEqual("Endpoint-2", ExtractDestination(route)); + Assert.That(ExtractDestination(route), Is.EqualTo("Endpoint-2")); } [Test] @@ -325,9 +328,12 @@ public void When_multiple_dynamic_instances_for_local_endpoint_and_instance_sele var route2 = router.Route(context); var route3 = router.Route(context); - Assert.AreEqual("Endpoint-2", ExtractDestination(route1)); - Assert.AreEqual("Endpoint-2", ExtractDestination(route2)); - Assert.AreEqual("Endpoint-2", ExtractDestination(route3)); + Assert.Multiple(() => + { + Assert.That(ExtractDestination(route1), Is.EqualTo("Endpoint-2")); + Assert.That(ExtractDestination(route2), Is.EqualTo("Endpoint-2")); + Assert.That(ExtractDestination(route3), Is.EqualTo("Endpoint-2")); + }); } [Test] @@ -352,9 +358,12 @@ public void When_multiple_dynamic_instances_for_local_endpoint_should_round_robi var route2 = router.Route(context); var route3 = router.Route(context); - Assert.AreEqual("Endpoint-1", ExtractDestination(route1)); - Assert.AreEqual("Endpoint-2", ExtractDestination(route2)); - Assert.AreEqual("Endpoint-1", ExtractDestination(route3)); + Assert.Multiple(() => + { + Assert.That(ExtractDestination(route1), Is.EqualTo("Endpoint-1")); + Assert.That(ExtractDestination(route2), Is.EqualTo("Endpoint-2")); + Assert.That(ExtractDestination(route3), Is.EqualTo("Endpoint-1")); + }); } [Test] @@ -371,7 +380,7 @@ public void When_route_with_physical_address_routes_to_physical_address() var router = CreateRouter(routingTable: routingTable); var route = router.Route(context); - Assert.AreEqual("Physical", ExtractDestination(route)); + Assert.That(ExtractDestination(route), Is.EqualTo("Physical")); } [Test] @@ -388,7 +397,7 @@ public void When_route_with_endpoint_instance_routes_to_instance() var router = CreateRouter(routingTable: routingTable); var route = router.Route(context); - Assert.AreEqual("Endpoint-2", ExtractDestination(route)); + Assert.That(ExtractDestination(route), Is.EqualTo("Endpoint-2")); } static string ExtractDestination(UnicastRoutingStrategy route) diff --git a/src/NServiceBus.Core.Tests/Routing/RoutingOptionExtensionsTests.cs b/src/NServiceBus.Core.Tests/Routing/RoutingOptionExtensionsTests.cs index 65b3dc323f5..327188fcec3 100644 --- a/src/NServiceBus.Core.Tests/Routing/RoutingOptionExtensionsTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/RoutingOptionExtensionsTests.cs @@ -14,7 +14,7 @@ public void ReplyOptions_GetDestination_Should_Return_Configured_Destination() var destination = options.GetDestination(); - Assert.AreEqual(expectedDestination, destination); + Assert.That(destination, Is.EqualTo(expectedDestination)); } [Test] @@ -24,7 +24,7 @@ public void ReplyOptions_GetDestination_Should_Return_Null_When_No_Destination_C var destination = options.GetDestination(); - Assert.IsNull(destination); + Assert.That(destination, Is.Null); } [Test] @@ -36,7 +36,7 @@ public void SendOptions_GetDestination_Should_Return_Configured_Destination() var destination = options.GetDestination(); - Assert.AreEqual(expectedDestination, destination); + Assert.That(destination, Is.EqualTo(expectedDestination)); } [Test] @@ -46,7 +46,7 @@ public void SendOptions_GetDestination_Should_Return_Null_When_No_Destination_Co var destination = options.GetDestination(); - Assert.IsNull(destination); + Assert.That(destination, Is.Null); } [Test] @@ -54,7 +54,7 @@ public void IsRoutingToThisEndpoint_Should_Return_False_When_Not_Routed_To_This_ { var options = new SendOptions(); - Assert.IsFalse(options.IsRoutingToThisEndpoint()); + Assert.That(options.IsRoutingToThisEndpoint(), Is.False); } [Test] @@ -64,7 +64,7 @@ public void IsRoutingToThisEndpoint_Should_Return_True_When_Routed_To_This_Endpo options.RouteToThisEndpoint(); - Assert.IsTrue(options.IsRoutingToThisEndpoint()); + Assert.That(options.IsRoutingToThisEndpoint(), Is.True); } [Test] @@ -72,7 +72,7 @@ public void IsRoutingToThisInstance_Should_Return_False_When_Not_Routed_To_This_ { var options = new SendOptions(); - Assert.IsFalse(options.IsRoutingToThisInstance()); + Assert.That(options.IsRoutingToThisInstance(), Is.False); } [Test] @@ -82,7 +82,7 @@ public void IsRoutingToThisInstance_Should_Return_True_When_Routed_To_This_Insta options.RouteToThisInstance(); - Assert.IsTrue(options.IsRoutingToThisInstance()); + Assert.That(options.IsRoutingToThisInstance(), Is.True); } [Test] @@ -93,7 +93,7 @@ public void GetRouteToSpecificInstance_Should_Return_Configured_Instance() options.RouteToSpecificInstance(expectedInstanceId); - Assert.AreEqual(expectedInstanceId, options.GetRouteToSpecificInstance()); + Assert.That(options.GetRouteToSpecificInstance(), Is.EqualTo(expectedInstanceId)); } [Test] @@ -101,7 +101,7 @@ public void GetRouteToSpecificInstance_Should_Return_Null_When_No_Instance_Confi { var options = new SendOptions(); - Assert.IsNull(options.GetRouteToSpecificInstance()); + Assert.That(options.GetRouteToSpecificInstance(), Is.Null); } [Test] @@ -111,7 +111,7 @@ public void SendOptions_IsRoutingReplyToThisInstance_Should_Return_True_When_Rou options.RouteReplyToThisInstance(); - Assert.IsTrue(options.IsRoutingReplyToThisInstance()); + Assert.That(options.IsRoutingReplyToThisInstance(), Is.True); } [Test] @@ -119,7 +119,7 @@ public void SendOptions_IsRoutingReplyToThisInstance_Should_Return_False_When_No { var options = new SendOptions(); - Assert.IsFalse(options.IsRoutingReplyToThisInstance()); + Assert.That(options.IsRoutingReplyToThisInstance(), Is.False); } [Test] @@ -129,7 +129,7 @@ public void ReplyOptions_IsRoutingReplyToThisInstance_Should_Return_True_When_Ro options.RouteReplyToThisInstance(); - Assert.IsTrue(options.IsRoutingReplyToThisInstance()); + Assert.That(options.IsRoutingReplyToThisInstance(), Is.True); } [Test] @@ -137,7 +137,7 @@ public void ReplyOptions_IsRoutingReplyToThisInstance_Should_Return_False_When_N { var options = new ReplyOptions(); - Assert.IsFalse(options.IsRoutingReplyToThisInstance()); + Assert.That(options.IsRoutingReplyToThisInstance(), Is.False); } [Test] @@ -147,7 +147,7 @@ public void SendOptions_IsRoutingReplyToAnyInstance_Should_Return_True_When_Rout options.RouteReplyToAnyInstance(); - Assert.IsTrue(options.IsRoutingReplyToAnyInstance()); + Assert.That(options.IsRoutingReplyToAnyInstance(), Is.True); } [Test] @@ -155,7 +155,7 @@ public void SendOptions_IsRoutingReplyToAnyInstance_Should_Return_False_When_Not { var options = new SendOptions(); - Assert.IsFalse(options.IsRoutingReplyToAnyInstance()); + Assert.That(options.IsRoutingReplyToAnyInstance(), Is.False); } [Test] @@ -165,7 +165,7 @@ public void ReplyOptions_IsRoutingReplyToAnyInstance_Should_Return_True_When_Rou options.RouteReplyToAnyInstance(); - Assert.IsTrue(options.IsRoutingReplyToAnyInstance()); + Assert.That(options.IsRoutingReplyToAnyInstance(), Is.True); } [Test] @@ -173,7 +173,7 @@ public void ReplyOptions_IsRoutingReplyToAnyInstance_Should_Return_False_When_No { var options = new ReplyOptions(); - Assert.IsFalse(options.IsRoutingReplyToAnyInstance()); + Assert.That(options.IsRoutingReplyToAnyInstance(), Is.False); } [Test] @@ -184,7 +184,7 @@ public void ReplyOptions_GetReplyToRoute_Should_Return_Configured_Reply_Route() options.RouteReplyTo(expectedReplyToAddress); - Assert.AreEqual(expectedReplyToAddress, options.GetReplyToRoute()); + Assert.That(options.GetReplyToRoute(), Is.EqualTo(expectedReplyToAddress)); } [Test] @@ -192,7 +192,7 @@ public void ReplyOptions_GetReplyToRoute_Should_Return_Null_When_No_Route_Config { var options = new ReplyOptions(); - Assert.IsNull(options.GetReplyToRoute()); + Assert.That(options.GetReplyToRoute(), Is.Null); } [Test] @@ -203,7 +203,7 @@ public void SendOptions_GetReplyToRoute_Should_Return_Configured_Reply_Route() options.RouteReplyTo(expectedReplyToAddress); - Assert.AreEqual(expectedReplyToAddress, options.GetReplyToRoute()); + Assert.That(options.GetReplyToRoute(), Is.EqualTo(expectedReplyToAddress)); } [Test] @@ -211,6 +211,6 @@ public void SendOptions_GetReplyToRoute_Should_Return_Null_When_No_Route_Configu { var options = new SendOptions(); - Assert.IsNull(options.GetReplyToRoute()); + Assert.That(options.GetReplyToRoute(), Is.Null); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Routing/RoutingSettingsTests.cs b/src/NServiceBus.Core.Tests/Routing/RoutingSettingsTests.cs index 88759accfeb..46d07b75c51 100644 --- a/src/NServiceBus.Core.Tests/Routing/RoutingSettingsTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/RoutingSettingsTests.cs @@ -29,7 +29,7 @@ public void WhenPassingTransportAddressForSenderInsteadOfEndpointName_ShouldThro var expectedExceptionMessage = expectedExceptionMessageForWrongEndpointName; var exception = Assert.Throws(() => routingSettings.RouteToEndpoint(typeof(MessageWithoutNamespace), "EndpointName@MyHost")); - Assert.AreEqual(expectedExceptionMessage, exception.Message); + Assert.That(exception.Message, Is.EqualTo(expectedExceptionMessage)); } [Test] @@ -39,7 +39,7 @@ public void WhenPassingTransportAddressForSenderInsteadOfEndpointName_UsingAssem var expectedExceptionMessage = expectedExceptionMessageForWrongEndpointName; var exception = Assert.Throws(() => routingSettings.RouteToEndpoint(Assembly.GetExecutingAssembly(), "EndpointName@MyHost")); - Assert.AreEqual(expectedExceptionMessage, exception.Message); + Assert.That(exception.Message, Is.EqualTo(expectedExceptionMessage)); } [Test] @@ -49,7 +49,7 @@ public void WhenPassingTransportAddressForSenderInsteadOfEndpointName_UsingAssem var expectedExceptionMessage = expectedExceptionMessageForWrongEndpointName; var exception = Assert.Throws(() => routingSettings.RouteToEndpoint(Assembly.GetExecutingAssembly(), nameof(MessageNamespaceA), "EndpointName@MyHost")); - Assert.AreEqual(expectedExceptionMessage, exception.Message); + Assert.That(exception.Message, Is.EqualTo(expectedExceptionMessage)); } [Test] @@ -77,9 +77,12 @@ public void WhenRoutingAssemblyToEndpoint_ShouldConfigureAllContainedMessagesInR var otherMessageRoute = routingTable.GetRouteFor(typeof(OtherMessageType)); var messageWithoutNamespaceRoute = routingTable.GetRouteFor(typeof(MessageWithoutNamespace)); - Assert.That(someMessageRoute, Is.Not.Null); - Assert.That(otherMessageRoute, Is.Not.Null); - Assert.That(messageWithoutNamespaceRoute, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(someMessageRoute, Is.Not.Null); + Assert.That(otherMessageRoute, Is.Not.Null); + Assert.That(messageWithoutNamespaceRoute, Is.Not.Null); + }); } [Test] @@ -94,9 +97,12 @@ public void WhenRoutingAssemblyWithNamespaceToEndpoint_ShouldOnlyConfigureMessag var otherMessageRoute = routingTable.GetRouteFor(typeof(OtherMessageType)); var messageWithoutNamespaceRoute = routingTable.GetRouteFor(typeof(MessageWithoutNamespace)); - Assert.That(someMessageRoute, Is.Not.Null, "because SomeMessageType is in the given namespace"); - Assert.That(otherMessageRoute, Is.Null, "because OtherMessageType is not in the given namespace"); - Assert.That(messageWithoutNamespaceRoute, Is.Null, "because MessageWithoutNamespace is not in the given namespace"); + Assert.Multiple(() => + { + Assert.That(someMessageRoute, Is.Not.Null, "because SomeMessageType is in the given namespace"); + Assert.That(otherMessageRoute, Is.Null, "because OtherMessageType is not in the given namespace"); + Assert.That(messageWithoutNamespaceRoute, Is.Null, "because MessageWithoutNamespace is not in the given namespace"); + }); } [Theory] @@ -113,9 +119,12 @@ public void WhenRoutingAssemblyWithNamespaceToEndpointAndSpecifyingEmptyNamespac var otherMessageRoute = routingTable.GetRouteFor(typeof(OtherMessageType)); var messageWithoutNamespaceRoute = routingTable.GetRouteFor(typeof(MessageWithoutNamespace)); - Assert.That(someMessageRoute, Is.Null); - Assert.That(otherMessageRoute, Is.Null); - Assert.That(messageWithoutNamespaceRoute, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(someMessageRoute, Is.Null); + Assert.That(otherMessageRoute, Is.Null); + Assert.That(messageWithoutNamespaceRoute, Is.Not.Null); + }); } static UnicastRoutingTable ApplyConfiguredRoutes(RoutingSettings routingSettings) diff --git a/src/NServiceBus.Core.Tests/Routing/RoutingToDispatchConnectorTests.cs b/src/NServiceBus.Core.Tests/Routing/RoutingToDispatchConnectorTests.cs index 4416dd9353f..c9c4f86175a 100644 --- a/src/NServiceBus.Core.Tests/Routing/RoutingToDispatchConnectorTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/RoutingToDispatchConnectorTests.cs @@ -39,11 +39,14 @@ await behavior.Invoke(testableRoutingContext, context => return Task.CompletedTask; }); - Assert.That(operations, Has.Length.EqualTo(1)); + Assert.That(operations.ToList(), Has.Count.EqualTo(1)); TransportOperation destination1Operation = operations.ElementAt(0); - Assert.That(destination1Operation.Message.MessageId, Is.EqualTo("ID")); - Assert.That((destination1Operation.AddressTag as UnicastAddressTag)?.Destination, Is.EqualTo("destination1")); + Assert.Multiple(() => + { + Assert.That(destination1Operation.Message.MessageId, Is.EqualTo("ID")); + Assert.That((destination1Operation.AddressTag as UnicastAddressTag)?.Destination, Is.EqualTo("destination1")); + }); Dictionary destination1Headers = destination1Operation.Message.Headers; Assert.That(destination1Headers, Contains.Item(new KeyValuePair("SomeHeaderKey", "SomeHeaderValue"))); Assert.That(destination1Headers, Contains.Item(new KeyValuePair("HeaderKeyAddedByTheRoutingStrategy1", "HeaderValueAddedByTheRoutingStrategy1"))); @@ -79,11 +82,14 @@ await behavior.Invoke(testableRoutingContext, context => return Task.CompletedTask; }); - Assert.That(operations, Has.Length.EqualTo(2)); + Assert.That(operations.ToList(), Has.Count.EqualTo(2)); TransportOperation destination1Operation = operations.ElementAt(0); - Assert.That(destination1Operation.Message.MessageId, Is.EqualTo("ID")); - Assert.That((destination1Operation.AddressTag as UnicastAddressTag)?.Destination, Is.EqualTo("destination1")); + Assert.Multiple(() => + { + Assert.That(destination1Operation.Message.MessageId, Is.EqualTo("ID")); + Assert.That((destination1Operation.AddressTag as UnicastAddressTag)?.Destination, Is.EqualTo("destination1")); + }); Dictionary destination1Headers = destination1Operation.Message.Headers; Assert.That(destination1Headers, Contains.Item(new KeyValuePair("SomeHeaderKey", "SomeHeaderValue"))); Assert.That(destination1Headers, Contains.Item(new KeyValuePair("HeaderKeyAddedByTheRoutingStrategy1", "HeaderValueAddedByTheRoutingStrategy1"))); @@ -94,8 +100,11 @@ await behavior.Invoke(testableRoutingContext, context => Assert.That(destination1DispatchProperties, Is.Not.SameAs(originalDispatchProperties)); TransportOperation destination2Operation = operations.ElementAt(1); - Assert.That(destination2Operation.Message.MessageId, Is.EqualTo("ID")); - Assert.That((destination2Operation.AddressTag as UnicastAddressTag)?.Destination, Is.EqualTo("destination2")); + Assert.Multiple(() => + { + Assert.That(destination2Operation.Message.MessageId, Is.EqualTo("ID")); + Assert.That((destination2Operation.AddressTag as UnicastAddressTag)?.Destination, Is.EqualTo("destination2")); + }); Dictionary destination2Headers = destination2Operation.Message.Headers; Assert.That(destination2Headers, Contains.Item(new KeyValuePair("SomeHeaderKey", "SomeHeaderValue"))); Assert.That(destination2Headers, Contains.Item(new KeyValuePair("HeaderKeyAddedByTheRoutingStrategy2", "HeaderValueAddedByTheRoutingStrategy2"))); @@ -103,10 +112,13 @@ await behavior.Invoke(testableRoutingContext, context => Assert.That(destination2Headers, Is.Not.SameAs(originalHeaders)); DispatchProperties destination2DispatchProperties = destination2Operation.Properties; Assert.That(destination2DispatchProperties, Is.Not.SameAs(originalDispatchProperties)); - Assert.That(destination2DispatchProperties, Contains.Item(new KeyValuePair("SomeKey", "SomeValue"))); + Assert.Multiple(() => + { + Assert.That(destination2DispatchProperties, Contains.Item(new KeyValuePair("SomeKey", "SomeValue"))); - Assert.That(destination1Headers, Is.Not.SameAs(destination2Headers)); - Assert.That(destination1DispatchProperties, Is.Not.SameAs(destination2DispatchProperties)); + Assert.That(destination1Headers, Is.Not.SameAs(destination2Headers)); + Assert.That(destination1DispatchProperties, Is.Not.SameAs(destination2DispatchProperties)); + }); } [Test] @@ -120,7 +132,7 @@ await behavior.Invoke(new TestableRoutingContext { RoutingStrategies = [new Head return Task.CompletedTask; }); - Assert.IsTrue(headers.ContainsKey("CustomHeader")); + Assert.That(headers.ContainsKey("CustomHeader"), Is.True); } [Test] @@ -140,7 +152,7 @@ await behavior.Invoke(new RoutingContext(message, return Task.CompletedTask; }); - Assert.IsTrue(dispatched); + Assert.That(dispatched, Is.True); } [Test] @@ -157,7 +169,7 @@ await behavior.Invoke(new RoutingContext(message, return Task.CompletedTask; }); - Assert.IsTrue(dispatched); + Assert.That(dispatched, Is.True); } [Test] @@ -174,7 +186,7 @@ await behavior.Invoke(new RoutingContext(message, return Task.CompletedTask; }); - Assert.IsFalse(dispatched); + Assert.That(dispatched, Is.False); } [Test] @@ -192,9 +204,12 @@ public async Task Should_promote_message_headers_to_pipeline_activity() await behavior.Invoke(routingContext, _ => Task.CompletedTask); var contentTypeTag = pipelineActivity.GetTagItem(ActivityTags.ContentType); - Assert.AreEqual("test content type", contentTypeTag, "should set tags on activity from pipeline context"); + Assert.Multiple(() => + { + Assert.That(contentTypeTag, Is.EqualTo("test content type"), "should set tags on activity from pipeline context"); - Assert.IsNull(ambientActivity.GetTagItem(ActivityTags.ContentType), "should not set tags on Activity.Current"); + Assert.That(ambientActivity.GetTagItem(ActivityTags.ContentType), Is.Null, "should not set tags on Activity.Current"); + }); } static OutgoingSendContext CreateContext(SendOptions options, bool fromHandler) diff --git a/src/NServiceBus.Core.Tests/Routing/SubscribeContextTests.cs b/src/NServiceBus.Core.Tests/Routing/SubscribeContextTests.cs index 1f2bc130759..4c44d19ec9b 100644 --- a/src/NServiceBus.Core.Tests/Routing/SubscribeContextTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/SubscribeContextTests.cs @@ -17,12 +17,18 @@ public void ShouldShallowCloneContextBag() testee.Extensions.Set("someKey", "updatedValue"); testee.Extensions.Set("anotherKey", "anotherValue"); context.TryGet("someKey", out string value); - Assert.AreEqual("someValue", value); - Assert.IsFalse(context.TryGet("anotherKey", out string _)); + Assert.Multiple(() => + { + Assert.That(value, Is.EqualTo("someValue")); + Assert.That(context.TryGet("anotherKey", out string _), Is.False); + }); testee.Extensions.TryGet("someKey", out string updatedValue); testee.Extensions.TryGet("anotherKey", out string anotherValue2); - Assert.AreEqual("updatedValue", updatedValue); - Assert.AreEqual("anotherValue", anotherValue2); + Assert.Multiple(() => + { + Assert.That(updatedValue, Is.EqualTo("updatedValue")); + Assert.That(anotherValue2, Is.EqualTo("anotherValue")); + }); } [Test] @@ -37,7 +43,7 @@ public void ShouldNotMergeOptionsToParentContext() var valueFound = parentContext.TryGet("someKey", out string _); - Assert.IsFalse(valueFound); + Assert.That(valueFound, Is.False); } [Test] @@ -50,7 +56,7 @@ public void ShouldExposeSendOptionsExtensionsAsOperationProperties() var context = new SubscribeContext(parentContext, Type.EmptyTypes, options); var operationProperties = context.GetOperationProperties(); - Assert.AreEqual("some value", operationProperties.Get("some key")); + Assert.That(operationProperties.Get("some key"), Is.EqualTo("some value")); } [Test] @@ -67,13 +73,19 @@ public void ShouldNotLeakParentsOperationProperties() var innerContext = new SubscribeContext(parentContext, Type.EmptyTypes, innerOptions); var innerOperationProperties = innerContext.GetOperationProperties(); - Assert.AreEqual("inner value", innerOperationProperties.Get("inner key")); - Assert.AreEqual("inner shared value", innerOperationProperties.Get("shared key")); - Assert.IsFalse(innerOperationProperties.TryGet("outer key", out string _)); + Assert.Multiple(() => + { + Assert.That(innerOperationProperties.Get("inner key"), Is.EqualTo("inner value")); + Assert.That(innerOperationProperties.Get("shared key"), Is.EqualTo("inner shared value")); + Assert.That(innerOperationProperties.TryGet("outer key", out string _), Is.False); + }); var outerOperationProperties = parentContext.GetOperationProperties(); - Assert.AreEqual("outer value", outerOperationProperties.Get("outer key")); - Assert.AreEqual("outer shared value", outerOperationProperties.Get("shared key")); - Assert.IsFalse(outerOperationProperties.TryGet("inner key", out string _)); + Assert.Multiple(() => + { + Assert.That(outerOperationProperties.Get("outer key"), Is.EqualTo("outer value")); + Assert.That(outerOperationProperties.Get("shared key"), Is.EqualTo("outer shared value")); + Assert.That(outerOperationProperties.TryGet("inner key", out string _), Is.False); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Routing/UnicastPublisherRouterTests.cs b/src/NServiceBus.Core.Tests/Routing/UnicastPublisherRouterTests.cs index f690947d8d6..2a67fdd13c8 100644 --- a/src/NServiceBus.Core.Tests/Routing/UnicastPublisherRouterTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/UnicastPublisherRouterTests.cs @@ -35,9 +35,9 @@ public async Task When_subscriber_does_not_define_logical_endpoint_should_send_e var routes = await router.Route(typeof(Event), new DistributionPolicy(), new TestableOutgoingPublishContext()); var destinations = routes.Select(ExtractDestination).ToList(); - Assert.AreEqual(2, destinations.Count); - Assert.Contains("address1", destinations); - Assert.Contains("address2", destinations); + Assert.That(destinations.Count, Is.EqualTo(2)); + Assert.That(destinations, Does.Contain("address1")); + Assert.That(destinations, Does.Contain("address2")); } [Test] @@ -53,9 +53,9 @@ public async Task When_multiple_subscribers_for_logical_endpoints_should_route_e var routes = (await router.Route(typeof(Event), new DistributionPolicy(), new TestableOutgoingPublishContext())).ToArray(); var destinations = routes.Select(ExtractDestination).ToList(); - Assert.AreEqual(2, destinations.Count); - Assert.Contains("sales1", destinations); - Assert.Contains("shipping1", destinations); + Assert.That(destinations.Count, Is.EqualTo(2)); + Assert.That(destinations, Does.Contain("sales1")); + Assert.That(destinations, Does.Contain("shipping1")); } [Test] @@ -69,8 +69,11 @@ public async Task Should_not_route_multiple_copies_of_message_to_one_physical_de var routes = await router.Route(typeof(Event), new DistributionPolicy(), new TestableOutgoingPublishContext()); - Assert.AreEqual(1, routes.Count()); - Assert.AreEqual("address", ExtractDestination(routes.Single())); + Assert.Multiple(() => + { + Assert.That(routes.Count(), Is.EqualTo(1)); + Assert.That(ExtractDestination(routes.Single()), Is.EqualTo("address")); + }); } [Test] @@ -86,8 +89,11 @@ public async Task Should_not_route_events_to_configured_endpoint_instances() var routes = await router.Route(typeof(Event), new DistributionPolicy(), new TestableOutgoingPublishContext()); - Assert.AreEqual(1, routes.Count()); - Assert.AreEqual("address", ExtractDestination(routes.First())); + Assert.Multiple(() => + { + Assert.That(routes.Count(), Is.EqualTo(1)); + Assert.That(ExtractDestination(routes.First()), Is.EqualTo("address")); + }); } [Test] @@ -95,7 +101,7 @@ public async Task Should_return_empty_list_when_no_routes_found() { var routes = await router.Route(typeof(Event), new DistributionPolicy(), new TestableOutgoingPublishContext()); - Assert.IsEmpty(routes); + Assert.That(routes, Is.Empty); } [Test] @@ -105,8 +111,8 @@ public async Task When_no_subscribers_found_Should_log_at_debug_level() var warning = $"No subscribers found for the event of type {typeof(Event).FullName}."; - StringAssert.Contains(warning, logStatements.ToString()); - StringAssert.Contains(" DEBUG ", logStatements.ToString()); + Assert.That(logStatements.ToString(), Does.Contain(warning)); + Assert.That(logStatements.ToString(), Does.Contain(" DEBUG ")); } static string ExtractDestination(UnicastRoutingStrategy route) diff --git a/src/NServiceBus.Core.Tests/Routing/UnicastRoutingTableTests.cs b/src/NServiceBus.Core.Tests/Routing/UnicastRoutingTableTests.cs index 143f74ce631..73681216021 100644 --- a/src/NServiceBus.Core.Tests/Routing/UnicastRoutingTableTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/UnicastRoutingTableTests.cs @@ -18,7 +18,7 @@ public void When_group_does_not_exist_should_add_routes() ]); var retrievedRoute = routingTable.GetRouteFor(typeof(Command)); - Assert.AreSame(route, retrievedRoute); + Assert.That(retrievedRoute, Is.SameAs(route)); } [Test] @@ -38,7 +38,7 @@ public void When_group_exists_should_replace_existing_routes() ]); var retrievedRoute = routingTable.GetRouteFor(typeof(Command)); - Assert.AreSame(newRoute, retrievedRoute); + Assert.That(retrievedRoute, Is.SameAs(newRoute)); } [Test] diff --git a/src/NServiceBus.Core.Tests/Routing/UnsubscribeContextTests.cs b/src/NServiceBus.Core.Tests/Routing/UnsubscribeContextTests.cs index cf44382932d..11995635ff6 100644 --- a/src/NServiceBus.Core.Tests/Routing/UnsubscribeContextTests.cs +++ b/src/NServiceBus.Core.Tests/Routing/UnsubscribeContextTests.cs @@ -16,12 +16,18 @@ public void ShouldShallowCloneContext() testee.Extensions.Set("someKey", "updatedValue"); testee.Extensions.Set("anotherKey", "anotherValue"); context.TryGet("someKey", out string value); - Assert.AreEqual("someValue", value); - Assert.IsFalse(context.TryGet("anotherKey", out string _)); + Assert.Multiple(() => + { + Assert.That(value, Is.EqualTo("someValue")); + Assert.That(context.TryGet("anotherKey", out string _), Is.False); + }); testee.Extensions.TryGet("someKey", out string updatedValue); testee.Extensions.TryGet("anotherKey", out string anotherValue2); - Assert.AreEqual("updatedValue", updatedValue); - Assert.AreEqual("anotherValue", anotherValue2); + Assert.Multiple(() => + { + Assert.That(updatedValue, Is.EqualTo("updatedValue")); + Assert.That(anotherValue2, Is.EqualTo("anotherValue")); + }); } [Test] @@ -36,7 +42,7 @@ public void ShouldNotMergeOptionsToParentContext() var valueFound = parentContext.TryGet("someKey", out string _); - Assert.IsFalse(valueFound); + Assert.That(valueFound, Is.False); } [Test] @@ -49,7 +55,7 @@ public void ShouldExposeSendOptionsExtensionsAsOperationProperties() var context = new UnsubscribeContext(parentContext, typeof(object), options); var operationProperties = context.GetOperationProperties(); - Assert.AreEqual("some value", operationProperties.Get("some key")); + Assert.That(operationProperties.Get("some key"), Is.EqualTo("some value")); } [Test] @@ -66,13 +72,19 @@ public void ShouldNotLeakParentsOperationProperties() var innerContext = new UnsubscribeContext(parentContext, typeof(object), innerOptions); var innerOperationProperties = innerContext.GetOperationProperties(); - Assert.AreEqual("inner value", innerOperationProperties.Get("inner key")); - Assert.AreEqual("inner shared value", innerOperationProperties.Get("shared key")); - Assert.IsFalse(innerOperationProperties.TryGet("outer key", out string _)); + Assert.Multiple(() => + { + Assert.That(innerOperationProperties.Get("inner key"), Is.EqualTo("inner value")); + Assert.That(innerOperationProperties.Get("shared key"), Is.EqualTo("inner shared value")); + Assert.That(innerOperationProperties.TryGet("outer key", out string _), Is.False); + }); var outerOperationProperties = parentContext.GetOperationProperties(); - Assert.AreEqual("outer value", outerOperationProperties.Get("outer key")); - Assert.AreEqual("outer shared value", outerOperationProperties.Get("shared key")); - Assert.IsFalse(outerOperationProperties.TryGet("inner key", out string _)); + Assert.Multiple(() => + { + Assert.That(outerOperationProperties.Get("outer key"), Is.EqualTo("outer value")); + Assert.That(outerOperationProperties.Get("shared key"), Is.EqualTo("outer shared value")); + Assert.That(outerOperationProperties.TryGet("inner key", out string _), Is.False); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Sagas/InvokeSagaNotFoundBehaviorTests.cs b/src/NServiceBus.Core.Tests/Sagas/InvokeSagaNotFoundBehaviorTests.cs index c3695a3d191..3ff472cd29e 100644 --- a/src/NServiceBus.Core.Tests/Sagas/InvokeSagaNotFoundBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/Sagas/InvokeSagaNotFoundBehaviorTests.cs @@ -28,7 +28,7 @@ public void SagaNotFound_handlers_are_not_called_when_saga_is_found() Assert.That(async () => await behavior.Invoke(incomingContext, ctx => Task.CompletedTask), Throws.Nothing); - Assert.False(validSagaHandler.Handled); + Assert.That(validSagaHandler.Handled, Is.False); } [Test] diff --git a/src/NServiceBus.Core.Tests/Sagas/SagaMetadataCreationTests.cs b/src/NServiceBus.Core.Tests/Sagas/SagaMetadataCreationTests.cs index 2036ae07e76..cf4b1685f35 100644 --- a/src/NServiceBus.Core.Tests/Sagas/SagaMetadataCreationTests.cs +++ b/src/NServiceBus.Core.Tests/Sagas/SagaMetadataCreationTests.cs @@ -24,22 +24,25 @@ public void Throws_when_does_not_implement_generic_saga() public void GetEntityClrType() { var metadata = SagaMetadata.Create(typeof(MySaga)); - Assert.AreEqual(typeof(MySaga.MyEntity), metadata.SagaEntityType); + Assert.That(metadata.SagaEntityType, Is.EqualTo(typeof(MySaga.MyEntity))); } [Test] public void GetSagaClrType() { var metadata = SagaMetadata.Create(typeof(MySaga)); - Assert.AreEqual(typeof(MySaga), metadata.SagaType); + Assert.That(metadata.SagaType, Is.EqualTo(typeof(MySaga))); } [Test] public void DetectUniquePropertiesByAttribute() { var metadata = SagaMetadata.Create(typeof(MySaga)); - Assert.True(metadata.TryGetCorrelationProperty(out var correlatedProperty)); - Assert.AreEqual("UniqueProperty", correlatedProperty.Name); + Assert.Multiple(() => + { + Assert.That(metadata.TryGetCorrelationProperty(out var correlatedProperty), Is.True); + Assert.That(correlatedProperty.Name, Is.EqualTo("UniqueProperty")); + }); } [Test] @@ -50,7 +53,7 @@ public void When_finder_for_non_message() typeof(SagaWithNonMessageFinder.Finder) }; var exception = Assert.Throws(() => { SagaMetadata.Create(typeof(SagaWithNonMessageFinder), availableTypes, new Conventions()); }); - Assert.AreEqual("A custom ISagaFinder must target a valid message type as defined by the message conventions. Change 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaMetadataCreationTests+SagaWithNonMessageFinder+StartSagaMessage' to a valid message type or add it to the message conventions. Finder name 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaMetadataCreationTests+SagaWithNonMessageFinder+Finder'.", exception.Message); + Assert.That(exception.Message, Is.EqualTo("A custom ISagaFinder must target a valid message type as defined by the message conventions. Change 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaMetadataCreationTests+SagaWithNonMessageFinder+StartSagaMessage' to a valid message type or add it to the message conventions. Finder name 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaMetadataCreationTests+SagaWithNonMessageFinder+Finder'.")); } [Test] @@ -61,8 +64,8 @@ public void When_message_only_has_custom_finder() typeof(SagaWithFinderOnly.Finder) }; var metadata = SagaMetadata.Create(typeof(SagaWithFinderOnly), availableTypes, new Conventions()); - Assert.AreEqual(1, metadata.Finders.Count); - Assert.AreEqual(typeof(CustomFinderAdapter), metadata.Finders.First().Type); + Assert.That(metadata.Finders.Count, Is.EqualTo(1)); + Assert.That(metadata.Finders.First().Type, Is.EqualTo(typeof(CustomFinderAdapter))); } [Test] @@ -73,15 +76,18 @@ public void When_a_finder_and_a_mapping_exists_for_same_property() typeof(SagaWithMappingAndFinder.Finder) }; var exception = Assert.Throws(() => { SagaMetadata.Create(typeof(SagaWithMappingAndFinder), availableTypes, new Conventions()); }); - Assert.AreEqual("A custom ISagaFinder and an existing mapping where found for message 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaMetadataCreationTests+SagaWithMappingAndFinder+StartSagaMessage'. Either remove the message mapping or remove the finder. Finder name 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaMetadataCreationTests+SagaWithMappingAndFinder+Finder'.", exception.Message); + Assert.That(exception.Message, Is.EqualTo("A custom ISagaFinder and an existing mapping where found for message 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaMetadataCreationTests+SagaWithMappingAndFinder+StartSagaMessage'. Either remove the message mapping or remove the finder. Finder name 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaMetadataCreationTests+SagaWithMappingAndFinder+Finder'.")); } [Test] public void HandleBothUniqueAttributeAndMapping() { var metadata = SagaMetadata.Create(typeof(MySagaWithMappedAndUniqueProperty)); - Assert.True(metadata.TryGetCorrelationProperty(out var correlatedProperty)); - Assert.AreEqual("UniqueProperty", correlatedProperty.Name); + Assert.Multiple(() => + { + Assert.That(metadata.TryGetCorrelationProperty(out var correlatedProperty), Is.True); + Assert.That(correlatedProperty.Name, Is.EqualTo("UniqueProperty")); + }); } [TestCase(typeof(MySagaWithMappedProperty))] @@ -89,8 +95,11 @@ public void HandleBothUniqueAttributeAndMapping() public void AutomaticallyAddUniqueForMappedProperties(Type sagaType) { var metadata = SagaMetadata.Create(sagaType); - Assert.True(metadata.TryGetCorrelationProperty(out var correlatedProperty)); - Assert.AreEqual("UniqueProperty", correlatedProperty.Name); + Assert.Multiple(() => + { + Assert.That(metadata.TryGetCorrelationProperty(out var correlatedProperty), Is.True); + Assert.That(correlatedProperty.Name, Is.EqualTo("UniqueProperty")); + }); } [Test] @@ -98,7 +107,7 @@ public void AutomaticallyAddUniqueForMappedProperties(Type sagaType) public void RequireFinderForMessagesStartingTheSaga() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(MySagaWithUnmappedStartProperty))); - Assert.True(ex.Message.Contains(typeof(MySagaWithUnmappedStartProperty.MessageThatStartsTheSaga).FullName)); + Assert.That(ex.Message, Does.Contain(typeof(MySagaWithUnmappedStartProperty.MessageThatStartsTheSaga).FullName)); } [Test] @@ -106,7 +115,7 @@ public void HandleNonExistingFinders() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(MySagaWithUnmappedStartProperty))); - Assert.That(ex.Message.Contains("mapper.ConfigureMapping")); + Assert.That(ex.Message, Does.Contain("mapper.ConfigureMapping")); } [Test] @@ -116,15 +125,18 @@ public void DetectMessagesStartingTheSaga() var messages = metadata.AssociatedMessages; - Assert.AreEqual(4, messages.Count); + Assert.Multiple(() => + { + Assert.That(messages.Count, Is.EqualTo(4)); - Assert.True(metadata.IsMessageAllowedToStartTheSaga(typeof(SagaWith2StartersAnd1Handler.StartMessage1).FullName)); + Assert.That(metadata.IsMessageAllowedToStartTheSaga(typeof(SagaWith2StartersAnd1Handler.StartMessage1).FullName), Is.True); - Assert.True(metadata.IsMessageAllowedToStartTheSaga(typeof(SagaWith2StartersAnd1Handler.StartMessage2).FullName)); + Assert.That(metadata.IsMessageAllowedToStartTheSaga(typeof(SagaWith2StartersAnd1Handler.StartMessage2).FullName), Is.True); - Assert.False(metadata.IsMessageAllowedToStartTheSaga(typeof(SagaWith2StartersAnd1Handler.Message3).FullName)); + Assert.That(metadata.IsMessageAllowedToStartTheSaga(typeof(SagaWith2StartersAnd1Handler.Message3).FullName), Is.False); - Assert.False(metadata.IsMessageAllowedToStartTheSaga(typeof(SagaWith2StartersAnd1Handler.MyTimeout).FullName)); + Assert.That(metadata.IsMessageAllowedToStartTheSaga(typeof(SagaWith2StartersAnd1Handler.MyTimeout).FullName), Is.False); + }); } [Test] @@ -134,9 +146,12 @@ public void DetectAndRegisterPropertyFinders() var finder = GetFinder(metadata, typeof(SomeMessage).FullName); - Assert.AreEqual(typeof(PropertySagaFinder), finder.Type); - Assert.NotNull(finder.Properties["property-accessor"]); - Assert.AreEqual("UniqueProperty", finder.Properties["saga-property-name"]); + Assert.Multiple(() => + { + Assert.That(finder.Type, Is.EqualTo(typeof(PropertySagaFinder))); + Assert.That(finder.Properties["property-accessor"], Is.Not.Null); + Assert.That(finder.Properties["saga-property-name"], Is.EqualTo("UniqueProperty")); + }); } [Test] @@ -146,45 +161,48 @@ public void DetectAndRegisterHeaderFinders() var finder = GetFinder(metadata, typeof(SomeMessage).FullName); - Assert.AreEqual(typeof(HeaderPropertySagaFinder), finder.Type); - Assert.AreEqual("CorrelationHeader", finder.Properties["message-header-name"]); - Assert.AreEqual("UniqueProperty", finder.Properties["saga-property-name"]); - Assert.AreEqual(typeof(int), finder.Properties["saga-property-type"]); + Assert.Multiple(() => + { + Assert.That(finder.Type, Is.EqualTo(typeof(HeaderPropertySagaFinder))); + Assert.That(finder.Properties["message-header-name"], Is.EqualTo("CorrelationHeader")); + Assert.That(finder.Properties["saga-property-name"], Is.EqualTo("UniqueProperty")); + Assert.That(finder.Properties["saga-property-type"], Is.EqualTo(typeof(int))); + }); } [Test] public void ValidateThatMappingOnSagaIdHasTypeGuidForMessageProps() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(SagaWithIdMappedToNonGuidMessageProperty))); - StringAssert.Contains(typeof(SomeMessage).FullName, ex.Message); + Assert.That(ex.Message, Does.Contain(typeof(SomeMessage).FullName)); } [Test] public void ValidateThatMappingOnSagaIdFromStringToGuidForMessagePropsThrowsException() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(SagaWithIdMappedToStringMessageProperty))); - StringAssert.Contains(typeof(SomeMessage).FullName, ex.Message); + Assert.That(ex.Message, Does.Contain(typeof(SomeMessage).FullName)); } [Test] public void ValidateThatMappingOnNonSagaIdGuidPropertyFromStringToGuidForMessagePropsThrowsException() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(SagaWithNonIdPropertyMappedToStringMessageProperty))); - StringAssert.Contains(typeof(SomeMessage).FullName, ex.Message); + Assert.That(ex.Message, Does.Contain(typeof(SomeMessage).FullName)); } [Test] public void ValidateThatMappingOnSagaIdHasTypeGuidForMessageFields() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(SagaWithIdMappedToNonGuidMessageField))); - StringAssert.Contains(nameof(SomeMessage), ex.Message); + Assert.That(ex.Message, Does.Contain(nameof(SomeMessage))); } [Test] public void ValidateThatSagaPropertyIsNotAField() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(SagaWithSagaDataMemberAsFieldInsteadOfProperty))); - StringAssert.Contains(typeof(SagaWithSagaDataMemberAsFieldInsteadOfProperty.SagaData).FullName, ex.Message); + Assert.That(ex.Message, Does.Contain(typeof(SagaWithSagaDataMemberAsFieldInsteadOfProperty.SagaData).FullName)); } [Test] @@ -198,8 +216,11 @@ public void DetectAndRegisterCustomFindersUsingScanning() var finder = GetFinder(metadata, typeof(SomeMessage).FullName); - Assert.AreEqual(typeof(CustomFinderAdapter), finder.Type); - Assert.AreEqual(typeof(MySagaWithScannedFinder.CustomFinder), finder.Properties["custom-finder-clr-type"]); + Assert.Multiple(() => + { + Assert.That(finder.Type, Is.EqualTo(typeof(CustomFinderAdapter))); + Assert.That(finder.Properties["custom-finder-clr-type"], Is.EqualTo(typeof(MySagaWithScannedFinder.CustomFinder))); + }); } [TestCase(typeof(SagaThatMapsMessageItDoesntHandle))] @@ -228,7 +249,7 @@ public void GetEntityClrTypeFromInheritanceChain() { var metadata = SagaMetadata.Create(typeof(SagaWithInheritanceChain)); - Assert.AreEqual(typeof(SagaWithInheritanceChain.SagaData), metadata.SagaEntityType); + Assert.That(metadata.SagaEntityType, Is.EqualTo(typeof(SagaWithInheritanceChain.SagaData))); } static SagaFinderDefinition GetFinder(SagaMetadata metadata, string messageType) diff --git a/src/NServiceBus.Core.Tests/Sagas/SagaModelTests.cs b/src/NServiceBus.Core.Tests/Sagas/SagaModelTests.cs index 02580e7eec6..4e5f611744f 100644 --- a/src/NServiceBus.Core.Tests/Sagas/SagaModelTests.cs +++ b/src/NServiceBus.Core.Tests/Sagas/SagaModelTests.cs @@ -25,7 +25,7 @@ public void FindSagasByName() var metadata = model.Find(typeof(MySaga)); - Assert.NotNull(metadata); + Assert.That(metadata, Is.Not.Null); } [Test] @@ -36,7 +36,7 @@ public void FindSagasByEntityName() var metadata = model.FindByEntity(typeof(MyEntity)); - Assert.NotNull(metadata); + Assert.That(metadata, Is.Not.Null); } [Test] @@ -46,23 +46,32 @@ public void ValidateAssumptionsAboutSagaMappings() var metadata = model.Find(typeof(MySaga)); - Assert.NotNull(metadata); + Assert.That(metadata, Is.Not.Null); - Assert.AreEqual(typeof(MyEntity), metadata.SagaEntityType); - Assert.AreEqual(typeof(MyEntity).FullName, metadata.EntityName); - Assert.AreEqual(typeof(MySaga), metadata.SagaType); - Assert.AreEqual(typeof(MySaga).FullName, metadata.Name); - - Assert.AreEqual(2, metadata.AssociatedMessages.Count); - Assert.AreEqual(1, metadata.AssociatedMessages.Count(am => am.MessageTypeName == typeof(Message1).FullName && am.IsAllowedToStartSaga)); - Assert.AreEqual(1, metadata.AssociatedMessages.Count(am => am.MessageTypeName == typeof(Message2).FullName && !am.IsAllowedToStartSaga)); + Assert.Multiple(() => + { + Assert.That(metadata.SagaEntityType, Is.EqualTo(typeof(MyEntity))); + Assert.That(metadata.EntityName, Is.EqualTo(typeof(MyEntity).FullName)); + Assert.That(metadata.SagaType, Is.EqualTo(typeof(MySaga))); + Assert.That(metadata.Name, Is.EqualTo(typeof(MySaga).FullName)); + + Assert.That(metadata.AssociatedMessages.Count, Is.EqualTo(2)); + }); + Assert.Multiple(() => + { + Assert.That(metadata.AssociatedMessages.Count(am => am.MessageTypeName == typeof(Message1).FullName && am.IsAllowedToStartSaga), Is.EqualTo(1)); + Assert.That(metadata.AssociatedMessages.Count(am => am.MessageTypeName == typeof(Message2).FullName && !am.IsAllowedToStartSaga), Is.EqualTo(1)); - Assert.True(metadata.TryGetCorrelationProperty(out var correlatedProperty)); - Assert.AreEqual("UniqueProperty", correlatedProperty.Name); + Assert.That(metadata.TryGetCorrelationProperty(out var correlatedProperty), Is.True); + Assert.That(correlatedProperty.Name, Is.EqualTo("UniqueProperty")); - Assert.AreEqual(2, metadata.Finders.Count); - Assert.AreEqual(1, metadata.Finders.Count(f => f.MessageType == typeof(Message1))); - Assert.AreEqual(1, metadata.Finders.Count(f => f.MessageType == typeof(Message2))); + Assert.That(metadata.Finders.Count, Is.EqualTo(2)); + }); + Assert.Multiple(() => + { + Assert.That(metadata.Finders.Count(f => f.MessageType == typeof(Message1)), Is.EqualTo(1)); + Assert.That(metadata.Finders.Count(f => f.MessageType == typeof(Message2)), Is.EqualTo(1)); + }); } [Test] @@ -80,8 +89,11 @@ public void ValidateHeaderBasedSagaMappingsSetCorrelationProperty() var metadata = model.Find(typeof(MyHeaderMappedSaga)); - Assert.That(metadata.TryGetCorrelationProperty(out var correlatedProperty), Is.True); - Assert.That(correlatedProperty.Name, Is.EqualTo("UniqueProperty")); + Assert.Multiple(() => + { + Assert.That(metadata.TryGetCorrelationProperty(out var correlatedProperty), Is.True); + Assert.That(correlatedProperty.Name, Is.EqualTo("UniqueProperty")); + }); } [Test] @@ -93,7 +105,7 @@ public void ValidateIfSagaEntityIsShared() const string expectedExceptionMessage = "Best practice violation: Multiple saga types are sharing the same saga state which can result in persisters to physically share the same storage structure.\n\n- Entity 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaModelTests+MyEntity' used by saga types 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaModelTests+MySaga' and 'NServiceBus.Core.Tests.Sagas.TypeBasedSagas.SagaModelTests+MySaga2'."; - Assert.AreEqual(expectedExceptionMessage, ex.Message); + Assert.That(ex.Message, Is.EqualTo(expectedExceptionMessage)); } class MyHeaderMappedSaga : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.Core.Tests/Sagas/When_saga_has_no_start_message.cs b/src/NServiceBus.Core.Tests/Sagas/When_saga_has_no_start_message.cs index 8ecefc43087..fd0618b2e17 100644 --- a/src/NServiceBus.Core.Tests/Sagas/When_saga_has_no_start_message.cs +++ b/src/NServiceBus.Core.Tests/Sagas/When_saga_has_no_start_message.cs @@ -14,7 +14,7 @@ public void Should_throw() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(SagaWithNoStartMessage), [], new Conventions())); - StringAssert.Contains("Sagas must have at least one message that is allowed to start the saga", ex.Message); + Assert.That(ex.Message, Does.Contain("Sagas must have at least one message that is allowed to start the saga")); } class SagaWithNoStartMessage : Saga, IHandleMessages diff --git a/src/NServiceBus.Core.Tests/Sagas/When_saga_is_correlated_on_a_unsupported_datetime_property_type.cs b/src/NServiceBus.Core.Tests/Sagas/When_saga_is_correlated_on_a_unsupported_datetime_property_type.cs index 08616bf7192..72fa1a9277d 100644 --- a/src/NServiceBus.Core.Tests/Sagas/When_saga_is_correlated_on_a_unsupported_datetime_property_type.cs +++ b/src/NServiceBus.Core.Tests/Sagas/When_saga_is_correlated_on_a_unsupported_datetime_property_type.cs @@ -14,7 +14,7 @@ public void Should_throw() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(SagaWithNoStartMessage), [], new Conventions())); - StringAssert.Contains("DateTime is not supported for correlated properties", ex.Message); + Assert.That(ex.Message, Does.Contain("DateTime is not supported for correlated properties")); } class SagaWithNoStartMessage : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.Core.Tests/Sagas/When_saga_is_correlated_on_a_unsupported_datetimeoffset_property_type.cs b/src/NServiceBus.Core.Tests/Sagas/When_saga_is_correlated_on_a_unsupported_datetimeoffset_property_type.cs index 108d70eb9a3..f641e02018f 100644 --- a/src/NServiceBus.Core.Tests/Sagas/When_saga_is_correlated_on_a_unsupported_datetimeoffset_property_type.cs +++ b/src/NServiceBus.Core.Tests/Sagas/When_saga_is_correlated_on_a_unsupported_datetimeoffset_property_type.cs @@ -14,7 +14,7 @@ public void Should_throw() { var ex = Assert.Throws(() => SagaMetadata.Create(typeof(SagaWithNoStartMessage), [], new Conventions())); - StringAssert.Contains("DateTimeOffset is not supported for correlated properties", ex.Message); + Assert.That(ex.Message, Does.Contain("DateTimeOffset is not supported for correlated properties")); } class SagaWithNoStartMessage : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.Core.Tests/Serializers/MessageDeserializerResolverTests.cs b/src/NServiceBus.Core.Tests/Serializers/MessageDeserializerResolverTests.cs index 426bff0f4f9..b0b951ea6ff 100644 --- a/src/NServiceBus.Core.Tests/Serializers/MessageDeserializerResolverTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/MessageDeserializerResolverTests.cs @@ -26,7 +26,7 @@ public void RetrievesSerializerByContentType(string contentType) {Headers.ContentType, contentType} }; var serializer = resolver.Resolve(headers); - Assert.AreSame(expectedResolver, serializer); + Assert.That(serializer, Is.SameAs(expectedResolver)); } [Test] @@ -44,7 +44,7 @@ public void UnknownContentTypeFallsBackToDefaultSerialization() }; var serializer = resolver.Resolve(headers); - Assert.AreSame(mainSerializer, serializer); + Assert.That(serializer, Is.SameAs(mainSerializer)); } [Test] @@ -58,7 +58,7 @@ public void NoContentTypeFallsBackToDefaultSerialization() var serializer = resolver.Resolve([]); - Assert.AreEqual(mainSerializer, serializer); + Assert.That(serializer, Is.EqualTo(mainSerializer)); } [TestCase(null)] @@ -76,7 +76,7 @@ public void EmptyContentTypeFallsBackToDefaultSerialization(string headerValue) { Headers.ContentType, headerValue} }); - Assert.AreEqual(mainSerializer, serializer); + Assert.That(serializer, Is.EqualTo(mainSerializer)); } [Test] diff --git a/src/NServiceBus.Core.Tests/Serializers/SystemTextJson/SystemJsonSerializerTests.cs b/src/NServiceBus.Core.Tests/Serializers/SystemTextJson/SystemJsonSerializerTests.cs index 2c057e02fb1..33699b3a407 100644 --- a/src/NServiceBus.Core.Tests/Serializers/SystemTextJson/SystemJsonSerializerTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/SystemTextJson/SystemJsonSerializerTests.cs @@ -97,22 +97,25 @@ public void Test() Assert.That(result[0], Is.TypeOf(typeof(A))); var a = (A)result[0]; - Assert.AreEqual(obj.Data, a.Data); - Assert.AreEqual(23, a.I); - Assert.AreEqual("Foo", a.S); - Assert.AreEqual(expectedDate.Kind, a.DateTime.Kind); - Assert.AreEqual(expectedDate, a.DateTime); - Assert.AreEqual(expectedDateLocal.Kind, a.DateTimeLocal.Kind); - Assert.AreEqual(expectedDateLocal, a.DateTimeLocal); - Assert.AreEqual(expectedDateUtc.Kind, a.DateTimeUtc.Kind); - Assert.AreEqual(expectedDateUtc, a.DateTimeUtc); - Assert.That(a.Bs[0].C, Is.TypeOf(typeof(JsonElement))); - Assert.AreEqual("ccc", ((JsonElement)a.Bs[0].C).GetProperty("Cstr").GetString()); - - Assert.AreEqual(expectedGuid, a.AGuid); - - Assert.IsInstanceOf(a.Bs[0]); - Assert.IsNotInstanceOf(a.Bs[1]); + Assert.Multiple(() => + { + Assert.That(a.Data, Is.EqualTo(obj.Data)); + Assert.That(a.I, Is.EqualTo(23)); + Assert.That(a.S, Is.EqualTo("Foo")); + Assert.That(a.DateTime.Kind, Is.EqualTo(expectedDate.Kind)); + Assert.That(a.DateTime, Is.EqualTo(expectedDate)); + Assert.That(a.DateTimeLocal.Kind, Is.EqualTo(expectedDateLocal.Kind)); + Assert.That(a.DateTimeLocal, Is.EqualTo(expectedDateLocal)); + Assert.That(a.DateTimeUtc.Kind, Is.EqualTo(expectedDateUtc.Kind)); + Assert.That(a.DateTimeUtc, Is.EqualTo(expectedDateUtc)); + Assert.That(a.Bs[0].C, Is.TypeOf(typeof(JsonElement))); + Assert.That(((JsonElement)a.Bs[0].C).GetProperty("Cstr").GetString(), Is.EqualTo("ccc")); + + Assert.That(a.AGuid, Is.EqualTo(expectedGuid)); + + Assert.That(a.Bs[0], Is.InstanceOf()); + Assert.That(a.Bs[1], Is.Not.InstanceOf()); + }); } [Test] @@ -162,19 +165,25 @@ public void TestInterfaces() Assert.DoesNotThrow(() => output.Position = 0, "Stream should still be open"); - Assert.IsNotEmpty(result); + Assert.That(result, Is.Not.Empty); Assert.That(result, Has.Length.EqualTo(1)); Assert.That(result[0], Is.AssignableTo(typeof(IA))); var a = (IA)result[0]; - Assert.AreEqual(a.Data, obj.Data); - Assert.AreEqual(42, a.I); - Assert.AreEqual("kalle", a.S); - Assert.IsNotNull(a.B); - Assert.AreEqual("BOO", a.B.BString); - Assert.That(a.B.C, Is.TypeOf(typeof(JsonElement))); - Assert.AreEqual("COO", ((JsonElement)a.B.C).GetProperty("Cstr").GetString()); + Assert.Multiple(() => + { + Assert.That(obj.Data, Is.EqualTo(a.Data)); + Assert.That(a.I, Is.EqualTo(42)); + Assert.That(a.S, Is.EqualTo("kalle")); + Assert.That(a.B, Is.Not.Null); + }); + Assert.Multiple(() => + { + Assert.That(a.B.BString, Is.EqualTo("BOO")); + Assert.That(a.B.C, Is.TypeOf(typeof(JsonElement))); + Assert.That(((JsonElement)a.B.C).GetProperty("Cstr").GetString(), Is.EqualTo("COO")); + }); } @@ -207,19 +216,28 @@ public void Should_preserve_timezones() typeof(DateTimeMessage) ]).Cast().Single(); - Assert.AreEqual(expectedDateTime.Kind, result.DateTime.Kind); - Assert.AreEqual(expectedDateTime, result.DateTime); - Assert.AreEqual(expectedDateTimeLocal.Kind, result.DateTimeLocal.Kind); - Assert.AreEqual(expectedDateTimeLocal, result.DateTimeLocal); - Assert.AreEqual(expectedDateTimeUtc.Kind, result.DateTimeUtc.Kind); - Assert.AreEqual(expectedDateTimeUtc, result.DateTimeUtc); - - Assert.AreEqual(expectedDateTimeOffset, result.DateTimeOffset); - Assert.AreEqual(expectedDateTimeOffset.Offset, result.DateTimeOffset.Offset); - Assert.AreEqual(expectedDateTimeOffsetLocal, result.DateTimeOffsetLocal); - Assert.AreEqual(expectedDateTimeOffsetLocal.Offset, result.DateTimeOffsetLocal.Offset); - Assert.AreEqual(expectedDateTimeOffsetUtc, result.DateTimeOffsetUtc); - Assert.AreEqual(expectedDateTimeOffsetUtc.Offset, result.DateTimeOffsetUtc.Offset); + Assert.Multiple(() => + { + Assert.That(result.DateTime.Kind, Is.EqualTo(expectedDateTime.Kind)); + Assert.That(result.DateTime, Is.EqualTo(expectedDateTime)); + Assert.That(result.DateTimeLocal.Kind, Is.EqualTo(expectedDateTimeLocal.Kind)); + Assert.That(result.DateTimeLocal, Is.EqualTo(expectedDateTimeLocal)); + Assert.That(result.DateTimeUtc.Kind, Is.EqualTo(expectedDateTimeUtc.Kind)); + Assert.That(result.DateTimeUtc, Is.EqualTo(expectedDateTimeUtc)); + + Assert.That(result.DateTimeOffset, Is.EqualTo(expectedDateTimeOffset)); + }); + Assert.Multiple(() => + { + Assert.That(result.DateTimeOffset.Offset, Is.EqualTo(expectedDateTimeOffset.Offset)); + Assert.That(result.DateTimeOffsetLocal, Is.EqualTo(expectedDateTimeOffsetLocal)); + }); + Assert.Multiple(() => + { + Assert.That(result.DateTimeOffsetLocal.Offset, Is.EqualTo(expectedDateTimeOffsetLocal.Offset)); + Assert.That(result.DateTimeOffsetUtc, Is.EqualTo(expectedDateTimeOffsetUtc)); + }); + Assert.That(result.DateTimeOffsetUtc.Offset, Is.EqualTo(expectedDateTimeOffsetUtc.Offset)); } [Test] diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/ConcurrencySerializerTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/ConcurrencySerializerTests.cs index 9269ebac164..decc6b8a79e 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/ConcurrencySerializerTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/ConcurrencySerializerTests.cs @@ -31,8 +31,11 @@ public void Should_deserialize_in_parallel() result = (RequestDataMessage)msgArray[0]; } - Assert.AreEqual(expected.DataId, result.DataId); - Assert.AreEqual(expected.String, result.String); + Assert.Multiple(() => + { + Assert.That(result.DataId, Is.EqualTo(expected.DataId)); + Assert.That(result.String, Is.EqualTo(expected.String)); + }); }); } } diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/DictionaryTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/DictionaryTests.cs index f3e13ac8fa4..8fb2630bb22 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/DictionaryTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/DictionaryTests.cs @@ -104,21 +104,21 @@ public void Should_deserialize_dictionaries() var result = ExecuteSerializer.ForMessage(expected); - CollectionAssert.AreEqual(expected.Bools, result.Bools); - CollectionAssert.AreEqual(expected.Chars, result.Chars); - CollectionAssert.AreEqual(expected.Bytes, result.Bytes); - CollectionAssert.AreEqual(expected.Ints, result.Ints); - CollectionAssert.AreEqual(expected.Decimals, result.Decimals); - CollectionAssert.AreEqual(expected.Doubles, result.Doubles); - CollectionAssert.AreEqual(expected.Floats, result.Floats); - CollectionAssert.AreEqual(expected.Enums, result.Enums); - CollectionAssert.AreEqual(expected.Longs, result.Longs); - CollectionAssert.AreEqual(expected.SBytes, result.SBytes); - CollectionAssert.AreEqual(expected.Shorts, result.Shorts); - CollectionAssert.AreEqual(expected.Strings, result.Strings); - CollectionAssert.AreEqual(expected.UInts, result.UInts); - CollectionAssert.AreEqual(expected.ULongs, result.ULongs); - CollectionAssert.AreEqual(expected.UShorts, result.UShorts); + Assert.That(result.Bools, Is.EqualTo(expected.Bools).AsCollection); + Assert.That(result.Chars, Is.EqualTo(expected.Chars).AsCollection); + Assert.That(result.Bytes, Is.EqualTo(expected.Bytes).AsCollection); + Assert.That(result.Ints, Is.EqualTo(expected.Ints).AsCollection); + Assert.That(result.Decimals, Is.EqualTo(expected.Decimals).AsCollection); + Assert.That(result.Doubles, Is.EqualTo(expected.Doubles).AsCollection); + Assert.That(result.Floats, Is.EqualTo(expected.Floats).AsCollection); + Assert.That(result.Enums, Is.EqualTo(expected.Enums).AsCollection); + Assert.That(result.Longs, Is.EqualTo(expected.Longs).AsCollection); + Assert.That(result.SBytes, Is.EqualTo(expected.SBytes).AsCollection); + Assert.That(result.Shorts, Is.EqualTo(expected.Shorts).AsCollection); + Assert.That(result.Strings, Is.EqualTo(expected.Strings).AsCollection); + Assert.That(result.UInts, Is.EqualTo(expected.UInts).AsCollection); + Assert.That(result.ULongs, Is.EqualTo(expected.ULongs).AsCollection); + Assert.That(result.UShorts, Is.EqualTo(expected.UShorts).AsCollection); } } diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/Issue_934.cs b/src/NServiceBus.Core.Tests/Serializers/XML/Issue_934.cs index ad8a481b86d..6bab7017bf4 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/Issue_934.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/Issue_934.cs @@ -27,8 +27,11 @@ public void Serialize_ShouldSucceed_WhenCharContainsXmlSpecialCharacters() messageDeserialized = serializer.Deserialize(stream.ToArray(), new[] { message.GetType() }); } - Assert.AreEqual(message.InvalidCharacter, ((TestMessageWithChar)messageDeserialized[0]).InvalidCharacter); - Assert.AreEqual(message.ValidCharacter, ((TestMessageWithChar)messageDeserialized[0]).ValidCharacter); + Assert.Multiple(() => + { + Assert.That(((TestMessageWithChar)messageDeserialized[0]).InvalidCharacter, Is.EqualTo(message.InvalidCharacter)); + Assert.That(((TestMessageWithChar)messageDeserialized[0]).ValidCharacter, Is.EqualTo(message.ValidCharacter)); + }); } public class TestMessageWithChar : IMessage diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/ListTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/ListTests.cs index d9f191bfd7d..f274a93858a 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/ListTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/ListTests.cs @@ -40,21 +40,21 @@ public void Should_deserialize_list() var result = ExecuteSerializer.ForMessage(expected); - CollectionAssert.AreEqual(expected.Bools, result.Bools); - CollectionAssert.AreEqual(expected.Chars, result.Chars); - CollectionAssert.AreEqual(expected.Bytes, result.Bytes); - CollectionAssert.AreEqual(expected.Ints, result.Ints); - CollectionAssert.AreEqual(expected.Decimals, result.Decimals); - CollectionAssert.AreEqual(expected.Doubles, result.Doubles); - CollectionAssert.AreEqual(expected.Floats, result.Floats); - CollectionAssert.AreEqual(expected.Enums, result.Enums); - CollectionAssert.AreEqual(expected.Longs, result.Longs); - CollectionAssert.AreEqual(expected.SBytes, result.SBytes); - CollectionAssert.AreEqual(expected.Shorts, result.Shorts); - CollectionAssert.AreEqual(expected.Strings, result.Strings); - CollectionAssert.AreEqual(expected.UInts, result.UInts); - CollectionAssert.AreEqual(expected.ULongs, result.ULongs); - CollectionAssert.AreEqual(expected.UShorts, result.UShorts); + Assert.That(result.Bools, Is.EqualTo(expected.Bools).AsCollection); + Assert.That(result.Chars, Is.EqualTo(expected.Chars).AsCollection); + Assert.That(result.Bytes, Is.EqualTo(expected.Bytes).AsCollection); + Assert.That(result.Ints, Is.EqualTo(expected.Ints).AsCollection); + Assert.That(result.Decimals, Is.EqualTo(expected.Decimals).AsCollection); + Assert.That(result.Doubles, Is.EqualTo(expected.Doubles).AsCollection); + Assert.That(result.Floats, Is.EqualTo(expected.Floats).AsCollection); + Assert.That(result.Enums, Is.EqualTo(expected.Enums).AsCollection); + Assert.That(result.Longs, Is.EqualTo(expected.Longs).AsCollection); + Assert.That(result.SBytes, Is.EqualTo(expected.SBytes).AsCollection); + Assert.That(result.Shorts, Is.EqualTo(expected.Shorts).AsCollection); + Assert.That(result.Strings, Is.EqualTo(expected.Strings).AsCollection); + Assert.That(result.UInts, Is.EqualTo(expected.UInts).AsCollection); + Assert.That(result.ULongs, Is.EqualTo(expected.ULongs).AsCollection); + Assert.That(result.UShorts, Is.EqualTo(expected.UShorts).AsCollection); } } diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/Pull_819.cs b/src/NServiceBus.Core.Tests/Serializers/XML/Pull_819.cs index 4a007163912..b84710b29af 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/Pull_819.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/Pull_819.cs @@ -19,7 +19,7 @@ public void Should_check_for_ignore_attribute_before_checking_type() m3.GenericList = []; }); - Assert.AreEqual("John", result.FirstName); + Assert.That(result.FirstName, Is.EqualTo("John")); } public class MessageWithXmlIgnore : MessageWithXmlIgnoreBase diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/SerializerTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/SerializerTests.cs index 813e730b965..7990f2aceb6 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/SerializerTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/SerializerTests.cs @@ -42,7 +42,7 @@ public void SerializeInvalidCharacters() var msgArray = serializer.Deserialize(stream.ToArray()); var m = (MessageWithInvalidCharacter)msgArray[0]; - Assert.AreEqual(sb.ToString(), m.Special); + Assert.That(m.Special, Is.EqualTo(sb.ToString())); } } @@ -60,7 +60,7 @@ public void Limitation_Does_not_handle_types_implementing_ISerializable() var result = (MessageImplementingISerializable)serializer.Deserialize(stream.ToArray())[0]; - Assert.Null(result.ReadOnlyProperty); + Assert.That(result.ReadOnlyProperty, Is.Null); } } @@ -82,8 +82,11 @@ public void Should_handle_struct_message() var result = (StructMessage)serializer.Deserialize(stream.ToArray())[0]; - Assert.AreEqual(message.SomeField, result.SomeField); - Assert.AreEqual(message.SomeProperty, result.SomeProperty); + Assert.Multiple(() => + { + Assert.That(result.SomeField, Is.EqualTo(message.SomeField)); + Assert.That(result.SomeProperty, Is.EqualTo(message.SomeProperty)); + }); } } @@ -101,7 +104,7 @@ public void Limitation_Does_not_handle_message_with_struct_property() var ex = Assert.Throws(() => serializer.Deserialize(stream.ToArray())); - StringAssert.StartsWith("Type not supported by the serializer", ex.Message); + Assert.That(ex.Message, Does.StartWith("Type not supported by the serializer")); } } @@ -146,7 +149,7 @@ public void Should_handle_concrete_message_with_interface_property() var result = (MessageWithInterfaceProperty)serializer.Deserialize(stream.ToArray())[0]; - Assert.AreEqual(message.InterfaceProperty.SomeProperty, result.InterfaceProperty.SomeProperty); + Assert.That(result.InterfaceProperty.SomeProperty, Is.EqualTo(message.InterfaceProperty.SomeProperty)); } } @@ -173,7 +176,7 @@ public void Should_handle_interface_message_with_interface_property() typeof(IMessageWithInterfaceProperty) })[0]; - Assert.AreEqual(message.InterfaceProperty.SomeProperty, result.InterfaceProperty.SomeProperty); + Assert.That(result.InterfaceProperty.SomeProperty, Is.EqualTo(message.InterfaceProperty.SomeProperty)); } } @@ -189,7 +192,7 @@ public void Should_deserialize_arrayList() }; var result = ExecuteSerializer.ForMessage(m3 => m3.ArrayList = expected); - CollectionAssert.AreEqual(expected, result.ArrayList); + Assert.That(result.ArrayList, Is.EqualTo(expected).AsCollection); } [Test] @@ -204,7 +207,7 @@ public void Should_deserialize_hashtable() }; var result = ExecuteSerializer.ForMessage(m3 => m3.Hashtable = expected); - CollectionAssert.AreEqual(expected, result.Hashtable); + Assert.That(result.Hashtable, Is.EqualTo(expected).AsCollection); } [Test] @@ -232,8 +235,11 @@ public void Should_deserialize_multiple_messages_from_different_namespaces() stream.Position = 0; var msgArray = SerializerFactory.Create(typeof(Command1), typeof(Command2)).Deserialize(stream.ToArray()); - Assert.AreEqual(typeof(Command1), msgArray[0].GetType()); - Assert.AreEqual(typeof(Command2), msgArray[1].GetType()); + Assert.Multiple(() => + { + Assert.That(msgArray[0].GetType(), Is.EqualTo(typeof(Command1))); + Assert.That(msgArray[1].GetType(), Is.EqualTo(typeof(Command2))); + }); } } @@ -249,7 +255,7 @@ public void Should_infer_message_type_from_root_node_if_type_is_known() var msgArray = SerializerFactory.Create(typeof(MessageWithDouble)).Deserialize(stream.ToArray()); - Assert.AreEqual(typeof(MessageWithDouble), msgArray[0].GetType()); + Assert.That(msgArray[0].GetType(), Is.EqualTo(typeof(MessageWithDouble))); } } @@ -278,8 +284,11 @@ public void Deserialize_private_message_with_two_unrelated_interface_without_wra }); var a = (IMyEventA)result[0]; var b = (IMyEventB)result[1]; - Assert.AreEqual(42, b.IntValue); - Assert.AreEqual("Answer", a.StringValue); + Assert.Multiple(() => + { + Assert.That(b.IntValue, Is.EqualTo(42)); + Assert.That(a.StringValue, Is.EqualTo("Answer")); + }); } } @@ -340,8 +349,8 @@ public void Should_deserialize_messages_where_xml_raw_data_root_element_matches_ var msg = serializer.Deserialize(stream.ToArray()).Cast().Single(); - Assert.NotNull(msg.Document); - Assert.AreEqual("Document", msg.Document.Root.Name.LocalName); + Assert.That(msg.Document, Is.Not.Null); + Assert.That(msg.Document.Root.Name.LocalName, Is.EqualTo("Document")); } serializer = SerializerFactory.Create(); @@ -357,8 +366,8 @@ public void Should_deserialize_messages_where_xml_raw_data_root_element_matches_ var msg = serializer.Deserialize(stream.ToArray()).Cast().Single(); - Assert.NotNull(msg.Document); - Assert.AreEqual("Document", msg.Document.Name.LocalName); + Assert.That(msg.Document, Is.Not.Null); + Assert.That(msg.Document.Name.LocalName, Is.EqualTo("Document")); } } @@ -375,7 +384,7 @@ public void Should_be_able_to_serialize_single_message_with_default_namespaces_a var msgArray = SerializerFactory.Create(typeof(MessageWithDouble)).Deserialize(stream.ToArray()); - Assert.AreEqual(typeof(MessageWithDouble), msgArray[0].GetType()); + Assert.That(msgArray[0].GetType(), Is.EqualTo(typeof(MessageWithDouble))); } } @@ -427,7 +436,7 @@ static void AssertSerializedEquals(XmlMessageSerializer serializer, IMessage msg result = XDocument.Load(reader).ToString(); } - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } } @@ -446,7 +455,7 @@ public void Should_deserialize_a_single_message_with_typeName_passed_in_external typeof(MessageWithDouble) }); - Assert.AreEqual(typeof(MessageWithDouble), msgArray[0].GetType()); + Assert.That(msgArray[0].GetType(), Is.EqualTo(typeof(MessageWithDouble))); } } @@ -466,7 +475,7 @@ public void Should_deserialize_a_single_message_with_typeName_passed_in_external typeof(MessageWithDouble) }); - Assert.AreEqual(23.4, ((MessageWithDouble)msgArray[0]).Double); + Assert.That(((MessageWithDouble)msgArray[0]).Double, Is.EqualTo(23.4)); } } @@ -487,8 +496,11 @@ public void Should_deserialize_a_batched_messages_with_typeName_passed_in_extern typeof(EmptyMessage) }); - Assert.AreEqual(23.4, ((MessageWithDouble)msgArray[0]).Double); - Assert.AreEqual(typeof(EmptyMessage), msgArray[1].GetType()); + Assert.Multiple(() => + { + Assert.That(((MessageWithDouble)msgArray[0]).Double, Is.EqualTo(23.4)); + Assert.That(msgArray[1].GetType(), Is.EqualTo(typeof(EmptyMessage))); + }); } } @@ -509,8 +521,11 @@ public void Should_deserialize_a_batched_messages_with_typeName_passed_in_extern typeof(EmptyMessage) }); - Assert.AreEqual(23.4, ((MessageWithDouble)msgArray[0]).Double); - Assert.AreEqual(typeof(EmptyMessage), msgArray[1].GetType()); + Assert.Multiple(() => + { + Assert.That(((MessageWithDouble)msgArray[0]).Double, Is.EqualTo(23.4)); + Assert.That(msgArray[1].GetType(), Is.EqualTo(typeof(EmptyMessage))); + }); } } @@ -537,7 +552,7 @@ public void TestMultipleInterfacesDuplicatedProperty() } } } - Assert.AreEqual(count, 1); + Assert.That(count, Is.EqualTo(1)); } @@ -553,7 +568,7 @@ public void Generic_properties_should_be_supported() }; }); - Assert.AreEqual("a property", result.GenericProperty.WhatEver); + Assert.That(result.GenericProperty.WhatEver, Is.EqualTo("a property")); } @@ -578,7 +593,7 @@ public void Culture() var msgArray = serializer.Deserialize(stream.ToArray()); var m = (MessageWithDouble)msgArray[0]; - Assert.AreEqual(val, m.Double); + Assert.That(m.Double, Is.EqualTo(val)); stream.Dispose(); } @@ -824,7 +839,7 @@ public void SerializeLists() var msgArray = serializer.Deserialize(stream.ToArray()); var m = (MessageWithList)msgArray[0]; - Assert.AreEqual("Hello", m.Items.First().Data); + Assert.That(m.Items.First().Data, Is.EqualTo("Hello")); } } @@ -850,7 +865,7 @@ public void SerializeClosedGenericListsInAlternateNamespace() var msgArray = serializer.Deserialize(stream.ToArray()); var m = (MessageWithClosedListInAlternateNamespace)msgArray[0]; - Assert.AreEqual("Hello", m.Items.First().Data); + Assert.That(m.Items.First().Data, Is.EqualTo("Hello")); } } @@ -878,7 +893,7 @@ public void SerializeClosedGenericListsInAlternateNamespaceMultipleIEnumerableIm var msgArray = serializer.Deserialize(stream.ToArray()); var m = (MessageWithClosedListInAlternateNamespaceMultipleIEnumerableImplementations)msgArray[0]; - Assert.AreEqual("Hello", m.Items.First().Data); + Assert.That(m.Items.First().Data, Is.EqualTo("Hello")); } } @@ -904,7 +919,7 @@ public void SerializeClosedGenericListsInAlternateNamespaceMultipleIListImplemen var msgArray = serializer.Deserialize(stream.ToArray()); var m = (MessageWithClosedListInAlternateNamespaceMultipleIListImplementations)msgArray[0]; - Assert.AreEqual("Hello", m.Items.First().Data); + Assert.That(m.Items.First().Data, Is.EqualTo("Hello")); } } @@ -930,7 +945,7 @@ public void SerializeClosedGenericListsInSameNamespace() var msgArray = serializer.Deserialize(stream.ToArray()); var m = (MessageWithClosedList)msgArray[0]; - Assert.AreEqual("Hello", m.Items.First().Data); + Assert.That(m.Items.First().Data, Is.EqualTo("Hello")); } } @@ -950,7 +965,7 @@ public void SerializeEmptyLists() var msgArray = serializer.Deserialize(stream.ToArray()); var m = (MessageWithList)msgArray[0]; - Assert.IsEmpty(m.Items); + Assert.That(m.Items, Is.Empty); } } @@ -1065,7 +1080,7 @@ void Time(object message, XmlMessageSerializer serializer) public void NestedObjectWithNullPropertiesShouldBeSerialized() { var result = ExecuteSerializer.ForMessage(m => { m.NestedObject = new MessageWithNullProperty(); }); - Assert.IsNotNull(result.NestedObject); + Assert.That(result.NestedObject, Is.Not.Null); } [Test] @@ -1082,7 +1097,7 @@ public void Messages_with_generic_properties_closing_nullables_should_be_support }; m.Whatever = "fdsfsdfsd"; }); - Assert.IsNotNull(result.GenericNullable.TheType == theTime); + Assert.That(result.GenericNullable.TheType, Is.EqualTo(theTime)); } [Test] @@ -1110,11 +1125,14 @@ public void System_classes_with_non_default_constructors_should_be_supported() var result = ExecuteSerializer.ForMessage( m => { m.MailMessage = message; }); - Assert.IsNotNull(result.MailMessage); - Assert.AreEqual("from@gmail.com", result.MailMessage.From.Address); - Assert.AreEqual(message.To.First(), result.MailMessage.To.First()); - Assert.AreEqual(message.BodyEncoding.CodePage, result.MailMessage.BodyEncoding.CodePage); - Assert.AreEqual(message.BodyEncoding.EncoderFallback.MaxCharCount, result.MailMessage.BodyEncoding.EncoderFallback.MaxCharCount); + Assert.That(result.MailMessage, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(result.MailMessage.From.Address, Is.EqualTo("from@gmail.com")); + Assert.That(result.MailMessage.To.First(), Is.EqualTo(message.To.First())); + Assert.That(result.MailMessage.BodyEncoding.CodePage, Is.EqualTo(message.BodyEncoding.CodePage)); + Assert.That(result.MailMessage.BodyEncoding.EncoderFallback.MaxCharCount, Is.EqualTo(message.BodyEncoding.EncoderFallback.MaxCharCount)); + }); } [Test] @@ -1132,9 +1150,12 @@ public void Messages_with_polymorphic_properties_should_be_supported() var result = ExecuteSerializer.ForMessage(message); - Assert.AreEqual(message.BaseType.BaseTypeProp, result.BaseType.BaseTypeProp); + Assert.Multiple(() => + { + Assert.That(result.BaseType.BaseTypeProp, Is.EqualTo(message.BaseType.BaseTypeProp)); - Assert.AreEqual(((ChildOfBase)message.BaseType).ChildProp, ((ChildOfBase)result.BaseType).ChildProp); + Assert.That(((ChildOfBase)result.BaseType).ChildProp, Is.EqualTo(((ChildOfBase)message.BaseType).ChildProp)); + }); } [Test] @@ -1155,8 +1176,11 @@ public void When_Using_Property_WithXContainerAssignable_should_preserve_xml() var resultXDocument = ExecuteSerializer.ForMessage(messageWithXDocument); var resultXElement = ExecuteSerializer.ForMessage(messageWithXElement); - Assert.AreEqual(messageWithXDocument.Document.ToString(), resultXDocument.Document.ToString()); - Assert.AreEqual(messageWithXElement.Document.ToString(), resultXElement.Document.ToString()); + Assert.Multiple(() => + { + Assert.That(resultXDocument.Document.ToString(), Is.EqualTo(messageWithXDocument.Document.ToString())); + Assert.That(resultXElement.Document.ToString(), Is.EqualTo(messageWithXElement.Document.ToString())); + }); } [Test] @@ -1183,7 +1207,7 @@ public void Should_be_able_to_deserialize_many_messages_of_same_type() { typeof(EmptyMessage) }); - Assert.AreEqual(3, msgArray.Length); + Assert.That(msgArray, Has.Length.EqualTo(3)); } } @@ -1211,8 +1235,11 @@ public void Object_property_with_primitive_or_struct_value_should_serialize_corr }); } - Assert.AreEqual(message.Key, ((SerializedPair)messageDeserialized[0]).Key); - Assert.AreEqual(message.Value, ((SerializedPair)messageDeserialized[0]).Value); + Assert.Multiple(() => + { + Assert.That(((SerializedPair)messageDeserialized[0]).Key, Is.EqualTo(message.Key)); + Assert.That(((SerializedPair)messageDeserialized[0]).Value, Is.EqualTo(message.Value)); + }); } [Test] diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/SerializingArrayTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/SerializingArrayTests.cs index 8d7ef90c891..ff953518ce5 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/SerializingArrayTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/SerializingArrayTests.cs @@ -56,13 +56,13 @@ public void CanDeserializeXmlWithWhitespace() var messages = serializer.Deserialize(data); - Assert.NotNull(messages); + Assert.That(messages, Is.Not.Null); Assert.That(messages, Has.Length.EqualTo(1)); Assert.That(messages[0], Is.TypeOf(typeof(MessageWithArray))); var m = (MessageWithArray)messages[0]; - Assert.IsNotNull(m.SomeInts); + Assert.That(m.SomeInts, Is.Not.Null); Assert.That(m.SomeInts, Has.Length.EqualTo(1)); } @@ -73,10 +73,13 @@ public void CanSerializeAndBack() var result = ExecuteSerializer.ForMessage(message); - Assert.IsNotNull(result.SomeInts); + Assert.That(result.SomeInts, Is.Not.Null); Assert.That(result.SomeInts, Has.Length.EqualTo(2)); - Assert.AreEqual(1234, result.SomeInts[0]); - Assert.AreEqual(5323, result.SomeInts[1]); + Assert.Multiple(() => + { + Assert.That(result.SomeInts[0], Is.EqualTo(1234)); + Assert.That(result.SomeInts[1], Is.EqualTo(5323)); + }); } [Test] @@ -89,7 +92,7 @@ public void CanSerializeMessageWithNullArray() var result = ExecuteSerializer.ForMessage(message); - Assert.IsNull(result.SomeWords); + Assert.That(result.SomeWords, Is.Null); } [Test] @@ -102,7 +105,7 @@ public void CanSerializeMessageWithEmptyArray() var result = ExecuteSerializer.ForMessage(message); - Assert.AreEqual(result.SomeWords, Array.Empty()); + Assert.That(Array.Empty(), Is.EqualTo(result.SomeWords)); } [Test] @@ -131,7 +134,7 @@ public void CanSerializeNullableArrayWithNullString() "); var actual = XDocument.Parse(xml); - Assert.AreEqual(expected.ToString(), actual.ToString()); + Assert.That(actual.ToString(), Is.EqualTo(expected.ToString())); } } @@ -151,7 +154,7 @@ public void CanDeserializeNullableArrayWithValueSetToNullString() var msgArray = SerializerFactory.Create().Deserialize(data, new[] { typeof(MessageWithNullableArray) }); var result = (MessageWithNullableArray)msgArray[0]; - Assert.AreEqual(null, result.SomeInts[0]); + Assert.That(result.SomeInts[0], Is.EqualTo(null)); } [Test] @@ -170,7 +173,7 @@ public void CanDeserializeNullableArrayWithFirstEntryXsiNilAttributeSetToTrue() var msgArray = SerializerFactory.Create().Deserialize(data, new[] { typeof(MessageWithNullableArray) }); var result = (MessageWithNullableArray)msgArray[0]; - Assert.AreEqual(null, result.SomeInts[0]); + Assert.That(result.SomeInts[0], Is.EqualTo(null)); } [Test] @@ -188,7 +191,7 @@ public void CanDeserializeNullableArrayWithXsiNilAttributeSetToTrue() var msgArray = SerializerFactory.Create().Deserialize(data, new[] { typeof(MessageWithNullableArray) }); var result = (MessageWithNullableArray)msgArray[0]; - Assert.IsFalse(result.SomeInts.Length != 0); + Assert.That(result.SomeInts.Length, Is.EqualTo(0)); } [Test] @@ -206,8 +209,8 @@ public void CanDeserializeNullableArrayWithNoElementsToEmptyList() var msgArray = SerializerFactory.Create().Deserialize(data, new[] { typeof(MessageWithNullableArray) }); var result = (MessageWithNullableArray)msgArray[0]; - Assert.NotNull(result.SomeInts); - Assert.AreEqual(0, result.SomeInts.Length); + Assert.That(result.SomeInts, Is.Not.Null); + Assert.That(result.SomeInts.Length, Is.EqualTo(0)); } [Test] @@ -227,7 +230,7 @@ public void CanDeserializeNullableArrayWithValueSetToEmptyString() var msgArray = SerializerFactory.Create().Deserialize(data, new[] { typeof(MessageWithNullableArray) }); var result = (MessageWithNullableArray)msgArray[0]; - Assert.AreEqual(null, result.SomeInts[0]); + Assert.That(result.SomeInts[0], Is.EqualTo(null)); } [Test] @@ -241,10 +244,13 @@ public void CanSerializeMessageWithNullableArray() var result = ExecuteSerializer.ForMessage(message); - Assert.IsNull(result.SomeInts[0]); - Assert.AreEqual(1, result.SomeInts[1]); - Assert.IsNull(result.SomeInts[2]); - Assert.AreEqual(3, result.SomeInts[3]); - Assert.IsNull(result.SomeInts[4]); + Assert.Multiple(() => + { + Assert.That(result.SomeInts[0], Is.Null); + Assert.That(result.SomeInts[1], Is.EqualTo(1)); + Assert.That(result.SomeInts[2], Is.Null); + Assert.That(result.SomeInts[3], Is.EqualTo(3)); + Assert.That(result.SomeInts[4], Is.Null); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/SerializingEnumerableTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/SerializingEnumerableTests.cs index 618bbce4604..523aa291867 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/SerializingEnumerableTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/SerializingEnumerableTests.cs @@ -30,7 +30,7 @@ public void CanSerializeNullElements() }; var result = ExecuteSerializer.ForMessage(message); - Assert.IsNotNull(result.SomeStrings); - Assert.AreEqual(4, result.SomeStrings.Count()); + Assert.That(result.SomeStrings, Is.Not.Null); + Assert.That(result.SomeStrings.Count(), Is.EqualTo(4)); } } diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/SerializingGenericTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/SerializingGenericTests.cs index a460bdd7270..4f4a042f90f 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/SerializingGenericTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/SerializingGenericTests.cs @@ -30,7 +30,10 @@ public void CanSerializeAndBack() var result = ExecuteSerializer.ForMessage>(message); - Assert.AreEqual(1234, result.Data1); - Assert.AreEqual("Lorem ipsum", result.Data2); + Assert.Multiple(() => + { + Assert.That(result.Data1, Is.EqualTo(1234)); + Assert.That(result.Data2, Is.EqualTo("Lorem ipsum")); + }); } } diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/SerializingNullableTypesTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/SerializingNullableTypesTests.cs index 32386d9e2d8..f29920da0c7 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/SerializingNullableTypesTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/SerializingNullableTypesTests.cs @@ -48,7 +48,7 @@ public void NullableTypesSerializeToXsiNilWhenNull() "); var actual = XDocument.Parse(xml); - Assert.AreEqual(expected.ToString(), actual.ToString()); + Assert.That(actual.ToString(), Is.EqualTo(expected.ToString())); } } @@ -80,7 +80,7 @@ public void NullableTypeSerializeToValueWhenNotNull() "); var actual = XDocument.Parse(xml); - Assert.AreEqual(expected.ToString(), actual.ToString()); + Assert.That(actual.ToString(), Is.EqualTo(expected.ToString())); } } @@ -101,7 +101,7 @@ public void CanDeserializeNilMessage() var msgArray = SerializerFactory.Create().Deserialize(data, new[] { typeof(MessageWithNullable) }); var result = (MessageWithNullable)msgArray[0]; - Assert.AreEqual(null, result.BirthDate); + Assert.That(result.BirthDate, Is.EqualTo(null)); } [Test] @@ -121,6 +121,6 @@ public void CanDeserializeOriginalNullValueMessage() var msgArray = SerializerFactory.Create().Deserialize(data, new[] { typeof(MessageWithNullable) }); var result = (MessageWithNullable)msgArray[0]; - Assert.AreEqual(null, result.BirthDate); + Assert.That(result.BirthDate, Is.EqualTo(null)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/UriTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/UriTests.cs index e9e8118d50a..4f731360140 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/UriTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/UriTests.cs @@ -16,7 +16,7 @@ public void Should_support() m3.Href = expected; }); - Assert.AreEqual(expected, result.Href); + Assert.That(result.Href, Is.EqualTo(expected)); } public class MessageWithUri : ICommand diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/Using_Infer_Type_With_Mixed_Namespace.cs b/src/NServiceBus.Core.Tests/Serializers/XML/Using_Infer_Type_With_Mixed_Namespace.cs index 3b39703f5a4..7cf7464d430 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/Using_Infer_Type_With_Mixed_Namespace.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/Using_Infer_Type_With_Mixed_Namespace.cs @@ -31,8 +31,11 @@ public void Execute() var serializer = SerializerFactory.Create(typeof(IMyBusMessage), typeof(Namespace1.FirstMessage), typeof(Namespace2.FirstMessage)); var messageDeserialized = serializer.Deserialize(stream.ToArray()); - Assert.IsInstanceOf(messageDeserialized[0]); - Assert.IsInstanceOf(messageDeserialized[1]); + Assert.Multiple(() => + { + Assert.That(messageDeserialized[0], Is.InstanceOf()); + Assert.That(messageDeserialized[1], Is.InstanceOf()); + }); } } } diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/Using_Infer_Type_With_Non_Nested_Class.cs b/src/NServiceBus.Core.Tests/Serializers/XML/Using_Infer_Type_With_Non_Nested_Class.cs index 5e9747e9a6f..aeae439912e 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/Using_Infer_Type_With_Non_Nested_Class.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/Using_Infer_Type_With_Non_Nested_Class.cs @@ -26,10 +26,13 @@ public void Should_deserialize_when_message_type_pre_discovered() { var serializer = SerializerFactory.Create(typeof(IMyBusMessage), typeof(FirstMessage), typeof(SecondMessage)); var messageDeserialized = serializer.Deserialize(StringToByteArray(XmlWithBaseType)); - Assert.IsInstanceOf(messageDeserialized[0]); - Assert.IsInstanceOf(messageDeserialized[1]); - Assert.IsInstanceOf(messageDeserialized[2]); - Assert.IsInstanceOf(messageDeserialized[3]); + Assert.Multiple(() => + { + Assert.That(messageDeserialized[0], Is.InstanceOf()); + Assert.That(messageDeserialized[1], Is.InstanceOf()); + Assert.That(messageDeserialized[2], Is.InstanceOf()); + Assert.That(messageDeserialized[3], Is.InstanceOf()); + }); } [Test] @@ -39,7 +42,7 @@ public void Should_throw_exception_when_message_type_not_pre_discovered() var serializer = SerializerFactory.Create(); var exception = Assert.Throws(() => serializer.Deserialize(StringToByteArray(XmlWithBaseType))); - Assert.True(exception.Message.StartsWith("Could not determine type for node:")); + Assert.That(exception.Message, Does.StartWith("Could not determine type for node:")); } static byte[] StringToByteArray(string input) diff --git a/src/NServiceBus.Core.Tests/Serializers/XML/XmlSerializerCacheTests.cs b/src/NServiceBus.Core.Tests/Serializers/XML/XmlSerializerCacheTests.cs index 874d1e70e6f..a0d5e205dd0 100644 --- a/src/NServiceBus.Core.Tests/Serializers/XML/XmlSerializerCacheTests.cs +++ b/src/NServiceBus.Core.Tests/Serializers/XML/XmlSerializerCacheTests.cs @@ -15,7 +15,7 @@ public void InitType_ShouldNotInitializeXContainerTypes() cache.InitType(typeof(XElement)); - Assert.IsFalse(cache.typeMembers.ContainsKey(typeof(XElement))); + Assert.That(cache.typeMembers.ContainsKey(typeof(XElement)), Is.False); } [Test] @@ -26,9 +26,12 @@ public void InitType_ShouldNotInfinitelyInitializeRecursiveTypes() cache.InitType(typeof(RecursiveType)); var members = cache.typeMembers[typeof(RecursiveType)]; - Assert.AreEqual(typeof(RecursiveType), members.Item1.Single().FieldType); - Assert.AreEqual(typeof(RecursiveType), members.Item2[0].PropertyType); - Assert.AreEqual(typeof(RecursiveType[]), members.Item2[1].PropertyType); + Assert.Multiple(() => + { + Assert.That(members.Item1.Single().FieldType, Is.EqualTo(typeof(RecursiveType))); + Assert.That(members.Item2[0].PropertyType, Is.EqualTo(typeof(RecursiveType))); + Assert.That(members.Item2[1].PropertyType, Is.EqualTo(typeof(RecursiveType[]))); + }); } [Test] @@ -41,9 +44,12 @@ public void InitType_ShouldHandleConcurrentInitializations() cache.InitType(typeof(SimpleType)); var members = cache.typeMembers[typeof(SimpleType)]; - Assert.NotNull(members); - Assert.AreEqual(nameof(SimpleType.SimpleField), members.Item1.Single().Name); - Assert.AreEqual(nameof(SimpleType.SimpleProperty), members.Item2.Single().Name); + Assert.That(members, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(members.Item1.Single().Name, Is.EqualTo(nameof(SimpleType.SimpleField))); + Assert.That(members.Item2.Single().Name, Is.EqualTo(nameof(SimpleType.SimpleProperty))); + }); }); } } diff --git a/src/NServiceBus.Core.Tests/ServicePlatform/Retries/RetryAcknowledgementBehaviorTests.cs b/src/NServiceBus.Core.Tests/ServicePlatform/Retries/RetryAcknowledgementBehaviorTests.cs index 095fa654692..fa1a63046d1 100644 --- a/src/NServiceBus.Core.Tests/ServicePlatform/Retries/RetryAcknowledgementBehaviorTests.cs +++ b/src/NServiceBus.Core.Tests/ServicePlatform/Retries/RetryAcknowledgementBehaviorTests.cs @@ -28,20 +28,26 @@ public async Task Should_confirm_successful_retries_to_acknowledgement_queue() await behavior.Invoke(context, _ => Task.CompletedTask); var outgoingMessage = routingPipeline.ForkInvocations.Single(); - Assert.AreEqual( - context.Message.Headers["ServiceControl.Retry.UniqueMessageId"], - outgoingMessage.Message.Headers["ServiceControl.Retry.UniqueMessageId"]); + Assert.Multiple(() => + { + Assert.That( + outgoingMessage.Message.Headers["ServiceControl.Retry.UniqueMessageId"], + Is.EqualTo(context.Message.Headers["ServiceControl.Retry.UniqueMessageId"])); - Assert.IsTrue(outgoingMessage.Message.Headers.ContainsKey("ServiceControl.Retry.Successful")); + Assert.That(outgoingMessage.Message.Headers.ContainsKey("ServiceControl.Retry.Successful"), Is.True); - Assert.AreEqual(0, outgoingMessage.Message.Body.Length); + Assert.That(outgoingMessage.Message.Body.Length, Is.EqualTo(0)); - Assert.AreEqual(bool.TrueString, outgoingMessage.Message.Headers[Headers.ControlMessageHeader]); + Assert.That(outgoingMessage.Message.Headers[Headers.ControlMessageHeader], Is.EqualTo(bool.TrueString)); + }); var addressTag = outgoingMessage.RoutingStrategies.Single().Apply([]) as UnicastAddressTag; - Assert.AreEqual(addressTag.Destination, acknowledgementQueue); + Assert.Multiple(() => + { + Assert.That(addressTag.Destination, Is.EqualTo(acknowledgementQueue)); - Assert.IsTrue(context.Extensions.TryGet(out MarkAsAcknowledgedBehavior.State _)); + Assert.That(context.Extensions.TryGet(out MarkAsAcknowledgedBehavior.State _), Is.True); + }); } [Test] @@ -58,8 +64,11 @@ public void Should_not_confirm_when_processing_fails() var exception = new Exception("some pipeline failure"); var thrownException = Assert.ThrowsAsync(async () => await behavior.Invoke(context, _ => Task.FromException(exception))); - Assert.AreSame(thrownException, exception); - Assert.AreEqual(0, routingPipeline.ForkInvocations.Count); + Assert.Multiple(() => + { + Assert.That(exception, Is.SameAs(thrownException)); + Assert.That(routingPipeline.ForkInvocations.Count, Is.EqualTo(0)); + }); } [Test] @@ -74,8 +83,11 @@ public async Task Should_not_confirm_when_message_does_not_contain_acknowledgeme await behavior.Invoke(context, _ => Task.CompletedTask); - Assert.AreEqual(0, routingPipeline.ForkInvocations.Count); - Assert.IsFalse(context.Extensions.TryGet(out MarkAsAcknowledgedBehavior.State _)); + Assert.Multiple(() => + { + Assert.That(routingPipeline.ForkInvocations.Count, Is.EqualTo(0)); + Assert.That(context.Extensions.TryGet(out MarkAsAcknowledgedBehavior.State _), Is.False); + }); } [Test] @@ -89,8 +101,11 @@ public async Task Should_not_confirm_when_message_does_not_contain_retry_header( await behavior.Invoke(context, _ => Task.CompletedTask); - Assert.AreEqual(0, routingPipeline.ForkInvocations.Count); - Assert.IsFalse(context.Extensions.TryGet(out MarkAsAcknowledgedBehavior.State _)); + Assert.Multiple(() => + { + Assert.That(routingPipeline.ForkInvocations.Count, Is.EqualTo(0)); + Assert.That(context.Extensions.TryGet(out MarkAsAcknowledgedBehavior.State _), Is.False); + }); } static TestableTransportReceiveContext SetupTestableContext(RoutingPipeline routingPipeline) diff --git a/src/NServiceBus.Core.Tests/Settings/SettingsHolderTests.cs b/src/NServiceBus.Core.Tests/Settings/SettingsHolderTests.cs index 7ee3318192c..996d9c44509 100644 --- a/src/NServiceBus.Core.Tests/Settings/SettingsHolderTests.cs +++ b/src/NServiceBus.Core.Tests/Settings/SettingsHolderTests.cs @@ -31,7 +31,7 @@ public void Clear_ShouldDisposeAllDisposables() settings.Clear(); - Assert.IsTrue(all.All(x => x.Disposed)); + Assert.That(all.All(x => x.Disposed), Is.True); } [Test] @@ -50,8 +50,11 @@ public void Merge_ShouldMergeContentFromSource() var result1 = settings.Get("SomeDefaultSettingThatGetsMerged"); var result2 = settings.Get("SomeSettingThatGetsMerged"); - Assert.AreEqual("Value1", result1); - Assert.AreEqual("Value1", result2); + Assert.Multiple(() => + { + Assert.That(result1, Is.EqualTo("Value1")); + Assert.That(result2, Is.EqualTo("Value1")); + }); } [Test] diff --git a/src/NServiceBus.Core.Tests/StandardsTests.cs b/src/NServiceBus.Core.Tests/StandardsTests.cs index 3eb12566d96..b2903b1f5f1 100644 --- a/src/NServiceBus.Core.Tests/StandardsTests.cs +++ b/src/NServiceBus.Core.Tests/StandardsTests.cs @@ -17,12 +17,15 @@ public void VerifyFeatureNaming() { foreach (var featureType in GetFeatures()) { - Assert.AreEqual("NServiceBus.Features", featureType.Namespace, "Features should be in the NServiceBus.Features namespace. " + featureType.FullName); - Assert.IsFalse(featureType.Name.EndsWith("Feature"), "Features should not be suffixed with 'Feature'. " + featureType.FullName); + Assert.Multiple(() => + { + Assert.That(featureType.Namespace, Is.EqualTo("NServiceBus.Features"), "Features should be in the NServiceBus.Features namespace. " + featureType.FullName); + Assert.That(featureType.Name, Does.Not.EndWith("Feature"), "Features should not be suffixed with 'Feature'. " + featureType.FullName); + }); if (featureType.IsPublic) { var constructorInfo = featureType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Array.Empty(), null); - Assert.IsFalse(constructorInfo.IsPublic, "Features should have an internal constructor. " + featureType.FullName); + Assert.That(constructorInfo.IsPublic, Is.False, "Features should have an internal constructor. " + featureType.FullName); } } } @@ -49,7 +52,7 @@ public void NonPublicShouldHaveSimpleNamespace() x.Namespace != "MicrosoftExtensionsDependencyInjection").ToList(); if (types.Count > 0) { - Assert.IsEmpty(types, $"Non-public types should have 'NServiceBus' namespace{Environment.NewLine}{string.Join(Environment.NewLine, types.Select(x => x.FullName))}"); + Assert.That(types, Is.Empty, $"Non-public types should have 'NServiceBus' namespace{Environment.NewLine}{string.Join(Environment.NewLine, types.Select(x => x.FullName))}"); } } @@ -67,7 +70,7 @@ public void LoggersShouldBeStaticField() { if (field.FieldType == typeof(ILog)) { - Assert.IsTrue(field.IsStatic, "Logger fields should be static " + type.FullName); + Assert.That(field.IsStatic, Is.True, "Logger fields should be static " + type.FullName); } } } @@ -78,9 +81,12 @@ public void VerifyBehaviorNaming() { foreach (var featureType in GetBehaviors()) { - Assert.IsFalse(featureType.IsPublic, "Behaviors should internal " + featureType.FullName); - Assert.AreEqual("NServiceBus", featureType.Namespace, "Behaviors should be in the NServiceBus namespace since it reduces the 'wall of text' problem when looking at pipeline stack traces. " + featureType.FullName); - Assert.IsTrue(featureType.Name.EndsWith("Terminator") || featureType.Name.EndsWith("Behavior") || featureType.Name.EndsWith("Connector"), "Behaviors should be suffixed with 'Behavior' or 'Connector'. " + featureType.FullName); + Assert.Multiple(() => + { + Assert.That(featureType.IsPublic, Is.False, "Behaviors should internal " + featureType.FullName); + Assert.That(featureType.Namespace, Is.EqualTo("NServiceBus"), "Behaviors should be in the NServiceBus namespace since it reduces the 'wall of text' problem when looking at pipeline stack traces. " + featureType.FullName); + Assert.That(featureType.Name.EndsWith("Terminator") || featureType.Name.EndsWith("Behavior") || featureType.Name.EndsWith("Connector"), Is.True, "Behaviors should be suffixed with 'Behavior' or 'Connector'. " + featureType.FullName); + }); } } @@ -89,7 +95,7 @@ public void VerifyAttributesAreSealed() { foreach (var attributeType in GetAttributeTypes()) { - Assert.IsTrue(attributeType.IsSealed, attributeType.FullName + " should be sealed."); + Assert.That(attributeType.IsSealed, Is.True, attributeType.FullName + " should be sealed."); } } diff --git a/src/NServiceBus.Core.Tests/TransactionScopeTests.cs b/src/NServiceBus.Core.Tests/TransactionScopeTests.cs index c2b06950c0e..e2d201b9de0 100644 --- a/src/NServiceBus.Core.Tests/TransactionScopeTests.cs +++ b/src/NServiceBus.Core.Tests/TransactionScopeTests.cs @@ -18,7 +18,7 @@ public void Basic_assumptions_promotable_should_fail_if_durable_already_exists() { var resourceManager = new FakePromotableResourceManager(); Transaction.Current.EnlistDurable(resourceManager.ResourceManagerId, new FakePromotableResourceManager(), EnlistmentOptions.None); - Assert.False(Transaction.Current.EnlistPromotableSinglePhase(new FakePromotableResourceManager())); + Assert.That(Transaction.Current.EnlistPromotableSinglePhase(new FakePromotableResourceManager()), Is.False); tx.Complete(); } @@ -34,9 +34,9 @@ public void Basic_assumptions_second_promotable_should_fail() { using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { - Assert.True(Transaction.Current.EnlistPromotableSinglePhase(new FakePromotableResourceManager())); + Assert.That(Transaction.Current.EnlistPromotableSinglePhase(new FakePromotableResourceManager()), Is.True); - Assert.False(Transaction.Current.EnlistPromotableSinglePhase(new FakePromotableResourceManager())); + Assert.That(Transaction.Current.EnlistPromotableSinglePhase(new FakePromotableResourceManager()), Is.False); tx.Complete(); } diff --git a/src/NServiceBus.Core.Tests/Transports/IncomingMessageTests.cs b/src/NServiceBus.Core.Tests/Transports/IncomingMessageTests.cs index ee4d21c574d..9eba44dfa43 100644 --- a/src/NServiceBus.Core.Tests/Transports/IncomingMessageTests.cs +++ b/src/NServiceBus.Core.Tests/Transports/IncomingMessageTests.cs @@ -13,9 +13,12 @@ public void Should_assign_transport_message_id_when_NServiceBus_message_id_heade var headers = new Dictionary(); var message = new IncomingMessage("nativeId", headers, System.Array.Empty()); - Assert.AreEqual("nativeId", message.NativeMessageId); - Assert.AreEqual("nativeId", message.MessageId); - Assert.AreEqual("nativeId", headers[Headers.MessageId]); + Assert.Multiple(() => + { + Assert.That(message.NativeMessageId, Is.EqualTo("nativeId")); + Assert.That(message.MessageId, Is.EqualTo("nativeId")); + Assert.That(headers[Headers.MessageId], Is.EqualTo("nativeId")); + }); } [Test] @@ -27,8 +30,11 @@ public void Should_retain_transport_message_id_when_NServiceBus_message_id_heade }; var message = new IncomingMessage("nativeId", headers, System.Array.Empty()); - Assert.AreEqual("nativeId", message.NativeMessageId); - Assert.AreEqual("coreId", message.MessageId); + Assert.Multiple(() => + { + Assert.That(message.NativeMessageId, Is.EqualTo("nativeId")); + Assert.That(message.MessageId, Is.EqualTo("coreId")); + }); } [Test] @@ -40,7 +46,10 @@ public void Should_assign_transport_message_id_when_NServiceBus_message_id_heade }; var message = new IncomingMessage("nativeId", headers, System.Array.Empty()); - Assert.AreEqual("nativeId", message.NativeMessageId); - Assert.AreEqual("nativeId", message.MessageId); + Assert.Multiple(() => + { + Assert.That(message.NativeMessageId, Is.EqualTo("nativeId")); + Assert.That(message.MessageId, Is.EqualTo("nativeId")); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Transports/Learning/AsyncFileTests.cs b/src/NServiceBus.Core.Tests/Transports/Learning/AsyncFileTests.cs index 2fd8e51661e..45d1ab3660a 100644 --- a/src/NServiceBus.Core.Tests/Transports/Learning/AsyncFileTests.cs +++ b/src/NServiceBus.Core.Tests/Transports/Learning/AsyncFileTests.cs @@ -19,7 +19,7 @@ public async Task When_file_content_larger_than_buffer_size() var content = await AsyncFile.ReadText(filePath); - Assert.AreEqual(originalContent, content); + Assert.That(content, Is.EqualTo(originalContent)); } finally { diff --git a/src/NServiceBus.Core.Tests/Transports/Learning/HeaderSerializerTests.cs b/src/NServiceBus.Core.Tests/Transports/Learning/HeaderSerializerTests.cs index d7c7dff5ee2..1ac75b358c1 100644 --- a/src/NServiceBus.Core.Tests/Transports/Learning/HeaderSerializerTests.cs +++ b/src/NServiceBus.Core.Tests/Transports/Learning/HeaderSerializerTests.cs @@ -24,6 +24,6 @@ public void Can_round_trip_headers() Approver.Verify(serialized); var deserialize = HeaderSerializer.Deserialize(serialized); - CollectionAssert.AreEquivalent(input, deserialize); + Assert.That(deserialize, Is.EquivalentTo(input)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Transports/Learning/LearningTransportDispatcherTests.cs b/src/NServiceBus.Core.Tests/Transports/Learning/LearningTransportDispatcherTests.cs index 529224f4221..9d990e1b31d 100644 --- a/src/NServiceBus.Core.Tests/Transports/Learning/LearningTransportDispatcherTests.cs +++ b/src/NServiceBus.Core.Tests/Transports/Learning/LearningTransportDispatcherTests.cs @@ -22,7 +22,7 @@ public async Task Should_throw_for_size_above_threshold() await dispatcher.Dispatch(new TransportOperations(new TransportOperation(messageAtThreshold, new UnicastAddressTag("my-destination"))), new TransportTransaction()); var ex = Assert.ThrowsAsync(async () => await dispatcher.Dispatch(new TransportOperations(new TransportOperation(messageAboveThreshold, new UnicastAddressTag("my-destination"))), new TransportTransaction())); - StringAssert.Contains("The total size of the 'TestMessage' message", ex.Message); + Assert.That(ex.Message, Does.Contain("The total size of the 'TestMessage' message")); } const int MessageSizeLimit = (64 * 1024) - headerSize; diff --git a/src/NServiceBus.Core.Tests/Transports/MulticastTransportOperationTest.cs b/src/NServiceBus.Core.Tests/Transports/MulticastTransportOperationTest.cs index 513a3ec7e6d..381a4b2a2ac 100644 --- a/src/NServiceBus.Core.Tests/Transports/MulticastTransportOperationTest.cs +++ b/src/NServiceBus.Core.Tests/Transports/MulticastTransportOperationTest.cs @@ -16,7 +16,10 @@ public void Should_not_share_constraints_when_not_provided() transportOperation.Properties.DiscardIfNotReceivedBefore = new DiscardIfNotReceivedBefore(TimeSpan.FromDays(1)); - Assert.IsEmpty(secondTransportOperation.Properties); - Assert.IsNotEmpty(transportOperation.Properties); + Assert.Multiple(() => + { + Assert.That(secondTransportOperation.Properties, Is.Empty); + Assert.That(transportOperation.Properties, Is.Not.Empty); + }); } } diff --git a/src/NServiceBus.Core.Tests/Transports/PushRuntimeSettingsTests.cs b/src/NServiceBus.Core.Tests/Transports/PushRuntimeSettingsTests.cs index bbe9fc463a2..5f4238bc862 100644 --- a/src/NServiceBus.Core.Tests/Transports/PushRuntimeSettingsTests.cs +++ b/src/NServiceBus.Core.Tests/Transports/PushRuntimeSettingsTests.cs @@ -10,12 +10,12 @@ public class PushRuntimeSettingsTests [Test] public void Should_default_concurrency_to_num_processors() { - Assert.AreEqual(Math.Max(2, Environment.ProcessorCount), new PushRuntimeSettings().MaxConcurrency); + Assert.That(new PushRuntimeSettings().MaxConcurrency, Is.EqualTo(Math.Max(2, Environment.ProcessorCount))); } [Test] public void Should_honor_explicit_concurrency_settings() { - Assert.AreEqual(10, new PushRuntimeSettings(10).MaxConcurrency); + Assert.That(new PushRuntimeSettings(10).MaxConcurrency, Is.EqualTo(10)); } } \ No newline at end of file diff --git a/src/NServiceBus.Core.Tests/Transports/QueueAddressTests.cs b/src/NServiceBus.Core.Tests/Transports/QueueAddressTests.cs index 8a087e4982e..3fd0897645c 100644 --- a/src/NServiceBus.Core.Tests/Transports/QueueAddressTests.cs +++ b/src/NServiceBus.Core.Tests/Transports/QueueAddressTests.cs @@ -10,7 +10,7 @@ public class QueueAddressTests [TestCaseSource(nameof(queueAddresses))] public void ToStringTests((QueueAddress address, string expectedResult) test) { - Assert.AreEqual(test.expectedResult, test.address.ToString()); + Assert.That(test.address.ToString(), Is.EqualTo(test.expectedResult)); } static (QueueAddress, string)[] queueAddresses = diff --git a/src/NServiceBus.Core.Tests/Transports/TransportOperationTest.cs b/src/NServiceBus.Core.Tests/Transports/TransportOperationTest.cs index 32e87cc1327..80ad8151b30 100644 --- a/src/NServiceBus.Core.Tests/Transports/TransportOperationTest.cs +++ b/src/NServiceBus.Core.Tests/Transports/TransportOperationTest.cs @@ -14,8 +14,11 @@ public void Should_not_share_constraints_when_not_provided() var transportOperation = new TransportOperation(new OutgoingMessage(Guid.NewGuid().ToString(), [], Array.Empty()), new UnicastAddressTag("destination")); var secondTransportOperation = new TransportOperation(new OutgoingMessage(Guid.NewGuid().ToString(), [], Array.Empty()), new UnicastAddressTag("destination2")); - Assert.AreNotSame(transportOperation.Properties, secondTransportOperation.Properties); - Assert.IsEmpty(transportOperation.Properties); - Assert.IsEmpty(secondTransportOperation.Properties); + Assert.Multiple(() => + { + Assert.That(secondTransportOperation.Properties, Is.Not.SameAs(transportOperation.Properties)); + Assert.That(transportOperation.Properties, Is.Empty); + }); + Assert.That(secondTransportOperation.Properties, Is.Empty); } } diff --git a/src/NServiceBus.Core.Tests/Transports/TransportOperationsTests.cs b/src/NServiceBus.Core.Tests/Transports/TransportOperationsTests.cs index 46209dbf185..a4b4fd73310 100644 --- a/src/NServiceBus.Core.Tests/Transports/TransportOperationsTests.cs +++ b/src/NServiceBus.Core.Tests/Transports/TransportOperationsTests.cs @@ -22,19 +22,25 @@ public void Should_split_multicast_and_unicast_messages() var result = new TransportOperations(operations); - Assert.AreEqual(1, result.MulticastTransportOperations.Count); + Assert.That(result.MulticastTransportOperations.Count, Is.EqualTo(1)); var multicastOp = result.MulticastTransportOperations.Single(); - Assert.AreEqual(multicastOperation.Message, multicastOp.Message); - Assert.AreEqual((multicastOperation.AddressTag as MulticastAddressTag)?.MessageType, multicastOp.MessageType); - Assert.AreEqual(multicastOperation.Properties, multicastOp.Properties); - Assert.AreEqual(multicastOperation.RequiredDispatchConsistency, multicastOp.RequiredDispatchConsistency); + Assert.Multiple(() => + { + Assert.That(multicastOp.Message, Is.EqualTo(multicastOperation.Message)); + Assert.That(multicastOp.MessageType, Is.EqualTo((multicastOperation.AddressTag as MulticastAddressTag)?.MessageType)); + Assert.That(multicastOp.Properties, Is.EqualTo(multicastOperation.Properties)); + Assert.That(multicastOp.RequiredDispatchConsistency, Is.EqualTo(multicastOperation.RequiredDispatchConsistency)); - Assert.AreEqual(1, result.UnicastTransportOperations.Count); + Assert.That(result.UnicastTransportOperations.Count, Is.EqualTo(1)); + }); var unicastOp = result.UnicastTransportOperations.Single(); - Assert.AreEqual(unicastOperation.Message, unicastOp.Message); - Assert.AreEqual((unicastOperation.AddressTag as UnicastAddressTag)?.Destination, unicastOp.Destination); - Assert.AreEqual(unicastOperation.Properties, unicastOp.Properties); - Assert.AreEqual(unicastOperation.RequiredDispatchConsistency, unicastOp.RequiredDispatchConsistency); + Assert.Multiple(() => + { + Assert.That(unicastOp.Message, Is.EqualTo(unicastOperation.Message)); + Assert.That(unicastOp.Destination, Is.EqualTo((unicastOperation.AddressTag as UnicastAddressTag)?.Destination)); + Assert.That(unicastOp.Properties, Is.EqualTo(unicastOperation.Properties)); + Assert.That(unicastOp.RequiredDispatchConsistency, Is.EqualTo(unicastOperation.RequiredDispatchConsistency)); + }); } [Test] @@ -42,8 +48,11 @@ public void When_no_messages_should_return_empty_lists() { var result = new TransportOperations(); - Assert.AreEqual(0, result.MulticastTransportOperations.Count); - Assert.AreEqual(0, result.UnicastTransportOperations.Count); + Assert.Multiple(() => + { + Assert.That(result.MulticastTransportOperations.Count, Is.EqualTo(0)); + Assert.That(result.UnicastTransportOperations.Count, Is.EqualTo(0)); + }); } [Test] diff --git a/src/NServiceBus.Core.Tests/Transports/UnicastTransportOperationTest.cs b/src/NServiceBus.Core.Tests/Transports/UnicastTransportOperationTest.cs index 9906fe2437a..6511b02dfe4 100644 --- a/src/NServiceBus.Core.Tests/Transports/UnicastTransportOperationTest.cs +++ b/src/NServiceBus.Core.Tests/Transports/UnicastTransportOperationTest.cs @@ -16,7 +16,10 @@ public void Should_not_share_constraints_when_not_provided() transportOperation.Properties.DiscardIfNotReceivedBefore = new DiscardIfNotReceivedBefore(TimeSpan.FromDays(1)); - Assert.IsEmpty(secondTransportOperation.Properties); - Assert.IsNotEmpty(transportOperation.Properties); + Assert.Multiple(() => + { + Assert.That(secondTransportOperation.Properties, Is.Empty); + Assert.That(transportOperation.Properties, Is.Not.Empty); + }); } } diff --git a/src/NServiceBus.Core.Tests/Unicast/Config/ConfigurationSettings.cs b/src/NServiceBus.Core.Tests/Unicast/Config/ConfigurationSettings.cs index f9c77f55868..f0eca82a1e6 100644 --- a/src/NServiceBus.Core.Tests/Unicast/Config/ConfigurationSettings.cs +++ b/src/NServiceBus.Core.Tests/Unicast/Config/ConfigurationSettings.cs @@ -10,49 +10,49 @@ public class ConfigUnicastBusTests [Test] public void Simple_handler_should_be_classified_as_a_handler() { - Assert.IsTrue(ReceiveComponent.IsMessageHandler(typeof(SimpleHandler))); + Assert.That(ReceiveComponent.IsMessageHandler(typeof(SimpleHandler)), Is.True); } [Test] public void Concrete_implementation_of_abstract_handler_should_be_classified_as_a_handler() { - Assert.IsTrue(ReceiveComponent.IsMessageHandler(typeof(ConcreteImplementationOfAbstractHandler))); + Assert.That(ReceiveComponent.IsMessageHandler(typeof(ConcreteImplementationOfAbstractHandler)), Is.True); } [Test] public void Abstract_handler_should_not_be_classified_as_a_handler() { - Assert.IsFalse(ReceiveComponent.IsMessageHandler(typeof(AbstractHandler))); + Assert.That(ReceiveComponent.IsMessageHandler(typeof(AbstractHandler)), Is.False); } [Test] public void Not_implementing_IHandleMessages_should_not_be_classified_as_a_handler() { - Assert.IsFalse(ReceiveComponent.IsMessageHandler(typeof(NotImplementingIHandleMessages))); + Assert.That(ReceiveComponent.IsMessageHandler(typeof(NotImplementingIHandleMessages)), Is.False); } [Test] public void Interface_handler_should_not_be_classified_as_a_handler() { - Assert.IsFalse(ReceiveComponent.IsMessageHandler(typeof(IInterfaceHandler))); + Assert.That(ReceiveComponent.IsMessageHandler(typeof(IInterfaceHandler)), Is.False); } [Test] public void Generic_type_definition_handler_should_not_be_classified_as_a_handler() { - Assert.IsFalse(ReceiveComponent.IsMessageHandler(typeof(GenericTypeDefinitionHandler<>))); + Assert.That(ReceiveComponent.IsMessageHandler(typeof(GenericTypeDefinitionHandler<>)), Is.False); } [Test] public void Specific_generic_type_definition_handler_should_be_classified_as_a_handler() { - Assert.IsTrue(ReceiveComponent.IsMessageHandler(typeof(GenericTypeDefinitionHandler))); + Assert.That(ReceiveComponent.IsMessageHandler(typeof(GenericTypeDefinitionHandler)), Is.True); } [Test] public void Generic_implemented_type_definition_handler_should_be_classified_as_a_handler() { - Assert.IsTrue(ReceiveComponent.IsMessageHandler(typeof(GenericImplementedHandler))); + Assert.That(ReceiveComponent.IsMessageHandler(typeof(GenericImplementedHandler)), Is.True); } diff --git a/src/NServiceBus.Core.Tests/Unicast/HandlerInvocationCache.cs b/src/NServiceBus.Core.Tests/Unicast/HandlerInvocationCache.cs index 435fa30cc43..fb954107f13 100644 --- a/src/NServiceBus.Core.Tests/Unicast/HandlerInvocationCache.cs +++ b/src/NServiceBus.Core.Tests/Unicast/HandlerInvocationCache.cs @@ -76,7 +76,7 @@ public async Task Should_invoke_handle_method() var handlerContext = new TestableMessageHandlerContext(); await handler.Invoke(new StubMessage(), handlerContext); - Assert.IsTrue(((StubHandler)handler.Instance).HandleCalled); + Assert.That(((StubHandler)handler.Instance).HandleCalled, Is.True); } [Test] @@ -90,7 +90,7 @@ public async Task Should_have_passed_through_correct_message() var handlerContext = new TestableMessageHandlerContext(); await handler.Invoke(stubMessage, handlerContext); - Assert.AreEqual(stubMessage, ((StubHandler)handler.Instance).HandledMessage); + Assert.That(((StubHandler)handler.Instance).HandledMessage, Is.EqualTo(stubMessage)); } [Test] @@ -103,7 +103,7 @@ public async Task Should_have_passed_through_correct_context() var handlerContext = new TestableMessageHandlerContext(); await handler.Invoke(new StubMessage(), handlerContext); - Assert.AreSame(handlerContext, ((StubHandler)handler.Instance).HandlerContext); + Assert.That(((StubHandler)handler.Instance).HandlerContext, Is.SameAs(handlerContext)); } public class StubHandler : IHandleMessages @@ -139,7 +139,7 @@ public async Task Should_invoke_timeout_method() var handlerContext = new TestableMessageHandlerContext(); await handler.Invoke(new StubTimeoutState(), handlerContext); - Assert.IsTrue(((StubHandler)handler.Instance).TimeoutCalled); + Assert.That(((StubHandler)handler.Instance).TimeoutCalled, Is.True); } [Test] @@ -153,7 +153,7 @@ public async Task Should_have_passed_through_correct_state() var handlerContext = new TestableMessageHandlerContext(); await handler.Invoke(stubState, handlerContext); - Assert.AreEqual(stubState, ((StubHandler)handler.Instance).HandledState); + Assert.That(((StubHandler)handler.Instance).HandledState, Is.EqualTo(stubState)); } [Test] @@ -166,7 +166,7 @@ public async Task Should_have_passed_through_correct_context() var handlerContext = new TestableMessageHandlerContext(); await handler.Invoke(new StubTimeoutState(), handlerContext); - Assert.AreSame(handlerContext, ((StubHandler)handler.Instance).HandlerContext); + Assert.That(((StubHandler)handler.Instance).HandlerContext, Is.SameAs(handlerContext)); } public class StubHandler : IHandleTimeouts diff --git a/src/NServiceBus.Core.Tests/Unicast/LoadHandlersConnectorTests.cs b/src/NServiceBus.Core.Tests/Unicast/LoadHandlersConnectorTests.cs index 69c9ff0fc74..2de6106cfdb 100644 --- a/src/NServiceBus.Core.Tests/Unicast/LoadHandlersConnectorTests.cs +++ b/src/NServiceBus.Core.Tests/Unicast/LoadHandlersConnectorTests.cs @@ -41,7 +41,7 @@ public void Should_throw_if_ambient_transaction_is_different_from_scope_used_by_ { var ex = Assert.ThrowsAsync(async () => await behavior.Invoke(context, c => Task.CompletedTask)); - StringAssert.Contains("A TransactionScope has been created that is overriding the one created by the transport", ex.Message); + Assert.That(ex.Message, Does.Contain("A TransactionScope has been created that is overriding the one created by the transport")); } } } @@ -61,7 +61,7 @@ public void Should_throw_if_ambient_transaction_suppressed_when_transport_uses_a { var ex = Assert.ThrowsAsync(async () => await behavior.Invoke(context, c => Task.CompletedTask)); - StringAssert.Contains("The TransactionScope created by the transport has been suppressed", ex.Message); + Assert.That(ex.Message, Does.Contain("The TransactionScope created by the transport has been suppressed")); } } } diff --git a/src/NServiceBus.Core.Tests/Unicast/MessageOperationsTests.cs b/src/NServiceBus.Core.Tests/Unicast/MessageOperationsTests.cs index dcaa02bfae1..0327e8b6bbd 100644 --- a/src/NServiceBus.Core.Tests/Unicast/MessageOperationsTests.cs +++ b/src/NServiceBus.Core.Tests/Unicast/MessageOperationsTests.cs @@ -35,8 +35,11 @@ public async Task When_sending_should_generate_message_id_and_set_message_id_hea await messageOperations.Send(new FakeRootContext(), m => { }, new SendOptions()); var messageId = messageOperations.SendPipeline.LastContext.MessageId; - Assert.IsNotNull(messageId); - Assert.AreEqual(messageId, messageOperations.SendPipeline.LastContext.Headers[Headers.MessageId]); + Assert.Multiple(() => + { + Assert.That(messageId, Is.Not.Null); + Assert.That(messageOperations.SendPipeline.LastContext.Headers[Headers.MessageId], Is.EqualTo(messageId)); + }); } [Test] @@ -50,8 +53,11 @@ public async Task When_sending_with_user_defined_message_id_should_set_defined_i sendOptions.SetMessageId(expectedMessageID); await messageOperations.Send(new FakeRootContext(), m => { }, sendOptions); - Assert.AreEqual(expectedMessageID, messageOperations.SendPipeline.LastContext.MessageId); - Assert.AreEqual(expectedMessageID, messageOperations.SendPipeline.LastContext.Headers[Headers.MessageId]); + Assert.Multiple(() => + { + Assert.That(messageOperations.SendPipeline.LastContext.MessageId, Is.EqualTo(expectedMessageID)); + Assert.That(messageOperations.SendPipeline.LastContext.Headers[Headers.MessageId], Is.EqualTo(expectedMessageID)); + }); } [Test] @@ -66,8 +72,8 @@ public async Task When_sending_should_clone_headersAsync() messageOperations.SendPipeline.LastContext.Headers["header1"] = "updated header1 value"; var optionsHeaders = sendOptions.GetHeaders(); - Assert.AreEqual(1, optionsHeaders.Count); - Assert.AreEqual("header1 value", optionsHeaders["header1"]); + Assert.That(optionsHeaders.Count, Is.EqualTo(1)); + Assert.That(optionsHeaders["header1"], Is.EqualTo("header1 value")); } [Test] @@ -98,8 +104,11 @@ public async Task When_replying_should_generate_message_id_and_set_message_id_he await messageOperations.Reply(new FakeRootContext(), m => { }, new ReplyOptions()); var messageId = messageOperations.ReplyPipeline.LastContext.MessageId; - Assert.IsNotNull(messageId); - Assert.AreEqual(messageId, messageOperations.ReplyPipeline.LastContext.Headers[Headers.MessageId]); + Assert.Multiple(() => + { + Assert.That(messageId, Is.Not.Null); + Assert.That(messageOperations.ReplyPipeline.LastContext.Headers[Headers.MessageId], Is.EqualTo(messageId)); + }); } [Test] @@ -113,8 +122,11 @@ public async Task When_replying_with_user_defined_message_id_should_set_defined_ replyOptions.SetMessageId(expectedMessageID); await messageOperations.Reply(new FakeRootContext(), m => { }, replyOptions); - Assert.AreEqual(expectedMessageID, messageOperations.ReplyPipeline.LastContext.MessageId); - Assert.AreEqual(expectedMessageID, messageOperations.ReplyPipeline.LastContext.Headers[Headers.MessageId]); + Assert.Multiple(() => + { + Assert.That(messageOperations.ReplyPipeline.LastContext.MessageId, Is.EqualTo(expectedMessageID)); + Assert.That(messageOperations.ReplyPipeline.LastContext.Headers[Headers.MessageId], Is.EqualTo(expectedMessageID)); + }); } [Test] @@ -129,8 +141,8 @@ public async Task When_replying_should_clone_headersAsync() messageOperations.ReplyPipeline.LastContext.Headers["header1"] = "updated header1 value"; var optionsHeaders = replyOptions.GetHeaders(); - Assert.AreEqual(1, optionsHeaders.Count); - Assert.AreEqual("header1 value", optionsHeaders["header1"]); + Assert.That(optionsHeaders.Count, Is.EqualTo(1)); + Assert.That(optionsHeaders["header1"], Is.EqualTo("header1 value")); } [Test] @@ -161,8 +173,11 @@ public async Task When_publishing_should_generate_message_id_and_set_message_id_ await messageOperations.Publish(new FakeRootContext(), m => { }, new PublishOptions()); var messageId = messageOperations.PublishPipeline.LastContext.MessageId; - Assert.IsNotNull(messageId); - Assert.AreEqual(messageId, messageOperations.PublishPipeline.LastContext.Headers[Headers.MessageId]); + Assert.Multiple(() => + { + Assert.That(messageId, Is.Not.Null); + Assert.That(messageOperations.PublishPipeline.LastContext.Headers[Headers.MessageId], Is.EqualTo(messageId)); + }); } [Test] @@ -176,8 +191,11 @@ public async Task When_publishing_with_user_defined_message_id_should_set_define publishOptions.SetMessageId(expectedMessageID); await messageOperations.Publish(new FakeRootContext(), m => { }, publishOptions); - Assert.AreEqual(expectedMessageID, messageOperations.PublishPipeline.LastContext.MessageId); - Assert.AreEqual(expectedMessageID, messageOperations.PublishPipeline.LastContext.Headers[Headers.MessageId]); + Assert.Multiple(() => + { + Assert.That(messageOperations.PublishPipeline.LastContext.MessageId, Is.EqualTo(expectedMessageID)); + Assert.That(messageOperations.PublishPipeline.LastContext.Headers[Headers.MessageId], Is.EqualTo(expectedMessageID)); + }); } [Test] @@ -192,8 +210,8 @@ public async Task When_publishing_should_clone_headers() messageOperations.PublishPipeline.LastContext.Headers["header1"] = "updated header1 value"; var optionsHeaders = publishOptions.GetHeaders(); - Assert.AreEqual(1, optionsHeaders.Count); - Assert.AreEqual("header1 value", optionsHeaders["header1"]); + Assert.That(optionsHeaders.Count, Is.EqualTo(1)); + Assert.That(optionsHeaders["header1"], Is.EqualTo("header1 value")); } public interface IMyMessage diff --git a/src/NServiceBus.Core.Tests/Unicast/MessageTypeTests.cs b/src/NServiceBus.Core.Tests/Unicast/MessageTypeTests.cs index 3457d00592d..0597b269f0c 100644 --- a/src/NServiceBus.Core.Tests/Unicast/MessageTypeTests.cs +++ b/src/NServiceBus.Core.Tests/Unicast/MessageTypeTests.cs @@ -11,8 +11,11 @@ public void Should_parse_types() { var messageType = new Subscriptions.MessageType(typeof(TestMessage)); - Assert.AreEqual(messageType.TypeName, typeof(TestMessage).FullName); - Assert.AreEqual(messageType.Version, typeof(TestMessage).Assembly.GetName().Version); + Assert.Multiple(() => + { + Assert.That(typeof(TestMessage).FullName, Is.EqualTo(messageType.TypeName)); + Assert.That(typeof(TestMessage).Assembly.GetName().Version, Is.EqualTo(messageType.Version)); + }); } [Test] @@ -20,8 +23,11 @@ public void Should_parse_AssemblyQualifiedName() { var messageType = new Subscriptions.MessageType(typeof(TestMessage).AssemblyQualifiedName); - Assert.AreEqual(messageType.TypeName, typeof(TestMessage).FullName); - Assert.AreEqual(messageType.Version, typeof(TestMessage).Assembly.GetName().Version); + Assert.Multiple(() => + { + Assert.That(typeof(TestMessage).FullName, Is.EqualTo(messageType.TypeName)); + Assert.That(typeof(TestMessage).Assembly.GetName().Version, Is.EqualTo(messageType.Version)); + }); } [Test] @@ -29,8 +35,11 @@ public void Should_parse_version_strings() { var messageType = new Subscriptions.MessageType("TestMessage", "1.2.3.4"); - Assert.AreEqual(messageType.TypeName, "TestMessage"); - Assert.AreEqual(messageType.Version, new Version(1, 2, 3, 4)); + Assert.Multiple(() => + { + Assert.That(messageType.TypeName, Is.EqualTo("TestMessage")); + Assert.That(new Version(1, 2, 3, 4), Is.EqualTo(messageType.Version)); + }); } diff --git a/src/NServiceBus.Core.Tests/Unicast/Messages/AssemblyQualifiedNameParserTests.cs b/src/NServiceBus.Core.Tests/Unicast/Messages/AssemblyQualifiedNameParserTests.cs index 56f34834d19..314d1a0243f 100644 --- a/src/NServiceBus.Core.Tests/Unicast/Messages/AssemblyQualifiedNameParserTests.cs +++ b/src/NServiceBus.Core.Tests/Unicast/Messages/AssemblyQualifiedNameParserTests.cs @@ -15,7 +15,7 @@ public void Should_extract_fullname_from_qualified_assembly_name(string assembly var typeNameWithoutAssembly = AssemblyQualifiedNameParser.GetMessageTypeNameWithoutAssembly(assemblyQualifiedName); - Assert.AreEqual(expectedFullName, typeNameWithoutAssembly); + Assert.That(typeNameWithoutAssembly, Is.EqualTo(expectedFullName)); } static IEnumerable AssemblyQualifiedNames => @@ -46,7 +46,7 @@ public void Should_extract_fullname_from_fullname(string assemblyQualifiedName, var messageType = AssemblyQualifiedNameParser.GetMessageTypeNameWithoutAssembly(assemblyQualifiedName); - Assert.AreEqual(expectedFullName, messageType); + Assert.That(messageType, Is.EqualTo(expectedFullName)); } static IEnumerable FullNames => diff --git a/src/NServiceBus.Core.Tests/Unicast/Messages/DefaultMessageRegistryTests.cs b/src/NServiceBus.Core.Tests/Unicast/Messages/DefaultMessageRegistryTests.cs index 3459484ded0..6f6b8208fe3 100644 --- a/src/NServiceBus.Core.Tests/Unicast/Messages/DefaultMessageRegistryTests.cs +++ b/src/NServiceBus.Core.Tests/Unicast/Messages/DefaultMessageRegistryTests.cs @@ -23,7 +23,7 @@ public void Should_return_null_when_resolving_unknown_type_from_type_identifier( var metadata = registry.GetMessageMetadata("SomeNamespace.SomeType, SomeAssemblyName, Version=81.0.0.0, Culture=neutral, PublicKeyToken=null"); - Assert.IsNull(metadata); + Assert.That(metadata, Is.Null); } [Test] @@ -34,8 +34,11 @@ public void Should_return_metadata_for_a_mapped_type() var messageMetadata = defaultMessageRegistry.GetMessageMetadata(typeof(int)); - Assert.AreEqual(typeof(int), messageMetadata.MessageType); - Assert.AreEqual(1, messageMetadata.MessageHierarchy.Length); + Assert.Multiple(() => + { + Assert.That(messageMetadata.MessageType, Is.EqualTo(typeof(int))); + Assert.That(messageMetadata.MessageHierarchy, Has.Length.EqualTo(1)); + }); } @@ -47,13 +50,16 @@ public void Should_return_the_correct_parent_hierarchy() defaultMessageRegistry.RegisterMessageTypesFoundIn([typeof(MyEvent)]); var messageMetadata = defaultMessageRegistry.GetMessageMetadata(typeof(MyEvent)); - Assert.AreEqual(5, messageMetadata.MessageHierarchy.Length); + Assert.That(messageMetadata.MessageHierarchy, Has.Length.EqualTo(5)); - Assert.AreEqual(typeof(MyEvent), messageMetadata.MessageHierarchy.ToList()[0]); - Assert.AreEqual(typeof(IInterfaceParent1), messageMetadata.MessageHierarchy.ToList()[1]); - Assert.AreEqual(typeof(ConcreteParent1), messageMetadata.MessageHierarchy.ToList()[2]); - Assert.AreEqual(typeof(IInterfaceParent1Base), messageMetadata.MessageHierarchy.ToList()[3]); - Assert.AreEqual(typeof(ConcreteParentBase), messageMetadata.MessageHierarchy.ToList()[4]); + Assert.Multiple(() => + { + Assert.That(messageMetadata.MessageHierarchy.ToList()[0], Is.EqualTo(typeof(MyEvent))); + Assert.That(messageMetadata.MessageHierarchy.ToList()[1], Is.EqualTo(typeof(IInterfaceParent1))); + Assert.That(messageMetadata.MessageHierarchy.ToList()[2], Is.EqualTo(typeof(ConcreteParent1))); + Assert.That(messageMetadata.MessageHierarchy.ToList()[3], Is.EqualTo(typeof(IInterfaceParent1Base))); + Assert.That(messageMetadata.MessageHierarchy.ToList()[4], Is.EqualTo(typeof(ConcreteParentBase))); + }); } [TestCase("NServiceBus.Unicast.Tests.MessageMetadataRegistryTests+MyEvent, NonExistingAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b50674d1e0c6ce54")] @@ -67,7 +73,7 @@ public void Should_match_types_from_a_different_assembly(string typeName) var messageMetadata = defaultMessageRegistry.GetMessageMetadata(typeName); - Assert.AreEqual(typeof(MyEvent), messageMetadata.MessageHierarchy.ToList()[0]); + Assert.That(messageMetadata.MessageHierarchy.ToList()[0], Is.EqualTo(typeof(MyEvent))); } [Test] @@ -79,7 +85,7 @@ public void Should_not_match_same_type_names_with_different_namespace() string typeIdentifier = typeof(MyEvent).AssemblyQualifiedName.Replace(typeof(MyEvent).FullName, $"SomeNamespace.{nameof(MyEvent)}"); var messageMetadata = defaultMessageRegistry.GetMessageMetadata(typeIdentifier); - Assert.IsNull(messageMetadata); + Assert.That(messageMetadata, Is.Null); } [Test] @@ -89,7 +95,7 @@ public void Should_resolve_uninitialized_types_from_loaded_assemblies() var metadata = registry.GetMessageMetadata(typeof(EndpointConfiguration).AssemblyQualifiedName); - Assert.AreEqual(typeof(EndpointConfiguration), metadata.MessageType); + Assert.That(metadata.MessageType, Is.EqualTo(typeof(EndpointConfiguration))); } [Test] @@ -99,7 +105,7 @@ public void Should_not_resolve_uninitialized_types_from_assembly_when_prohibitin var metadata = registry.GetMessageMetadata(typeof(EndpointConfiguration).AssemblyQualifiedName); - Assert.IsNull(metadata); + Assert.That(metadata, Is.Null); } class MyEvent : ConcreteParent1, IInterfaceParent1 diff --git a/src/NServiceBus.Core.Tests/Unicast/MessagingBestPracticesTests.cs b/src/NServiceBus.Core.Tests/Unicast/MessagingBestPracticesTests.cs index 5b183f84fc4..47b3397bdc8 100644 --- a/src/NServiceBus.Core.Tests/Unicast/MessagingBestPracticesTests.cs +++ b/src/NServiceBus.Core.Tests/Unicast/MessagingBestPracticesTests.cs @@ -14,7 +14,7 @@ public void Should_throw_for_command() { var invalidOperationException = Assert.Throws(() => new Validations(new Conventions()).AssertIsValidForReply(typeof(MyCommand))); - Assert.AreEqual($"Best practice violation for message type '{typeof(MyCommand).FullName}'. Reply is not supported for commands or events. Commands should be sent to their logical owner. Events should be published.", invalidOperationException.Message); + Assert.That(invalidOperationException.Message, Is.EqualTo($"Best practice violation for message type '{typeof(MyCommand).FullName}'. Reply is not supported for commands or events. Commands should be sent to their logical owner. Events should be published.")); } [Test] @@ -22,7 +22,7 @@ public void Should_throw_for_event() { var invalidOperationException = Assert.Throws(() => new Validations(new Conventions()).AssertIsValidForReply(typeof(MyEvent))); - Assert.AreEqual($"Best practice violation for message type '{typeof(MyEvent).FullName}'. Reply is not supported for commands or events. Commands should be sent to their logical owner. Events should be published.", invalidOperationException.Message); + Assert.That(invalidOperationException.Message, Is.EqualTo($"Best practice violation for message type '{typeof(MyEvent).FullName}'. Reply is not supported for commands or events. Commands should be sent to their logical owner. Events should be published.")); } [Test] @@ -41,7 +41,7 @@ public void Should_throw_for_command() { var invalidOperationException = Assert.Throws(() => new Validations(new Conventions()).AssertIsValidForPubSub(typeof(MyCommand))); - Assert.AreEqual($"Best practice violation for message type '{typeof(MyCommand).FullName}'. Pub/sub is not supported for commands, so they should be be sent to their logical owner instead.", invalidOperationException.Message); + Assert.That(invalidOperationException.Message, Is.EqualTo($"Best practice violation for message type '{typeof(MyCommand).FullName}'. Pub/sub is not supported for commands, so they should be be sent to their logical owner instead.")); } [Test] diff --git a/src/NServiceBus.Core.Tests/Utils/Reflection/ExtensionMethodsTests.cs b/src/NServiceBus.Core.Tests/Utils/Reflection/ExtensionMethodsTests.cs index f0f4c311d38..5e10fb3c6bf 100644 --- a/src/NServiceBus.Core.Tests/Utils/Reflection/ExtensionMethodsTests.cs +++ b/src/NServiceBus.Core.Tests/Utils/Reflection/ExtensionMethodsTests.cs @@ -12,10 +12,13 @@ public class ExtensionMethodsTests [Test] public void SerializationFriendlyNameTests() { - Assert.AreEqual("String", typeof(string).SerializationFriendlyName()); - Assert.AreEqual("DictionaryOfStringAndInt32", typeof(Dictionary).SerializationFriendlyName()); - Assert.AreEqual("DictionaryOfStringAndTupleOfInt32", typeof(Dictionary>).SerializationFriendlyName()); - Assert.AreEqual("NServiceBus.KeyValuePairOfStringAndTupleOfInt32", typeof(KeyValuePair>).SerializationFriendlyName()); + Assert.Multiple(() => + { + Assert.That(typeof(string).SerializationFriendlyName(), Is.EqualTo("String")); + Assert.That(typeof(Dictionary).SerializationFriendlyName(), Is.EqualTo("DictionaryOfStringAndInt32")); + Assert.That(typeof(Dictionary>).SerializationFriendlyName(), Is.EqualTo("DictionaryOfStringAndTupleOfInt32")); + Assert.That(typeof(KeyValuePair>).SerializationFriendlyName(), Is.EqualTo("NServiceBus.KeyValuePairOfStringAndTupleOfInt32")); + }); } [Test] @@ -25,8 +28,11 @@ public void Should_return_return_different_results_for_different_types() var customTypeResult = typeof(Target).IsSystemType(); var systemTypeResult = typeof(string).IsSystemType(); - Assert.IsTrue(systemTypeResult, "Expected string to be a system type."); - Assert.IsFalse(customTypeResult, "Expected Target to be a custom type."); + Assert.Multiple(() => + { + Assert.That(systemTypeResult, Is.True, "Expected string to be a system type."); + Assert.That(customTypeResult, Is.False, "Expected Target to be a custom type."); + }); } public class Target @@ -37,20 +43,20 @@ public class Target [Test] public void Should_return_false_for_SN_and_non_particular_assembly() { - Assert.IsFalse(typeof(string).IsFromParticularAssembly()); + Assert.That(typeof(string).IsFromParticularAssembly(), Is.False); } [Test] public void Should_return_true_for_particular_assembly() { - Assert.IsTrue(typeof(TransportReceiveToPhysicalMessageConnector).IsFromParticularAssembly()); + Assert.That(typeof(TransportReceiveToPhysicalMessageConnector).IsFromParticularAssembly(), Is.True); } [Test] public void Should_return_false_for_non_SN_and_non_particular_assembly() { var type = GetNonSnFakeType(); - Assert.IsFalse(type.IsFromParticularAssembly()); + Assert.That(type.IsFromParticularAssembly(), Is.False); } static Type GetNonSnFakeType() diff --git a/src/NServiceBus.Core.Tests/Utils/Reflection/ReflectTests.cs b/src/NServiceBus.Core.Tests/Utils/Reflection/ReflectTests.cs index e2c66707f45..048c2e31105 100644 --- a/src/NServiceBus.Core.Tests/Utils/Reflection/ReflectTests.cs +++ b/src/NServiceBus.Core.Tests/Utils/Reflection/ReflectTests.cs @@ -14,7 +14,7 @@ public class When_is_a_simple_property public void Should_return_property_name() { var propertyInfo = Reflect.GetProperty(target => target.Property); - Assert.AreEqual("Property", propertyInfo.Name); + Assert.That(propertyInfo.Name, Is.EqualTo("Property")); } public class Target @@ -31,7 +31,7 @@ public class When_is_a_field public void Should_throw() { var argumentException = Assert.Throws(() => Reflect.GetProperty(target => target.Field)); - Assert.AreEqual("Member is not a property", argumentException.Message); + Assert.That(argumentException.Message, Is.EqualTo("Member is not a property")); } public class Target @@ -48,15 +48,15 @@ public class When_is_a_nested_property public void Should_return_property_name() { var propertyInfo = Reflect.GetProperty(target => target.Property1.Property2); - Assert.AreEqual("Property2", propertyInfo.Name); + Assert.That(propertyInfo.Name, Is.EqualTo("Property2")); } [Test] public void Should_throw_when_dots_not_allowed() { var argumentException = Assert.Throws(() => Reflect.GetProperty(target => target.Property1.Property2, true)); - StringAssert.StartsWith("Argument passed contains more than a single dot which is not allowed: target => target.Property1.Property2", argumentException.Message); - Assert.AreEqual("member", argumentException.ParamName); + Assert.That(argumentException.Message, Does.StartWith("Argument passed contains more than a single dot which is not allowed: target => target.Property1.Property2")); + Assert.That(argumentException.ParamName, Is.EqualTo("member")); } public class Target1 diff --git a/src/NServiceBus.Learning.AcceptanceTests/NServiceBus.Learning.AcceptanceTests.csproj b/src/NServiceBus.Learning.AcceptanceTests/NServiceBus.Learning.AcceptanceTests.csproj index 740ffe57338..5179586c070 100644 --- a/src/NServiceBus.Learning.AcceptanceTests/NServiceBus.Learning.AcceptanceTests.csproj +++ b/src/NServiceBus.Learning.AcceptanceTests/NServiceBus.Learning.AcceptanceTests.csproj @@ -12,6 +12,7 @@ + diff --git a/src/NServiceBus.Learning.AcceptanceTests/When_disabling_payload_restrictions.cs b/src/NServiceBus.Learning.AcceptanceTests/When_disabling_payload_restrictions.cs index d751ce2f166..fd1421eba7e 100644 --- a/src/NServiceBus.Learning.AcceptanceTests/When_disabling_payload_restrictions.cs +++ b/src/NServiceBus.Learning.AcceptanceTests/When_disabling_payload_restrictions.cs @@ -18,7 +18,7 @@ public async Task Should_allow_messages_above_64kb() .Done(c => c.MessageReceived) .Run(); - Assert.True(context.MessageReceived, "Message was not received"); + Assert.That(context.MessageReceived, Is.True, "Message was not received"); } class Context : ScenarioContext diff --git a/src/NServiceBus.PersistenceTests/NServiceBus.PersistenceTests.csproj b/src/NServiceBus.PersistenceTests/NServiceBus.PersistenceTests.csproj index 92c8e9a4e56..850b67eb2bc 100644 --- a/src/NServiceBus.PersistenceTests/NServiceBus.PersistenceTests.csproj +++ b/src/NServiceBus.PersistenceTests/NServiceBus.PersistenceTests.csproj @@ -14,6 +14,7 @@ + diff --git a/src/NServiceBus.PersistenceTests/Outbox/OutboxStorageTests.cs b/src/NServiceBus.PersistenceTests/Outbox/OutboxStorageTests.cs index c6759789a19..df627bdc505 100644 --- a/src/NServiceBus.PersistenceTests/Outbox/OutboxStorageTests.cs +++ b/src/NServiceBus.PersistenceTests/Outbox/OutboxStorageTests.cs @@ -48,9 +48,12 @@ public async Task Should_find_existing_outbox_data() var message = await storage.Get(messageId, configuration.GetContextBagForOutbox()); - Assert.IsNotNull(message); - Assert.AreEqual(messageId, message.MessageId); - Assert.That(message.TransportOperations, Has.Length.EqualTo(1)); + Assert.That(message, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(message.MessageId, Is.EqualTo(messageId)); + Assert.That(message.TransportOperations, Has.Length.EqualTo(1)); + }); Assert.That(message.TransportOperations[0].MessageId, Is.EqualTo(transportOperationMessageId)); } @@ -78,7 +81,7 @@ public async Task Should_clear_operations_on_dispatched_messages() var message = await storage.Get(messageId, configuration.GetContextBagForOutbox()); Assert.That(message, Is.Not.Null); - CollectionAssert.IsEmpty(message.TransportOperations); + Assert.That(message.TransportOperations, Is.Empty); } [Test] @@ -129,7 +132,7 @@ public async Task Should_not_store_when_transaction_not_committed() } var message = await storage.Get(messageId, configuration.GetContextBagForOutbox()); - Assert.Null(message); + Assert.That(message, Is.Null); } [Test] @@ -152,7 +155,7 @@ public async Task Should_store_when_transaction_committed() } var message = await storage.Get(messageId, configuration.GetContextBagForOutbox()); - Assert.NotNull(message); + Assert.That(message, Is.Not.Null); } PersistenceTestsConfiguration configuration; diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_completing_a_saga_loaded_by_id.cs b/src/NServiceBus.PersistenceTests/Sagas/When_completing_a_saga_loaded_by_id.cs index c5738eb0a86..c2bb26c89d4 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_completing_a_saga_loaded_by_id.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_completing_a_saga_loaded_by_id.cs @@ -24,7 +24,7 @@ public async Task Should_delete_the_saga() } var completedSaga = await GetById(saga.Id); - Assert.Null(completedSaga); + Assert.That(completedSaga, Is.Null); } public class TestSaga : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_completing_a_saga_with_correlation_property.cs b/src/NServiceBus.PersistenceTests/Sagas/When_completing_a_saga_with_correlation_property.cs index edd5421de13..cf78a5378d0 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_completing_a_saga_with_correlation_property.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_completing_a_saga_with_correlation_property.cs @@ -26,7 +26,7 @@ public async Task Should_delete_the_saga() } var completedSaga = await GetByCorrelationProperty(correlatedPropertyName, correlationPropertyData); - Assert.Null(completedSaga); + Assert.That(completedSaga, Is.Null); } public class SagaWithCorrelationPropertyData : ContainSagaData diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_multiple_sagas_in_outbox_transaction.cs b/src/NServiceBus.PersistenceTests/Sagas/When_multiple_sagas_in_outbox_transaction.cs index 67bc3863aba..f7af1ac15d0 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_multiple_sagas_in_outbox_transaction.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_multiple_sagas_in_outbox_transaction.cs @@ -16,7 +16,7 @@ public async Task Should_create_new_sagas_when_committed() var context = configuration.GetContextBagForOutbox(); var outboxMessage = await configuration.OutboxStorage.Get(Guid.NewGuid().ToString(), context); - Assert.IsNull(outboxMessage); + Assert.That(outboxMessage, Is.Null); using (var outboxTransaction = await configuration.OutboxStorage.BeginTransaction(context)) { using (var saga1Session = configuration.CreateStorageSession()) @@ -24,7 +24,7 @@ public async Task Should_create_new_sagas_when_committed() await saga1Session.TryOpen(outboxTransaction, context); var saga1Data = await configuration.SagaStorage.Get(nameof(Saga1Data.CorrelationId), saga1.CorrelationId, saga1Session, context); - Assert.IsNull(saga1Data); + Assert.That(saga1Data, Is.Null); await SaveSagaWithSession(saga1, saga1Session, context); @@ -36,7 +36,7 @@ public async Task Should_create_new_sagas_when_committed() await saga2Session.TryOpen(outboxTransaction, context); var saga2Data = await configuration.SagaStorage.Get(nameof(Saga2Data.CorrelationId), saga2.CorrelationId, saga2Session, context); - Assert.IsNull(saga2Data); + Assert.That(saga2Data, Is.Null); await SaveSagaWithSession(saga2, saga2Session, context); @@ -47,11 +47,11 @@ public async Task Should_create_new_sagas_when_committed() } var sagaData1 = await GetById(saga1.Id); - Assert.NotNull(sagaData1); - Assert.AreEqual(saga1.CorrelationId, sagaData1.CorrelationId); + Assert.That(sagaData1, Is.Not.Null); + Assert.That(sagaData1.CorrelationId, Is.EqualTo(saga1.CorrelationId)); var sagaData2 = await GetById(saga2.Id); - Assert.NotNull(sagaData2); - Assert.AreEqual(saga2.CorrelationId, sagaData2.CorrelationId); + Assert.That(sagaData2, Is.Not.Null); + Assert.That(sagaData2.CorrelationId, Is.EqualTo(saga2.CorrelationId)); } [Test] @@ -64,7 +64,7 @@ public async Task Should_not_create_new_sagas_when_not_committed() var context = configuration.GetContextBagForOutbox(); var outboxMessage = await configuration.OutboxStorage.Get(Guid.NewGuid().ToString(), context); - Assert.IsNull(outboxMessage); + Assert.That(outboxMessage, Is.Null); using (var outboxTransaction = await configuration.OutboxStorage.BeginTransaction(context)) { using (var saga1Session = configuration.CreateStorageSession()) @@ -72,7 +72,7 @@ public async Task Should_not_create_new_sagas_when_not_committed() await saga1Session.TryOpen(outboxTransaction, context); var saga1Data = await configuration.SagaStorage.Get(nameof(Saga1Data.CorrelationId), saga1.CorrelationId, saga1Session, context); - Assert.IsNull(saga1Data); + Assert.That(saga1Data, Is.Null); await SaveSagaWithSession(saga1, saga1Session, context); @@ -84,7 +84,7 @@ public async Task Should_not_create_new_sagas_when_not_committed() await saga2Session.TryOpen(outboxTransaction, context); var saga2Data = await configuration.SagaStorage.Get(nameof(Saga2Data.CorrelationId), saga2.CorrelationId, saga2Session, context); - Assert.IsNull(saga2Data); + Assert.That(saga2Data, Is.Null); await SaveSagaWithSession(saga2, saga2Session, context); @@ -95,9 +95,9 @@ public async Task Should_not_create_new_sagas_when_not_committed() } var sagaData1 = await GetById(saga1.Id); - Assert.IsNull(sagaData1); + Assert.That(sagaData1, Is.Null); var sagaData2 = await GetById(saga2.Id); - Assert.IsNull(sagaData2); + Assert.That(sagaData2, Is.Null); } [Test] @@ -112,7 +112,7 @@ public async Task Should_update_existing_sagas_when_committed() var context = configuration.GetContextBagForOutbox(); var outboxMessage = await configuration.OutboxStorage.Get(Guid.NewGuid().ToString(), context); - Assert.IsNull(outboxMessage); + Assert.That(outboxMessage, Is.Null); using (var outboxTransaction = await configuration.OutboxStorage.BeginTransaction(context)) { using (var saga1Session = configuration.CreateStorageSession()) @@ -143,11 +143,11 @@ public async Task Should_update_existing_sagas_when_committed() } var saga1AfterUpdate = await GetById(saga1.Id); - Assert.NotNull(saga1AfterUpdate); - Assert.AreEqual("saga 1 after update", saga1AfterUpdate.SomeSaga1Data); + Assert.That(saga1AfterUpdate, Is.Not.Null); + Assert.That(saga1AfterUpdate.SomeSaga1Data, Is.EqualTo("saga 1 after update")); var saga2AfterUpdate = await GetById(saga2.Id); - Assert.NotNull(saga2AfterUpdate); - Assert.AreEqual("saga 2 after update", saga2AfterUpdate.SomeSaga2Data); + Assert.That(saga2AfterUpdate, Is.Not.Null); + Assert.That(saga2AfterUpdate.SomeSaga2Data, Is.EqualTo("saga 2 after update")); } [Test] @@ -162,7 +162,7 @@ public async Task Should_not_update_existing_sagas_when_not_committed() var context = configuration.GetContextBagForOutbox(); var outboxMessage = await configuration.OutboxStorage.Get(Guid.NewGuid().ToString(), context); - Assert.IsNull(outboxMessage); + Assert.That(outboxMessage, Is.Null); using (var outboxTransaction = await configuration.OutboxStorage.BeginTransaction(context)) { using (var saga1Session = configuration.CreateStorageSession()) @@ -193,11 +193,11 @@ public async Task Should_not_update_existing_sagas_when_not_committed() } var saga1AfterUpdate = await GetById(saga1.Id); - Assert.NotNull(saga1AfterUpdate); - Assert.AreEqual("saga 1 before update", saga1AfterUpdate.SomeSaga1Data); + Assert.That(saga1AfterUpdate, Is.Not.Null); + Assert.That(saga1AfterUpdate.SomeSaga1Data, Is.EqualTo("saga 1 before update")); var saga2AfterUpdate = await GetById(saga2.Id); - Assert.NotNull(saga2AfterUpdate); - Assert.AreEqual("saga 2 before update", saga2AfterUpdate.SomeSaga2Data); + Assert.That(saga2AfterUpdate, Is.Not.Null); + Assert.That(saga2AfterUpdate.SomeSaga2Data, Is.EqualTo("saga 2 before update")); } public class Saga1 : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_an_escalated_DTC_transaction.cs b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_an_escalated_DTC_transaction.cs index 7df483f66ac..59d1ffa996a 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_an_escalated_DTC_transaction.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_an_escalated_DTC_transaction.cs @@ -45,8 +45,8 @@ public async Task Should_rollback_when_the_dtc_transaction_is_aborted() var updatedSagaData = await GetById(startingSagaData.Id); - Assert.NotNull(updatedSagaData); - Assert.AreEqual("Unchanged", updatedSagaData.LastUpdatedBy); + Assert.That(updatedSagaData, Is.Not.Null); + Assert.That(updatedSagaData.LastUpdatedBy, Is.EqualTo("Unchanged")); } [Test] @@ -82,10 +82,13 @@ public async Task Should_rollback_dtc_transaction_when_storage_session_rolls_bac var notUpdatedSagaData = await GetById(startingSagaData.Id); - Assert.NotNull(notUpdatedSagaData); - Assert.AreEqual("Unchanged", notUpdatedSagaData.LastUpdatedBy); - Assert.IsFalse(enlistmentNotifier.CommitWasCalled); - Assert.IsTrue(enlistmentNotifier.RollbackWasCalled); + Assert.That(notUpdatedSagaData, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(notUpdatedSagaData.LastUpdatedBy, Is.EqualTo("Unchanged")); + Assert.That(enlistmentNotifier.CommitWasCalled, Is.False); + Assert.That(enlistmentNotifier.RollbackWasCalled, Is.True); + }); } public class TestSaga : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_complex_types.cs b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_complex_types.cs index 62d022e0be7..8dcffa1c566 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_complex_types.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_complex_types.cs @@ -17,8 +17,8 @@ public async Task It_should_get_deep_copy() var retrieved = await GetById(sagaData.Id); - CollectionAssert.AreEqual(sagaData.Ints, retrieved.Ints); - Assert.False(ReferenceEquals(sagaData.Ints, retrieved.Ints)); + Assert.That(retrieved.Ints, Is.EqualTo(sagaData.Ints).AsCollection); + Assert.That(ReferenceEquals(sagaData.Ints, retrieved.Ints), Is.False); } public class SagaWithComplexType : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_no_mapping.cs b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_no_mapping.cs index e5b9a4ac518..720495f14f9 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_no_mapping.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_no_mapping.cs @@ -25,7 +25,7 @@ public async Task It_should_persist_successfully_when_finder_exists() var result = await GetById(sagaData.Id); - Assert.AreEqual(sagaData.FoundByFinderProperty, result.FoundByFinderProperty); + Assert.That(result.FoundByFinderProperty, Is.EqualTo(sagaData.FoundByFinderProperty)); } public class SagaWithoutCorrelationProperty : Saga, diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_record_type.cs b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_record_type.cs index 4a20a3ac0df..3dfb05a2c3e 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_record_type.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_record_type.cs @@ -21,8 +21,8 @@ public async Task It_should_get_deep_copy() var retrieved = await GetById(sagaData.Id); - CollectionAssert.AreEqual(sagaData.Ints, retrieved.Ints); - Assert.False(ReferenceEquals(sagaData.Ints, retrieved.Ints)); + Assert.That(retrieved.Ints, Is.EqualTo(sagaData.Ints).AsCollection); + Assert.That(ReferenceEquals(sagaData.Ints, retrieved.Ints), Is.False); } [Test] @@ -37,8 +37,8 @@ public async Task It_Should_Load() var retrieved = await GetById(sagaData.Id); - Assert.IsNotNull(retrieved); - Assert.AreEqual(person, retrieved.SomePerson); + Assert.That(retrieved, Is.Not.Null); + Assert.That(retrieved.SomePerson, Is.EqualTo(person)); } public class SagaWithRecordType : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_the_same_unique_prop_as_another_saga.cs b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_the_same_unique_prop_as_another_saga.cs index e3b24195818..a65e96f2ca3 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_the_same_unique_prop_as_another_saga.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_a_saga_with_the_same_unique_prop_as_another_saga.cs @@ -41,8 +41,11 @@ public async Task It_should_persist_successfully() var saga2Result = await persister.Get(nameof(AnotherSagaWithCorrelatedPropertyData.CorrelatedProperty), saga2.CorrelatedProperty, readSession, readContextBag); - Assert.AreEqual(saga1.CorrelatedProperty, saga1Result.CorrelatedProperty); - Assert.AreEqual(saga2.CorrelatedProperty, saga2Result.CorrelatedProperty); + Assert.Multiple(() => + { + Assert.That(saga1Result.CorrelatedProperty, Is.EqualTo(saga1.CorrelatedProperty)); + Assert.That(saga2Result.CorrelatedProperty, Is.EqualTo(saga2.CorrelatedProperty)); + }); } } diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_different_sagas_without_mapping.cs b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_different_sagas_without_mapping.cs index 5b8a2217d29..d69b380f89d 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_different_sagas_without_mapping.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_different_sagas_without_mapping.cs @@ -45,8 +45,11 @@ public async Task It_should_persist_successfully_when_finder_exists() var saga2Result = await configuration.SagaStorage.Get(saga2.Id, readSession, readContextBag); - Assert.AreEqual(saga1.FoundByFinderProperty, saga1Result.FoundByFinderProperty); - Assert.AreEqual(saga2.FoundByFinderProperty, saga2Result.FoundByFinderProperty); + Assert.Multiple(() => + { + Assert.That(saga1Result.FoundByFinderProperty, Is.EqualTo(saga1.FoundByFinderProperty)); + Assert.That(saga2Result.FoundByFinderProperty, Is.EqualTo(saga2.FoundByFinderProperty)); + }); } } diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_saga_with_same_unique_prop_as_completed_saga.cs b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_saga_with_same_unique_prop_as_completed_saga.cs index 235faf15a70..d8e86939e33 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_persisting_saga_with_same_unique_prop_as_completed_saga.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_persisting_saga_with_same_unique_prop_as_completed_saga.cs @@ -22,13 +22,13 @@ public async Task It_should_persist_successfully() await completeSession.Open(context1); var sagaData = await persister.Get(nameof(saga1.CorrelatedProperty), correlationPropertyData, completeSession, context1); - Assert.AreEqual(saga1.DataProperty, sagaData.DataProperty); + Assert.That(sagaData.DataProperty, Is.EqualTo(saga1.DataProperty)); await persister.Complete(sagaData, completeSession, context1); await completeSession.CompleteAsync(); } - Assert.IsNull(await GetById(saga1.Id)); + Assert.That(await GetById(saga1.Id), Is.Null); await SaveSaga(saga2); var context2 = configuration.GetContextBagForSagaStorage(); @@ -37,13 +37,13 @@ public async Task It_should_persist_successfully() await completeSession.Open(context2); var sagaData = await persister.Get(nameof(saga2.CorrelatedProperty), correlationPropertyData, completeSession, context2); - Assert.AreEqual(saga2.DataProperty, sagaData.DataProperty); + Assert.That(sagaData.DataProperty, Is.EqualTo(saga2.DataProperty)); await persister.Complete(sagaData, completeSession, context2); await completeSession.CompleteAsync(); } - Assert.IsNull(await GetById(saga2.Id)); + Assert.That(await GetById(saga2.Id), Is.Null); } public class SagaWithCorrelationProperty : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_retrieving_the_same_saga_twice.cs b/src/NServiceBus.PersistenceTests/Sagas/When_retrieving_the_same_saga_twice.cs index 4631a94d3f6..693ff12c4e8 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_retrieving_the_same_saga_twice.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_retrieving_the_same_saga_twice.cs @@ -17,9 +17,12 @@ public async Task Get_returns_different_instance_of_saga_data() var returnedSaga1 = await GetById(saga.Id); var returnedSaga2 = await GetById(saga.Id); - Assert.AreNotSame(returnedSaga2, returnedSaga1); - Assert.AreNotSame(returnedSaga1, saga); - Assert.AreNotSame(returnedSaga2, saga); + Assert.Multiple(() => + { + Assert.That(returnedSaga1, Is.Not.SameAs(returnedSaga2)); + Assert.That(saga, Is.Not.SameAs(returnedSaga1)); + }); + Assert.That(saga, Is.Not.SameAs(returnedSaga2)); } public class TestSaga : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_rolling_back_storage_session.cs b/src/NServiceBus.PersistenceTests/Sagas/When_rolling_back_storage_session.cs index ac1e530706b..1ecba4bbcc4 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_rolling_back_storage_session.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_rolling_back_storage_session.cs @@ -31,7 +31,7 @@ public async Task Should_rollback_updates() var hopefullyNotUpdatedSaga = await GetById(sagaData.Id); - Assert.NotNull(hopefullyNotUpdatedSaga); + Assert.That(hopefullyNotUpdatedSaga, Is.Not.Null); Assert.That(hopefullyNotUpdatedSaga.SomethingWeCareAbout, Is.EqualTo("NServiceBus")); } @@ -54,9 +54,9 @@ public async Task Should_rollback_storing_new_saga() } var sagaById = await GetById(sagaData.Id); - Assert.IsNull(sagaById); + Assert.That(sagaById, Is.Null); var sagaByCorrelationProperty = await GetByCorrelationProperty(nameof(sagaData.SomeId), sagaData.SomeId); - Assert.IsNull(sagaByCorrelationProperty); + Assert.That(sagaByCorrelationProperty, Is.Null); } [Test] @@ -83,7 +83,7 @@ public async Task Should_rollback_saga_completion() var nonCompletedSaga = await GetById(sagaData.Id); - Assert.NotNull(nonCompletedSaga); + Assert.That(nonCompletedSaga, Is.Not.Null); Assert.That(nonCompletedSaga.SomethingWeCareAbout, Is.EqualTo("NServiceBus")); } diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_saga_not_found.cs b/src/NServiceBus.PersistenceTests/Sagas/When_saga_not_found.cs index e67e88d261b..7727d7f9993 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_saga_not_found.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_saga_not_found.cs @@ -10,14 +10,14 @@ public class When_saga_not_found : SagaPersisterTests public async Task Should_return_null_when_loading_by_correlation_property() { var result = await GetByCorrelationProperty("UsedAsCorrelationId", "someValue"); - Assert.IsNull(result); + Assert.That(result, Is.Null); } [Test] public async Task Should_return_null_when_loading_by_id() { var result = await GetById(Guid.NewGuid()); - Assert.IsNull(result); + Assert.That(result, Is.Null); } public class SimpleSagaEntitySaga : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.PersistenceTests/Sagas/When_updating_saga_in_outbox_transaction.cs b/src/NServiceBus.PersistenceTests/Sagas/When_updating_saga_in_outbox_transaction.cs index 9c802579243..999a83e4587 100644 --- a/src/NServiceBus.PersistenceTests/Sagas/When_updating_saga_in_outbox_transaction.cs +++ b/src/NServiceBus.PersistenceTests/Sagas/When_updating_saga_in_outbox_transaction.cs @@ -20,11 +20,11 @@ public async Task Should_save_saga_only_when_outbox_tx_committed() using (var synchronizedStorageSession = configuration.CreateStorageSession()) { var sessionCreated = await synchronizedStorageSession.TryOpen(outboxTransaction, contextBag); - Assert.IsTrue(sessionCreated); + Assert.That(sessionCreated, Is.True); var readBeforeCreate = await configuration.SagaStorage.Get(nameof(TestSagaData.SomeId), sagaData.SomeId, synchronizedStorageSession, contextBag); - Assert.IsNull(readBeforeCreate); + Assert.That(readBeforeCreate, Is.Null); await SaveSagaWithSession(sagaData, synchronizedStorageSession, contextBag); @@ -33,14 +33,14 @@ public async Task Should_save_saga_only_when_outbox_tx_committed() // outbox transaction not yet committed var readBeforeOutboxCommit = await GetById(sagaData.Id); - Assert.IsNull(readBeforeOutboxCommit); + Assert.That(readBeforeOutboxCommit, Is.Null); await outboxTransaction.Commit(); } var readAfterOutboxCommit = await GetById(sagaData.Id); - Assert.NotNull(readAfterOutboxCommit); - Assert.AreEqual(sagaData.SomeId, readAfterOutboxCommit.SomeId); + Assert.That(readAfterOutboxCommit, Is.Not.Null); + Assert.That(readAfterOutboxCommit.SomeId, Is.EqualTo(sagaData.SomeId)); } public class TestSaga : Saga, IAmStartedByMessages diff --git a/src/NServiceBus.TransportTests/NServiceBus.TransportTests.csproj b/src/NServiceBus.TransportTests/NServiceBus.TransportTests.csproj index 09d103150aa..8fc7c14ce08 100644 --- a/src/NServiceBus.TransportTests/NServiceBus.TransportTests.csproj +++ b/src/NServiceBus.TransportTests/NServiceBus.TransportTests.csproj @@ -12,6 +12,7 @@ + diff --git a/src/NServiceBus.TransportTests/TransportTestLoggerFactory.cs b/src/NServiceBus.TransportTests/TransportTestLoggerFactory.cs index 3c9d5fabfcf..1505650dfad 100644 --- a/src/NServiceBus.TransportTests/TransportTestLoggerFactory.cs +++ b/src/NServiceBus.TransportTests/TransportTestLoggerFactory.cs @@ -124,7 +124,7 @@ void Log(LogLevel level, string message) }); #pragma warning disable PS0023 // Use DateTime.UtcNow or DateTimeOffset.UtcNow - For test logging - TestContext.WriteLine($"{DateTime.Now:T} {level} {name}: {message}"); + TestContext.Out.WriteLine($"{DateTime.Now:T} {level} {name}: {message}"); #pragma warning restore PS0023 // Use DateTime.UtcNow or DateTimeOffset.UtcNow } diff --git a/src/NServiceBus.TransportTests/TransportTestPolicy.cs b/src/NServiceBus.TransportTests/TransportTestPolicy.cs index 852abe610e3..3f99046a744 100644 --- a/src/NServiceBus.TransportTests/TransportTestPolicy.cs +++ b/src/NServiceBus.TransportTests/TransportTestPolicy.cs @@ -20,7 +20,7 @@ public void LimitOneTransportTestPerClass() .Select(group => $"{Environment.NewLine} - {group.Key.FullName}") .ToArray(); - Assert.IsEmpty(multiTestClasses, "Each transport test method should be in its own class. The class determines the queue name and can lead to subtle bugs between tests. Offenders:" + string.Join("", multiTestClasses)); + Assert.That(multiTestClasses, Is.Empty, "Each transport test method should be in its own class. The class determines the queue name and can lead to subtle bugs between tests. Offenders:" + string.Join("", multiTestClasses)); } static bool IsTestMethod(MethodInfo method) => method.GetCustomAttributes().Any(att => att is TestAttribute or TestCaseAttribute); diff --git a/src/NServiceBus.TransportTests/When_cancelling_stop_on_error.cs b/src/NServiceBus.TransportTests/When_cancelling_stop_on_error.cs index 7377c689a4d..36d49eaad2b 100644 --- a/src/NServiceBus.TransportTests/When_cancelling_stop_on_error.cs +++ b/src/NServiceBus.TransportTests/When_cancelling_stop_on_error.cs @@ -45,6 +45,6 @@ await StartPump( await StopPump(new CancellationToken(true)); - Assert.True(await wasCanceled.Task, "onError was not canceled."); + Assert.That(await wasCanceled.Task, Is.True, "onError was not canceled."); } } diff --git a/src/NServiceBus.TransportTests/When_cancelling_stop_on_message.cs b/src/NServiceBus.TransportTests/When_cancelling_stop_on_message.cs index 5b63470985d..a17628f9806 100644 --- a/src/NServiceBus.TransportTests/When_cancelling_stop_on_message.cs +++ b/src/NServiceBus.TransportTests/When_cancelling_stop_on_message.cs @@ -43,6 +43,6 @@ await StartPump( await StopPump(new CancellationToken(true)); - Assert.True(await wasCanceled.Task, "onMessage was not canceled."); + Assert.That(await wasCanceled.Task, Is.True, "onMessage was not canceled."); } } diff --git a/src/NServiceBus.TransportTests/When_creating_send_only_transport.cs b/src/NServiceBus.TransportTests/When_creating_send_only_transport.cs index 99133accc80..defd17fb8da 100644 --- a/src/NServiceBus.TransportTests/When_creating_send_only_transport.cs +++ b/src/NServiceBus.TransportTests/When_creating_send_only_transport.cs @@ -22,7 +22,7 @@ public async Task Should_have_empty_receivers() var transport = await transportDefinition.Initialize(hostSettings, Array.Empty(), Array.Empty()); - Assert.IsNotNull(transport.Receivers); - Assert.IsEmpty(transport.Receivers); + Assert.That(transport.Receivers, Is.Not.Null); + Assert.That(transport.Receivers, Is.Empty); } } \ No newline at end of file diff --git a/src/NServiceBus.TransportTests/When_failure_happens_after_send.cs b/src/NServiceBus.TransportTests/When_failure_happens_after_send.cs index 904be0c3fe1..bd2463c4e5b 100644 --- a/src/NServiceBus.TransportTests/When_failure_happens_after_send.cs +++ b/src/NServiceBus.TransportTests/When_failure_happens_after_send.cs @@ -49,6 +49,6 @@ await StartPump( await StopPump(); - Assert.False(messageEmitted); + Assert.That(messageEmitted, Is.False); } } diff --git a/src/NServiceBus.TransportTests/When_message_is_available.cs b/src/NServiceBus.TransportTests/When_message_is_available.cs index 3566bb2c4e2..fef4381c3bb 100644 --- a/src/NServiceBus.TransportTests/When_message_is_available.cs +++ b/src/NServiceBus.TransportTests/When_message_is_available.cs @@ -30,8 +30,11 @@ await StartPump( var messageContext = await onMessageInvoked.Task; - Assert.False(string.IsNullOrEmpty(messageContext.NativeMessageId), "Should pass the native message id"); - Assert.AreEqual("MyValue", messageContext.Headers["MyHeader"], "Should pass the message headers"); - Assert.AreEqual(new byte[] { 1, 2, 3 }, messageBody, "Should pass the body"); + Assert.Multiple(() => + { + Assert.That(string.IsNullOrEmpty(messageContext.NativeMessageId), Is.False, "Should pass the native message id"); + Assert.That(messageContext.Headers["MyHeader"], Is.EqualTo("MyValue"), "Should pass the message headers"); + Assert.That(messageBody, Is.EqualTo(new byte[] { 1, 2, 3 }), "Should pass the body"); + }); } } diff --git a/src/NServiceBus.TransportTests/When_modifying_headers_before_on_error.cs b/src/NServiceBus.TransportTests/When_modifying_headers_before_on_error.cs index 1367ab6d2e1..dd2cf01de87 100644 --- a/src/NServiceBus.TransportTests/When_modifying_headers_before_on_error.cs +++ b/src/NServiceBus.TransportTests/When_modifying_headers_before_on_error.cs @@ -33,6 +33,6 @@ await StartPump( var errorContext = await errorHandled.Task; - Assert.AreEqual("original", errorContext.Message.Headers["test-header"]); + Assert.That(errorContext.Message.Headers["test-header"], Is.EqualTo("original")); } } diff --git a/src/NServiceBus.TransportTests/When_modifying_headers_before_retry.cs b/src/NServiceBus.TransportTests/When_modifying_headers_before_retry.cs index aa79034303f..d861b612f64 100644 --- a/src/NServiceBus.TransportTests/When_modifying_headers_before_retry.cs +++ b/src/NServiceBus.TransportTests/When_modifying_headers_before_retry.cs @@ -39,6 +39,6 @@ await StartPump( var retryMessageContext = await retried.Task; - Assert.AreEqual("original", retryMessageContext.Headers["test-header"]); + Assert.That(retryMessageContext.Headers["test-header"], Is.EqualTo("original")); } } diff --git a/src/NServiceBus.TransportTests/When_modifying_headers_in_on_error.cs b/src/NServiceBus.TransportTests/When_modifying_headers_in_on_error.cs index f4f0e69a447..c18ead637ad 100644 --- a/src/NServiceBus.TransportTests/When_modifying_headers_in_on_error.cs +++ b/src/NServiceBus.TransportTests/When_modifying_headers_in_on_error.cs @@ -31,6 +31,6 @@ await StartPump( var retryMessageContext = await retried.Task; - Assert.AreEqual("original", retryMessageContext.Headers["test-header"]); + Assert.That(retryMessageContext.Headers["test-header"], Is.EqualTo("original")); } } diff --git a/src/NServiceBus.TransportTests/When_multiple_messages_are_available.cs b/src/NServiceBus.TransportTests/When_multiple_messages_are_available.cs index b39e3c893ee..0999f37edfc 100644 --- a/src/NServiceBus.TransportTests/When_multiple_messages_are_available.cs +++ b/src/NServiceBus.TransportTests/When_multiple_messages_are_available.cs @@ -55,7 +55,10 @@ await StartPump(async (context, _) => TestTimeoutCancellationToken.ThrowIfCancellationRequested(); } - Assert.AreEqual(concurrencyLevel, maximumConcurrentMessages, "should not process more messages than configured at once"); - Assert.AreEqual(concurrencyLevel * 2, messagesProcessed, "should process all enqueued messages"); + Assert.Multiple(() => + { + Assert.That(maximumConcurrentMessages, Is.EqualTo(concurrencyLevel), "should not process more messages than configured at once"); + Assert.That(messagesProcessed, Is.EqualTo(concurrencyLevel * 2), "should process all enqueued messages"); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_increased_after_pump_started.cs b/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_increased_after_pump_started.cs index 0e7139553bf..e1eabd84301 100644 --- a/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_increased_after_pump_started.cs +++ b/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_increased_after_pump_started.cs @@ -58,7 +58,10 @@ await StartPump(async (context, _) => TestTimeoutCancellationToken.ThrowIfCancellationRequested(); } - Assert.AreEqual(newConcurrencyLevel, maximumConcurrentMessages, "should not process more messages than configured at once"); - Assert.AreEqual(startConcurrencyLevel * 2, messagesProcessed, "should process all enqueued messages"); + Assert.Multiple(() => + { + Assert.That(maximumConcurrentMessages, Is.EqualTo(newConcurrencyLevel), "should not process more messages than configured at once"); + Assert.That(messagesProcessed, Is.EqualTo(startConcurrencyLevel * 2), "should process all enqueued messages"); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_increased_and_decreased_after_pump_started.cs b/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_increased_and_decreased_after_pump_started.cs index bae35b8cb51..a53b45a4d90 100644 --- a/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_increased_and_decreased_after_pump_started.cs +++ b/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_increased_and_decreased_after_pump_started.cs @@ -60,7 +60,10 @@ await StartPump(async (context, _) => TestTimeoutCancellationToken.ThrowIfCancellationRequested(); } - Assert.AreEqual(lastConcurrencyLevel, maximumConcurrentMessages, "should not process more messages than configured at once"); - Assert.AreEqual(startConcurrencyLevel * 2, messagesProcessed, "should process all enqueued messages"); + Assert.Multiple(() => + { + Assert.That(maximumConcurrentMessages, Is.EqualTo(lastConcurrencyLevel), "should not process more messages than configured at once"); + Assert.That(messagesProcessed, Is.EqualTo(startConcurrencyLevel * 2), "should process all enqueued messages"); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_lowered_after_pump_started.cs b/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_lowered_after_pump_started.cs index 7ea02d58303..50e7f91f551 100644 --- a/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_lowered_after_pump_started.cs +++ b/src/NServiceBus.TransportTests/When_multiple_messages_are_available_and_concurrency_is_lowered_after_pump_started.cs @@ -58,7 +58,10 @@ await StartPump(async (context, _) => TestTimeoutCancellationToken.ThrowIfCancellationRequested(); } - Assert.AreEqual(newConcurrencyLevel, maximumConcurrentMessages, "should not process more messages than configured at once"); - Assert.AreEqual(startConcurrencyLevel * 2, messagesProcessed, "should process all enqueued messages"); + Assert.Multiple(() => + { + Assert.That(maximumConcurrentMessages, Is.EqualTo(newConcurrencyLevel), "should not process more messages than configured at once"); + Assert.That(messagesProcessed, Is.EqualTo(startConcurrencyLevel * 2), "should process all enqueued messages"); + }); } } \ No newline at end of file diff --git a/src/NServiceBus.TransportTests/When_on_error_throws.cs b/src/NServiceBus.TransportTests/When_on_error_throws.cs index a8304fcae4d..ec55488cff3 100644 --- a/src/NServiceBus.TransportTests/When_on_error_throws.cs +++ b/src/NServiceBus.TransportTests/When_on_error_throws.cs @@ -54,11 +54,14 @@ await StartPump( await retried.Task; - Assert.True(criticalErrorCalled, "Should invoke critical error"); - Assert.AreEqual($"Failed to execute recoverability policy for message with native ID: `{nativeMessageId}`", criticalErrorMessage); - Assert.AreEqual(exceptionFromOnError, criticalErrorException); + Assert.Multiple(() => + { + Assert.That(criticalErrorCalled, Is.True, "Should invoke critical error"); + Assert.That(criticalErrorMessage, Is.EqualTo($"Failed to execute recoverability policy for message with native ID: `{nativeMessageId}`")); + Assert.That(criticalErrorException, Is.EqualTo(exceptionFromOnError)); + }); var logItemsAboveInfo = LogFactory.LogItems.Where(item => item.Level > LogLevel.Info).Select(log => $"{log.Level}: {log.Message}").ToArray(); - Assert.AreEqual(0, logItemsAboveInfo.Length, "Transport should not log anything above LogLevel.Info:" + string.Join(Environment.NewLine, logItemsAboveInfo)); + Assert.That(logItemsAboveInfo, Is.Empty, "Transport should not log anything above LogLevel.Info:" + string.Join(Environment.NewLine, logItemsAboveInfo)); } } diff --git a/src/NServiceBus.TransportTests/When_on_message_throws.cs b/src/NServiceBus.TransportTests/When_on_message_throws.cs index 70f5390c1a9..6b66ea1cd51 100644 --- a/src/NServiceBus.TransportTests/When_on_message_throws.cs +++ b/src/NServiceBus.TransportTests/When_on_message_throws.cs @@ -29,8 +29,11 @@ await StartPump( var errorContext = await onErrorCalled.Task; - Assert.AreEqual(errorContext.Exception.Message, "Simulated exception", "Should preserve the exception"); - Assert.AreEqual(1, errorContext.ImmediateProcessingFailures, "Should track the number of delivery attempts"); - Assert.AreEqual("MyValue", errorContext.Message.Headers["MyHeader"], "Should pass the message headers"); + Assert.Multiple(() => + { + Assert.That(errorContext.Exception.Message, Is.EqualTo("Simulated exception"), "Should preserve the exception"); + Assert.That(errorContext.ImmediateProcessingFailures, Is.EqualTo(1), "Should track the number of delivery attempts"); + Assert.That(errorContext.Message.Headers["MyHeader"], Is.EqualTo("MyValue"), "Should pass the message headers"); + }); } } diff --git a/src/NServiceBus.TransportTests/When_on_message_throws_after_delayed_retry.cs b/src/NServiceBus.TransportTests/When_on_message_throws_after_delayed_retry.cs index b0cfc374578..2c744026cb2 100644 --- a/src/NServiceBus.TransportTests/When_on_message_throws_after_delayed_retry.cs +++ b/src/NServiceBus.TransportTests/When_on_message_throws_after_delayed_retry.cs @@ -38,6 +38,6 @@ await StartPump( var errorContext = await sentDelayedMessage.Task; - Assert.AreEqual(1, errorContext.ImmediateProcessingFailures, "Should track delivery attempts between immediate retries"); + Assert.That(errorContext.ImmediateProcessingFailures, Is.EqualTo(1), "Should track delivery attempts between immediate retries"); } } diff --git a/src/NServiceBus.TransportTests/When_on_message_throws_after_immediate_retry.cs b/src/NServiceBus.TransportTests/When_on_message_throws_after_immediate_retry.cs index 111e606779f..68fd71df2fc 100644 --- a/src/NServiceBus.TransportTests/When_on_message_throws_after_immediate_retry.cs +++ b/src/NServiceBus.TransportTests/When_on_message_throws_after_immediate_retry.cs @@ -35,6 +35,6 @@ await StartPump( var errorContext = await maxAttemptsReached.Task; - Assert.AreEqual(attempts, errorContext.ImmediateProcessingFailures, "Should track delivery attempts between immediate retries"); + Assert.That(errorContext.ImmediateProcessingFailures, Is.EqualTo(attempts), "Should track delivery attempts between immediate retries"); } } diff --git a/src/NServiceBus.TransportTests/When_receiving_message.cs b/src/NServiceBus.TransportTests/When_receiving_message.cs index 75b27f79834..28a6fdcb503 100644 --- a/src/NServiceBus.TransportTests/When_receiving_message.cs +++ b/src/NServiceBus.TransportTests/When_receiving_message.cs @@ -18,7 +18,7 @@ public async Task Should_expose_receiving_address(TransportTransactionMode trans await StartPump( (context, _) => { - Assert.AreEqual(receiver.ReceiveAddress, context.ReceiveAddress); + Assert.That(context.ReceiveAddress, Is.EqualTo(receiver.ReceiveAddress)); throw new Exception("Simulated exception"); }, (context, _) => @@ -31,6 +31,6 @@ await StartPump( await SendMessage(InputQueueName); var errorContext = await onError.Task; - Assert.AreEqual(receiver.ReceiveAddress, errorContext.ReceiveAddress); + Assert.That(errorContext.ReceiveAddress, Is.EqualTo(receiver.ReceiveAddress)); } } diff --git a/src/NServiceBus.TransportTests/When_scope_complete_throws.cs b/src/NServiceBus.TransportTests/When_scope_complete_throws.cs index 17e63ed1d81..2daeecda5a9 100644 --- a/src/NServiceBus.TransportTests/When_scope_complete_throws.cs +++ b/src/NServiceBus.TransportTests/When_scope_complete_throws.cs @@ -34,11 +34,14 @@ await StartPump( var errorContext = await onErrorCalled.Task; - Assert.IsInstanceOf(errorContext.Exception); - - // since some transports doesn't have native retry counters we can't expect the attempts to be fully consistent since if - // dispose throws the message might be picked up before the counter is incremented - Assert.LessOrEqual(1, errorContext.ImmediateProcessingFailures); + Assert.Multiple(() => + { + Assert.That(errorContext.Exception, Is.InstanceOf()); + + // since some transports doesn't have native retry counters we can't expect the attempts to be fully consistent since if + // dispose throws the message might be picked up before the counter is incremented + Assert.That(errorContext.ImmediateProcessingFailures, Is.LessThanOrEqualTo(1)); + }); } class EnlistmentWhichFailsDuringPrepare : IEnlistmentNotification diff --git a/src/NServiceBus.TransportTests/When_scope_throws_after_successful_message_processing.cs b/src/NServiceBus.TransportTests/When_scope_throws_after_successful_message_processing.cs index 4f91ed87662..5f7f7737a95 100644 --- a/src/NServiceBus.TransportTests/When_scope_throws_after_successful_message_processing.cs +++ b/src/NServiceBus.TransportTests/When_scope_throws_after_successful_message_processing.cs @@ -40,8 +40,11 @@ await StartPump( var errorContext = await secondFailure.Task; - Assert.IsInstanceOf(errorContext.Exception); - Assert.LessOrEqual(2, errorContext.ImmediateProcessingFailures); + Assert.Multiple(() => + { + Assert.That(errorContext.Exception, Is.InstanceOf()); + Assert.That(errorContext.ImmediateProcessingFailures, Is.LessThanOrEqualTo(2)); + }); } } diff --git a/src/NServiceBus.TransportTests/When_setting_context_items.cs b/src/NServiceBus.TransportTests/When_setting_context_items.cs index 5da93eda00a..9d038633172 100644 --- a/src/NServiceBus.TransportTests/When_setting_context_items.cs +++ b/src/NServiceBus.TransportTests/When_setting_context_items.cs @@ -32,6 +32,6 @@ await StartPump( var errorContext = await onError.Task; - Assert.AreEqual("MyValue", errorContext.Extensions.Get("MyKey")); + Assert.That(errorContext.Extensions.Get("MyKey"), Is.EqualTo("MyValue")); } } diff --git a/src/NServiceBus.TransportTests/When_stop_canceled_on_error.cs b/src/NServiceBus.TransportTests/When_stop_canceled_on_error.cs index 4af1163e57b..629926d7df1 100644 --- a/src/NServiceBus.TransportTests/When_stop_canceled_on_error.cs +++ b/src/NServiceBus.TransportTests/When_stop_canceled_on_error.cs @@ -37,6 +37,6 @@ await StartPump( await StopPump(new CancellationToken(true)); - Assert.False(criticalErrorInvoked, "Critical error should not be invoked"); + Assert.That(criticalErrorInvoked, Is.False, "Critical error should not be invoked"); } } diff --git a/src/NServiceBus.TransportTests/When_stop_canceled_on_message.cs b/src/NServiceBus.TransportTests/When_stop_canceled_on_message.cs index e3e5075874c..f9fae53c141 100644 --- a/src/NServiceBus.TransportTests/When_stop_canceled_on_message.cs +++ b/src/NServiceBus.TransportTests/When_stop_canceled_on_message.cs @@ -36,6 +36,6 @@ await StartPump( await StopPump(new CancellationToken(true)); - Assert.False(recoverabilityInvoked, "Recoverability should not have been invoked."); + Assert.That(recoverabilityInvoked, Is.False, "Recoverability should not have been invoked."); } } diff --git a/src/NServiceBus.TransportTests/When_stopping_on_error.cs b/src/NServiceBus.TransportTests/When_stopping_on_error.cs index 533a3b85948..443206f9bee 100644 --- a/src/NServiceBus.TransportTests/When_stopping_on_error.cs +++ b/src/NServiceBus.TransportTests/When_stopping_on_error.cs @@ -40,6 +40,6 @@ await StartPump( await pumpTask; - Assert.False(onErrorToken.IsCancellationRequested); + Assert.That(onErrorToken.IsCancellationRequested, Is.False); } } diff --git a/src/NServiceBus.TransportTests/When_stopping_on_message.cs b/src/NServiceBus.TransportTests/When_stopping_on_message.cs index dc8f22ff67c..acc402fbdbb 100644 --- a/src/NServiceBus.TransportTests/When_stopping_on_message.cs +++ b/src/NServiceBus.TransportTests/When_stopping_on_message.cs @@ -38,6 +38,6 @@ await StartPump( await pumpTask; - Assert.False(onMessageToken.IsCancellationRequested); + Assert.That(onMessageToken.IsCancellationRequested, Is.False); } } diff --git a/src/NServiceBus.TransportTests/When_transaction_level_TransactionScope.cs b/src/NServiceBus.TransportTests/When_transaction_level_TransactionScope.cs index 488833c09a1..f345798b3ec 100644 --- a/src/NServiceBus.TransportTests/When_transaction_level_TransactionScope.cs +++ b/src/NServiceBus.TransportTests/When_transaction_level_TransactionScope.cs @@ -29,7 +29,10 @@ await StartPump( await messageProcessed.Task; - Assert.NotNull(currentTransaction); - Assert.AreSame(currentTransaction, contextTransaction); + Assert.Multiple(() => + { + Assert.That(currentTransaction, Is.Not.Null); + Assert.That(contextTransaction, Is.SameAs(currentTransaction)); + }); } } diff --git a/src/NServiceBus.TransportTests/When_using_unicode_characters_in_headers.cs b/src/NServiceBus.TransportTests/When_using_unicode_characters_in_headers.cs index 5bec1e5815f..3bdf0f532c9 100644 --- a/src/NServiceBus.TransportTests/When_using_unicode_characters_in_headers.cs +++ b/src/NServiceBus.TransportTests/When_using_unicode_characters_in_headers.cs @@ -32,7 +32,7 @@ await StartPump( var messageContext = await messageProcessed.Task; - Assert.IsNotEmpty(messageContext.Headers); - CollectionAssert.IsSupersetOf(messageContext.Headers, headers); + Assert.That(messageContext.Headers, Is.Not.Empty); + Assert.That(messageContext.Headers, Is.SupersetOf(headers)); } } From 8d5b11b3eaaa367081622428da038d13d2686f29 Mon Sep 17 00:00:00 2001 From: danielmarbach Date: Mon, 19 Aug 2024 16:20:21 +0200 Subject: [PATCH 2/2] NUnit4 upgrade (#7142) * Lower range to NUnit 4.1.0 * Fix leftover assert that had now analyzer * Bump NUnit from 3.14.0 to 4.1.0 in /src --------- Co-authored-by: Daniel Marbach (cherry picked from commit 9424fa883a7f1393b4a4d6b7c1f9871616ce3fc9) --- .../NServiceBus.AcceptanceTesting.csproj | 2 +- .../Recoverability/When_message_fails_retries.cs | 2 +- .../NServiceBus.ContainerTests.csproj | 2 +- .../NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj | 2 +- src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj | 2 +- .../NServiceBus.PersistenceTests.csproj | 2 +- .../NServiceBus.TransportTests.csproj | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/NServiceBus.AcceptanceTesting/NServiceBus.AcceptanceTesting.csproj b/src/NServiceBus.AcceptanceTesting/NServiceBus.AcceptanceTesting.csproj index 821d60a7a7c..cd39c07aba1 100644 --- a/src/NServiceBus.AcceptanceTesting/NServiceBus.AcceptanceTesting.csproj +++ b/src/NServiceBus.AcceptanceTesting/NServiceBus.AcceptanceTesting.csproj @@ -12,7 +12,7 @@ - + diff --git a/src/NServiceBus.AcceptanceTests/Recoverability/When_message_fails_retries.cs b/src/NServiceBus.AcceptanceTests/Recoverability/When_message_fails_retries.cs index e4f98bb4985..5f7177e57a9 100644 --- a/src/NServiceBus.AcceptanceTests/Recoverability/When_message_fails_retries.cs +++ b/src/NServiceBus.AcceptanceTests/Recoverability/When_message_fails_retries.cs @@ -25,8 +25,8 @@ public void Should_forward_message_to_error_queue() { Assert.That(exception.FailedMessage.Headers[Headers.EnclosedMessageTypes], Is.EqualTo(typeof(MessageWhichFailsRetries).AssemblyQualifiedName)); Assert.That(exception.FailedMessage.MessageId, Is.EqualTo(testContext.PhysicalMessageId)); + Assert.That(exception.FailedMessage.Exception, Is.AssignableFrom()); }); - Assert.IsAssignableFrom(typeof(SimulatedException), exception.FailedMessage.Exception); Assert.That(testContext.Logs.Count(l => l.Message .StartsWith($"Moving message '{testContext.PhysicalMessageId}' to the error queue 'error' because processing failed due to an exception:")), Is.EqualTo(1)); diff --git a/src/NServiceBus.ContainerTests/NServiceBus.ContainerTests.csproj b/src/NServiceBus.ContainerTests/NServiceBus.ContainerTests.csproj index 7ba5b295ce1..2b84364d165 100644 --- a/src/NServiceBus.ContainerTests/NServiceBus.ContainerTests.csproj +++ b/src/NServiceBus.ContainerTests/NServiceBus.ContainerTests.csproj @@ -13,7 +13,7 @@ - + diff --git a/src/NServiceBus.Core.Analyzer.Tests.Roslyn4/NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj b/src/NServiceBus.Core.Analyzer.Tests.Roslyn4/NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj index 99cb73ace15..e842260a9ae 100644 --- a/src/NServiceBus.Core.Analyzer.Tests.Roslyn4/NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj +++ b/src/NServiceBus.Core.Analyzer.Tests.Roslyn4/NServiceBus.Core.Analyzer.Tests.Roslyn4.csproj @@ -16,7 +16,7 @@ - + diff --git a/src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj b/src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj index b37d418dadc..64108410862 100644 --- a/src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj +++ b/src/NServiceBus.Core.Tests/NServiceBus.Core.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/src/NServiceBus.PersistenceTests/NServiceBus.PersistenceTests.csproj b/src/NServiceBus.PersistenceTests/NServiceBus.PersistenceTests.csproj index 850b67eb2bc..79bbdb19371 100644 --- a/src/NServiceBus.PersistenceTests/NServiceBus.PersistenceTests.csproj +++ b/src/NServiceBus.PersistenceTests/NServiceBus.PersistenceTests.csproj @@ -13,7 +13,7 @@ - + diff --git a/src/NServiceBus.TransportTests/NServiceBus.TransportTests.csproj b/src/NServiceBus.TransportTests/NServiceBus.TransportTests.csproj index 8fc7c14ce08..aaf9030efa3 100644 --- a/src/NServiceBus.TransportTests/NServiceBus.TransportTests.csproj +++ b/src/NServiceBus.TransportTests/NServiceBus.TransportTests.csproj @@ -11,7 +11,7 @@ - +