diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs index a7fc128737..8f3170025a 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -50,9 +52,9 @@ public void AddSubDirectoriesShouldReturnSubDirectoriesInDfsOrder() assemblyResolver.AddSubdirectories(path, searchDirectories); // Assert. - Verify(searchDirectories.Count == 4); + searchDirectories.Count.Should().Be(4); - Verify(resultDirectories.SequenceEqual(searchDirectories, StringComparer.OrdinalIgnoreCase)); + resultDirectories.SequenceEqual(searchDirectories, StringComparer.OrdinalIgnoreCase).Should().BeTrue(); } public void OnResolveShouldAddSearchDirectoryListOnANeedToBasis() @@ -98,37 +100,37 @@ public void OnResolveShouldAddSearchDirectoryListOnANeedToBasis() { // First time SearchAssemblyInTheFollowingLocation should get call with one directory which is in // m_searchDirectories variable - Verify(listPath.Count == 1); - Verify(string.Equals(listPath[0], dummyDirectories[0], StringComparison.OrdinalIgnoreCase)); + listPath.Count.Should().Be(1); + string.Equals(listPath[0], dummyDirectories[0], StringComparison.OrdinalIgnoreCase).Should().BeTrue(); count++; } else if (count == 1) { // Second time SearchAssemblyInTheFollowingLocation should get call with directory C:\unitTesting // and with all its sub directory, as its isRecursive property is true - Verify(listPath.Count == 3); - Verify(string.Equals(listPath[0], @"C:\unitTesting", StringComparison.OrdinalIgnoreCase)); - Verify(string.Equals(listPath[1], @"C:\unitTesting\a", StringComparison.OrdinalIgnoreCase)); - Verify(string.Equals(listPath[2], @"C:\unitTesting\b", StringComparison.OrdinalIgnoreCase)); + listPath.Count.Should().Be(3); + string.Equals(listPath[0], @"C:\unitTesting", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); + string.Equals(listPath[1], @"C:\unitTesting\a", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); + string.Equals(listPath[2], @"C:\unitTesting\b", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); count++; } else if (count == 2) { // Third time SearchAssemblyInTheFollowingLocation should get call with directory C:\FunctionalTesting // as its isRecursive property is false - Verify(listPath.Count == 1); - Verify(string.Equals(listPath[0], @"C:\FunctionalTesting", StringComparison.OrdinalIgnoreCase)); + listPath.Count.Should().Be(1); + string.Equals(listPath[0], @"C:\FunctionalTesting", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); count++; } else if (count == 3) { // call will come here when we will call onResolve second time. - Verify(listPath.Count == 5); - Verify(string.Equals(listPath[0], dummyDirectories[0], StringComparison.OrdinalIgnoreCase)); - Verify(string.Equals(listPath[1], @"C:\unitTesting", StringComparison.OrdinalIgnoreCase)); - Verify(string.Equals(listPath[2], @"C:\unitTesting\a", StringComparison.OrdinalIgnoreCase)); - Verify(string.Equals(listPath[3], @"C:\unitTesting\b", StringComparison.OrdinalIgnoreCase)); - Verify(string.Equals(listPath[4], @"C:\FunctionalTesting", StringComparison.OrdinalIgnoreCase)); + listPath.Count.Should().Be(5); + string.Equals(listPath[0], dummyDirectories[0], StringComparison.OrdinalIgnoreCase).Should().BeTrue(); + string.Equals(listPath[1], @"C:\unitTesting", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); + string.Equals(listPath[2], @"C:\unitTesting\a", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); + string.Equals(listPath[3], @"C:\unitTesting\b", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); + string.Equals(listPath[4], @"C:\FunctionalTesting", StringComparison.OrdinalIgnoreCase).Should().BeTrue(); count++; } @@ -170,8 +172,8 @@ public void ReflectionOnlyOnResolveShouldNotReturnACachedDefaultLoadedAssembly() // Simulate loading the assembly in default context first. assemblyResolver.OnResolve(null, new ResolveEventArgs(currentAssembly.FullName)); - Verify(isAssemblyLoaded); - Verify(!isAssemblyReflectionOnlyLoaded); + isAssemblyLoaded.Should().BeTrue(); + isAssemblyReflectionOnlyLoaded.Should().BeFalse(); // Reset. isAssemblyLoaded = false; @@ -180,8 +182,8 @@ public void ReflectionOnlyOnResolveShouldNotReturnACachedDefaultLoadedAssembly() assemblyResolver.ReflectionOnlyOnResolve(null!, new ResolveEventArgs(currentAssembly.FullName)); // The below assertions ensure that a cached version is not returned out because it actually Reflection only loads the assembly. - Verify(!isAssemblyLoaded); - Verify(isAssemblyReflectionOnlyLoaded); + isAssemblyLoaded.Should().BeFalse(); + isAssemblyReflectionOnlyLoaded.Should().BeTrue(); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/AssemblyLoadWorkerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/AssemblyLoadWorkerTests.cs index 96f7112734..ce4f7054b0 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/AssemblyLoadWorkerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/AssemblyLoadWorkerTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; @@ -34,7 +36,7 @@ public void GetFullPathToDependentAssembliesShouldReturnV1FrameworkAssembly() // Assert. string utfAssembly = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll"); - Verify(dependentAssemblies.Contains(utfAssembly)); + dependentAssemblies.Should().Contain(utfAssembly); } public void GetFullPathToDependentAssembliesShouldReturnV1FrameworkReferencedInADependency() @@ -93,7 +95,7 @@ public void GetFullPathToDependentAssembliesShouldReturnV1FrameworkReferencedInA // Assert. string utfAssembly = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll"); - Verify(dependentAssemblies.Contains(utfAssembly)); + dependentAssemblies.Should().Contain(utfAssembly); } #region Testable Implementations diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/DeploymentItemTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/DeploymentItemTests.cs index 4eb8834a36..0923c87717 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/DeploymentItemTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/DeploymentItemTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; @@ -14,14 +16,14 @@ public void EqualsShouldReturnFalseIfOtherItemIsNull() { DeploymentItem item = new("e:\\temp\\temp1.dll"); - Verify(!item.Equals(null)); + item.Equals(null).Should().BeFalse(); } public void EqualsShouldReturnFalseIfOtherItemIsNotDeploymentItem() { DeploymentItem item = new("e:\\temp\\temp1.dll"); - Verify(!item.Equals(new DeploymentItemTests())); + item.Equals(new DeploymentItemTests()).Should().BeFalse(); } public void EqualsShouldReturnFalseIfSourcePathIsDifferent() @@ -29,7 +31,7 @@ public void EqualsShouldReturnFalseIfSourcePathIsDifferent() DeploymentItem item1 = new("e:\\temp\\temp1.dll"); DeploymentItem item2 = new("e:\\temp\\temp2.dll"); - Verify(!item1.Equals(item2)); + item1.Equals(item2).Should().BeFalse(); } public void EqualsShouldReturnFalseIfRelativeOutputDirectoryIsDifferent() @@ -37,7 +39,7 @@ public void EqualsShouldReturnFalseIfRelativeOutputDirectoryIsDifferent() DeploymentItem item1 = new("e:\\temp\\temp1.dll", "foo1"); DeploymentItem item2 = new("e:\\temp\\temp1.dll", "foo2"); - Verify(!item1.Equals(item2)); + item1.Equals(item2).Should().BeFalse(); } public void EqualsShouldReturnTrueIfSourcePathDiffersByCase() @@ -45,7 +47,7 @@ public void EqualsShouldReturnTrueIfSourcePathDiffersByCase() DeploymentItem item1 = new("e:\\temp\\temp1.dll"); DeploymentItem item2 = new("e:\\temp\\Temp1.dll"); - Verify(item1.Equals(item2)); + item1.Equals(item2).Should().BeTrue(); } public void EqualsShouldReturnTrueIfRelativeOutputDirectoryDiffersByCase() @@ -53,7 +55,7 @@ public void EqualsShouldReturnTrueIfRelativeOutputDirectoryDiffersByCase() DeploymentItem item1 = new("e:\\temp\\temp1.dll", "foo1"); DeploymentItem item2 = new("e:\\temp\\temp1.dll", "Foo1"); - Verify(item1.Equals(item2)); + item1.Equals(item2).Should().BeTrue(); } public void EqualsShouldReturnTrueIfSourceAndRelativeOutputDirectoryAreSame() @@ -61,7 +63,7 @@ public void EqualsShouldReturnTrueIfSourceAndRelativeOutputDirectoryAreSame() DeploymentItem item1 = new("e:\\temp\\temp1.dll", "foo1"); DeploymentItem item2 = new("e:\\temp\\temp1.dll", "foo1"); - Verify(item1.Equals(item2)); + item1.Equals(item2).Should().BeTrue(); } public void GetHashCodeShouldConsiderSourcePathAndRelativeOutputDirectory() @@ -70,7 +72,7 @@ public void GetHashCodeShouldConsiderSourcePathAndRelativeOutputDirectory() string relativeOutputDirectory = "foo1"; DeploymentItem item = new(sourcePath, relativeOutputDirectory); - Verify(sourcePath.GetHashCode() + relativeOutputDirectory.GetHashCode() == item.GetHashCode()); + item.GetHashCode().Should().Be(sourcePath.GetHashCode() + relativeOutputDirectory.GetHashCode()); } public void ToStringShouldReturnDeploymentItemIfRelativeOutputDirectoryIsNotSpecified() @@ -78,7 +80,7 @@ public void ToStringShouldReturnDeploymentItemIfRelativeOutputDirectoryIsNotSpec string sourcePath = "e:\\temp\\temp1.dll"; DeploymentItem item = new(sourcePath); - Verify(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentItem, sourcePath) == item.ToString()); + item.ToString().Should().Be(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentItem, sourcePath)); } public void ToStringShouldReturnDeploymentItemAndRelativeOutputDirectory() @@ -87,6 +89,6 @@ public void ToStringShouldReturnDeploymentItemAndRelativeOutputDirectory() string relativeOutputDirectory = "foo1"; DeploymentItem item = new(sourcePath, relativeOutputDirectory); - Verify(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentItemWithOutputDirectory, sourcePath, relativeOutputDirectory) == item.ToString()); + item.ToString().Should().Be(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentItemWithOutputDirectory, sourcePath, relativeOutputDirectory)); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/TestRunDirectoriesTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/TestRunDirectoriesTests.cs index 20de9c7d6f..381a93e55b 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/TestRunDirectoriesTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Deployment/TestRunDirectoriesTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; using TestFramework.ForTestingMSTest; @@ -11,9 +13,12 @@ public class TestRunDirectoriesTests : TestContainer { private readonly TestRunDirectories _testRunDirectories = new(@"C:\temp", @"C:\temp\asm.dll", isAppDomainCreationDisabled: false); - public void InDirectoryShouldReturnCorrectDirectory() => Verify(_testRunDirectories.InDirectory == @"C:\temp\In"); + public void InDirectoryShouldReturnCorrectDirectory() + => _testRunDirectories.InDirectory.Should().Be(@"C:\temp\In"); - public void OutDirectoryShouldReturnCorrectDirectory() => Verify(_testRunDirectories.OutDirectory == @"C:\temp\Out"); + public void OutDirectoryShouldReturnCorrectDirectory() + => _testRunDirectories.OutDirectory.Should().Be(@"C:\temp\Out"); - public void InMachineNameDirectoryShouldReturnMachineSpecificDeploymentDirectory() => Verify(Path.Combine(@"C:\temp\In", Environment.MachineName) == _testRunDirectories.InMachineNameDirectory); + public void InMachineNameDirectoryShouldReturnMachineSpecificDeploymentDirectory() + => _testRunDirectories.InMachineNameDirectory.Should().Be(Path.Combine(@"C:\temp\In", Environment.MachineName)); } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs index 74b7a3f349..2b81567eff 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorTests.cs @@ -3,6 +3,8 @@ using System.Collections.ObjectModel; +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; @@ -67,7 +69,7 @@ public void ConstructorShouldPopulateSettings() // Constructor has the side effect of populating the passed settings to MSTestSettings.CurrentSettings _ = new AssemblyEnumerator(adapterSettings); - Verify(MSTestSettings.CurrentSettings.TestSettingsFile == "DummyPath\\TestSettings1.testsettings"); + MSTestSettings.CurrentSettings.TestSettingsFile.Should().Be("DummyPath\\TestSettings1.testsettings"); } #endregion @@ -81,7 +83,7 @@ public void GetTypesShouldReturnEmptyArrayWhenNoDeclaredTypes() // Setup mocks mockAssembly.Setup(a => a.GetTypes()).Returns([]); - Verify(AssemblyEnumerator.GetTypes(mockAssembly.Object).Length == 0); + AssemblyEnumerator.GetTypes(mockAssembly.Object).Length.Should().Be(0); } public void GetTypesShouldReturnSetOfDefinedTypes() @@ -94,7 +96,7 @@ public void GetTypesShouldReturnSetOfDefinedTypes() mockAssembly.Setup(a => a.GetTypes()).Returns(expectedTypes); Type[] types = AssemblyEnumerator.GetTypes(mockAssembly.Object); - Verify(expectedTypes.SequenceEqual(types)); + expectedTypes.SequenceEqual(types).Should().BeTrue(); } #endregion @@ -112,7 +114,7 @@ public void EnumerateAssemblyShouldReturnEmptyListWhenNoDeclaredTypes() AssemblyEnumerationResult result = _assemblyEnumerator.EnumerateAssembly("DummyAssembly"); _warnings.AddRange(result.Warnings); - Verify(result.TestElements.Count == 0); + result.TestElements.Count.Should().Be(0); } public void EnumerateAssemblyShouldReturnEmptyListWhenNoTestElementsInAType() @@ -132,7 +134,7 @@ public void EnumerateAssemblyShouldReturnEmptyListWhenNoTestElementsInAType() AssemblyEnumerationResult result = _assemblyEnumerator.EnumerateAssembly("DummyAssembly"); _warnings.AddRange(result.Warnings); - Verify(result.TestElements.Count == 0); + result.TestElements.Count.Should().Be(0); } public void EnumerateAssemblyShouldReturnTestElementsForAType() @@ -154,7 +156,7 @@ public void EnumerateAssemblyShouldReturnTestElementsForAType() AssemblyEnumerationResult result = testableAssemblyEnumerator.EnumerateAssembly("DummyAssembly"); _warnings.AddRange(result.Warnings); - Verify(new Collection { unitTestElement }.SequenceEqual(result.TestElements)); + new Collection { unitTestElement }.SequenceEqual(result.TestElements).Should().BeTrue(); } public void EnumerateAssemblyShouldReturnMoreThanOneTestElementForAType() @@ -177,7 +179,7 @@ public void EnumerateAssemblyShouldReturnMoreThanOneTestElementForAType() AssemblyEnumerationResult result = testableAssemblyEnumerator.EnumerateAssembly("DummyAssembly"); _warnings.AddRange(result.Warnings); - Verify(expectedTestElements.SequenceEqual(result.TestElements)); + expectedTestElements.SequenceEqual(result.TestElements).Should().BeTrue(); } public void EnumerateAssemblyShouldReturnMoreThanOneTestElementForMoreThanOneType() @@ -202,7 +204,7 @@ public void EnumerateAssemblyShouldReturnMoreThanOneTestElementForMoreThanOneTyp expectedTestElements.Add(unitTestElement); expectedTestElements.Add(unitTestElement); - Verify(expectedTestElements.SequenceEqual(result.TestElements)); + expectedTestElements.SequenceEqual(result.TestElements).Should().BeTrue(); } public void EnumerateAssemblyShouldNotLogWarningsIfNonePresent() @@ -222,7 +224,7 @@ public void EnumerateAssemblyShouldNotLogWarningsIfNonePresent() AssemblyEnumerationResult result = testableAssemblyEnumerator.EnumerateAssembly("DummyAssembly"); _warnings.AddRange(result.Warnings); - Verify(result.Warnings.Count == 0); + result.Warnings.Count.Should().Be(0); } public void EnumerateAssemblyShouldLogWarningsIfPresent() @@ -246,7 +248,7 @@ public void EnumerateAssemblyShouldLogWarningsIfPresent() AssemblyEnumerationResult result = testableAssemblyEnumerator.EnumerateAssembly("DummyAssembly"); - Verify(warningsFromTypeEnumerator.SequenceEqual(result.Warnings)); + warningsFromTypeEnumerator.SequenceEqual(result.Warnings).Should().BeTrue(); } public void EnumerateAssemblyShouldHandleExceptionsWhileEnumeratingAType() @@ -267,13 +269,13 @@ public void EnumerateAssemblyShouldHandleExceptionsWhileEnumeratingAType() AssemblyEnumerationResult result = testableAssemblyEnumerator.EnumerateAssembly("DummyAssembly"); _warnings.AddRange(result.Warnings); - Verify(result.Warnings.Contains( + result.Warnings.Contains( string.Format( CultureInfo.CurrentCulture, Resource.CouldNotInspectTypeDuringDiscovery, typeof(InternalTestClass), "DummyAssembly", - exception.Message))); + exception.Message)).Should().BeTrue(); } private static Mock CreateMockTestableAssembly() diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs index 80b90fc42e..9e8e462958 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; @@ -34,9 +36,11 @@ protected override void Dispose(bool disposing) } } - public void GetTestsShouldReturnNullIfAssemblyNameIsNull() => Verify(AssemblyEnumeratorWrapper.GetTests(null, null, _mockTestSourceHandler.Object, out _) is null); + public void GetTestsShouldReturnNullIfAssemblyNameIsNull() + => AssemblyEnumeratorWrapper.GetTests(null, null, _mockTestSourceHandler.Object, out _).Should().BeNull(); - public void GetTestsShouldReturnNullIfAssemblyNameIsEmpty() => Verify(AssemblyEnumeratorWrapper.GetTests(string.Empty, null, _mockTestSourceHandler.Object, out _) is null); + public void GetTestsShouldReturnNullIfAssemblyNameIsEmpty() + => AssemblyEnumeratorWrapper.GetTests(string.Empty, null, _mockTestSourceHandler.Object, out _).Should().BeNull(); public void GetTestsShoulThrowIfSourceFileDoesNotExistInContext() { @@ -48,8 +52,8 @@ public void GetTestsShoulThrowIfSourceFileDoesNotExistInContext() _testablePlatformServiceProvider.MockFileOperations.Setup(fo => fo.DoesFileExist(assemblyName)) .Returns(false); - FileNotFoundException exception = VerifyThrows(() => AssemblyEnumeratorWrapper.GetTests(assemblyName, null, _mockTestSourceHandler.Object, out _)); - Verify(exception.Message == string.Format(CultureInfo.CurrentCulture, Resource.TestAssembly_FileDoesNotExist, assemblyName)); + FileNotFoundException exception = Assert.Throws(() => AssemblyEnumeratorWrapper.GetTests(assemblyName, null, _mockTestSourceHandler.Object, out _)); + exception.Message.Should().Be(string.Format(CultureInfo.CurrentCulture, Resource.TestAssembly_FileDoesNotExist, assemblyName)); } public void GetTestsShouldReturnNullIfSourceDoesNotReferenceUnitTestFrameworkAssembly() @@ -59,7 +63,7 @@ public void GetTestsShouldReturnNullIfSourceDoesNotReferenceUnitTestFrameworkAss // Setup mocks. SetupMocks(assemblyName, doesFileExist: true, isAssemblyReferenced: false); - Verify(AssemblyEnumeratorWrapper.GetTests(assemblyName, null, _mockTestSourceHandler.Object, out _) is null); + AssemblyEnumeratorWrapper.GetTests(assemblyName, null, _mockTestSourceHandler.Object, out _).Should().BeNull(); } public void GetTestsShouldReturnTestElements() @@ -71,10 +75,10 @@ public void GetTestsShouldReturnTestElements() ICollection? tests = AssemblyEnumeratorWrapper.GetTests(assemblyName, null, _mockTestSourceHandler.Object, out _); - Verify(tests is not null); + tests.Should().NotBeNull(); // Validate if the current test is enumerated in this list. - Verify(tests.Any(t => t.TestMethod.Name == "ValidTestMethod")); + tests.Any(t => t.TestMethod.Name == "ValidTestMethod").Should().BeTrue(); } public void GetTestsShouldCreateAnIsolatedInstanceOfAssemblyEnumerator() @@ -104,8 +108,8 @@ public void GetTestsShouldReturnNullIfSourceFileCannotBeLoaded() _testablePlatformServiceProvider.MockFileOperations.Setup(fo => fo.DoesFileExist(assemblyName)) .Returns(true); - Exception fileNotFoundException = Assert.Throws(() => AssemblyEnumeratorWrapper.GetTests(assemblyName, null, _mockTestSourceHandler.Object, out _)); - Verify(fileNotFoundException.Message == string.Format(CultureInfo.CurrentCulture, Resource.TestAssembly_FileDoesNotExist, fullFilePath)); + FileNotFoundException fileNotFoundException = Assert.Throws(() => AssemblyEnumeratorWrapper.GetTests(assemblyName, null, _mockTestSourceHandler.Object, out _)); + fileNotFoundException.Message.Should().Be(string.Format(CultureInfo.CurrentCulture, Resource.TestAssembly_FileDoesNotExist, fullFilePath)); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TestMethodValidatorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TestMethodValidatorTests.cs index dce04bc894..defee3b8ab 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TestMethodValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TestMethodValidatorTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; @@ -33,7 +35,7 @@ public void IsValidTestMethodShouldReturnFalseForMethodsWithoutATestMethodAttrib { _mockReflectHelper.Setup( rh => rh.IsAttributeDefined(It.IsAny())).Returns(false); - Verify(!_testMethodValidator.IsValidTestMethod(_mockMethodInfo.Object, _type, _warnings)); + _testMethodValidator.IsValidTestMethod(_mockMethodInfo.Object, _type, _warnings).Should().BeFalse(); } // TODO: Fix this test. It should be returning true, but we get false for a different reason (IsPublic is false) @@ -45,7 +47,7 @@ public void IsValidTestMethodShouldReturnFalseForGenericTestMethodDefinitions() _mockMethodInfo.Setup(mi => mi.DeclaringType!.FullName).Returns("DummyTestClass"); _mockMethodInfo.Setup(mi => mi.Name).Returns("DummyTestMethod"); - Verify(!_testMethodValidator.IsValidTestMethod(_mockMethodInfo.Object, _type, _warnings)); + _testMethodValidator.IsValidTestMethod(_mockMethodInfo.Object, _type, _warnings).Should().BeFalse(); } // TODO: Fix this test. It should be returning true, but we get false for a different reason (IsPublic is false) @@ -65,7 +67,7 @@ public void IsValidTestMethodShouldNotReportWarningsForGenericTestMethodDefiniti _mockMethodInfo.Setup(mi => mi.ReturnType).Returns(typeof(void)); _testMethodValidator.IsValidTestMethod(_mockMethodInfo.Object, _type, _warnings); - Verify(_warnings.Count == 0); + _warnings.Count.Should().Be(0); } public void IsValidTestMethodShouldReturnFalseForNonPublicMethods() @@ -75,7 +77,7 @@ public void IsValidTestMethodShouldReturnFalseForNonPublicMethods() "InternalTestMethod", BindingFlags.Instance | BindingFlags.NonPublic)!; - Verify(!_testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings)); + _testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings).Should().BeFalse(); } public void IsValidTestMethodShouldReturnFalseForAbstractMethods() @@ -85,7 +87,7 @@ public void IsValidTestMethodShouldReturnFalseForAbstractMethods() "AbstractTestMethod", BindingFlags.Instance | BindingFlags.Public)!; - Verify(!_testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings)); + _testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings).Should().BeFalse(); } public void IsValidTestMethodShouldReturnFalseForStaticMethods() @@ -95,7 +97,7 @@ public void IsValidTestMethodShouldReturnFalseForStaticMethods() "StaticTestMethod", BindingFlags.Static | BindingFlags.Public)!; - Verify(!_testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings)); + _testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings).Should().BeFalse(); } public void IsValidTestMethodShouldReturnFalseForGenericTestMethods() @@ -103,7 +105,7 @@ public void IsValidTestMethodShouldReturnFalseForGenericTestMethods() SetupTestMethod(); Action action = () => new DummyTestClassWithGenericMethods().GenericMethod(); - Verify(!_testMethodValidator.IsValidTestMethod(action.Method, typeof(DummyTestClassWithGenericMethods), _warnings)); + _testMethodValidator.IsValidTestMethod(action.Method, typeof(DummyTestClassWithGenericMethods), _warnings).Should().BeFalse(); } public void IsValidTestMethodShouldReturnFalseForAsyncMethodsWithNonTaskReturnType() @@ -115,7 +117,7 @@ public void IsValidTestMethodShouldReturnFalseForAsyncMethodsWithNonTaskReturnTy _mockReflectHelper.Setup(_mockReflectHelper => _mockReflectHelper.GetFirstAttributeOrDefault(methodInfo)) .CallBase(); - Verify(!_testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings)); + _testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings).Should().BeFalse(); } public void IsValidTestMethodShouldReturnFalseForMethodsWithNonVoidReturnType() @@ -125,7 +127,7 @@ public void IsValidTestMethodShouldReturnFalseForMethodsWithNonVoidReturnType() "MethodWithIntReturnType", BindingFlags.Instance | BindingFlags.Public)!; - Verify(!_testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings)); + _testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings).Should().BeFalse(); } public void IsValidTestMethodShouldReturnTrueForAsyncMethodsWithTaskReturnType() @@ -135,7 +137,7 @@ public void IsValidTestMethodShouldReturnTrueForAsyncMethodsWithTaskReturnType() "AsyncMethodWithTaskReturnType", BindingFlags.Instance | BindingFlags.Public)!; - Verify(_testMethodValidator.IsValidTestMethod(methodInfo, _type, _warnings)); + _testMethodValidator.IsValidTestMethod(methodInfo, _type, _warnings).Should().BeTrue(); } public void IsValidTestMethodShouldReturnTrueForNonAsyncMethodsWithTaskReturnType() @@ -145,7 +147,7 @@ public void IsValidTestMethodShouldReturnTrueForNonAsyncMethodsWithTaskReturnTyp "MethodWithTaskReturnType", BindingFlags.Instance | BindingFlags.Public)!; - Verify(_testMethodValidator.IsValidTestMethod(methodInfo, _type, _warnings)); + _testMethodValidator.IsValidTestMethod(methodInfo, _type, _warnings).Should().BeTrue(); } public void IsValidTestMethodShouldReturnTrueForMethodsWithVoidReturnType() @@ -155,7 +157,7 @@ public void IsValidTestMethodShouldReturnTrueForMethodsWithVoidReturnType() "MethodWithVoidReturnType", BindingFlags.Instance | BindingFlags.Public)!; - Verify(_testMethodValidator.IsValidTestMethod(methodInfo, _type, _warnings)); + _testMethodValidator.IsValidTestMethod(methodInfo, _type, _warnings).Should().BeTrue(); } #region Discovery of internals enabled @@ -169,7 +171,7 @@ public void WhenDiscoveryOfInternalsIsEnabledIsValidTestMethodShouldReturnTrueFo var testMethodValidator = new TestMethodValidator(_mockReflectHelper.Object, true); - Verify(testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings)); + testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings).Should().BeTrue(); } public void WhenDiscoveryOfInternalsIsEnabledIsValidTestMethodShouldReturnFalseForPrivateMethods() @@ -181,7 +183,7 @@ public void WhenDiscoveryOfInternalsIsEnabledIsValidTestMethodShouldReturnFalseF var testMethodValidator = new TestMethodValidator(_mockReflectHelper.Object, true); - Verify(!testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings)); + testMethodValidator.IsValidTestMethod(methodInfo, typeof(DummyTestClass), _warnings).Should().BeFalse(); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs index 725b5b778a..f67374a61e 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeEnumeratorTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; @@ -54,7 +56,7 @@ protected override void Dispose(bool disposing) public void EnumerateShouldReturnNullIfTypeIsNotValid() { TypeEnumerator typeEnumerator = GetTypeEnumeratorInstance(typeof(IDummyInterface), string.Empty); - Verify(typeEnumerator.Enumerate(_warnings) is null); + typeEnumerator.Enumerate(_warnings).Should().BeNull(); } public void EnumerateShouldReturnEmptyCollectionWhenNoValidTestMethodsExist() @@ -64,8 +66,8 @@ public void EnumerateShouldReturnEmptyCollectionWhenNoValidTestMethodsExist() ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); - Verify(tests.Count == 0); + tests.Should().NotBeNull(); + tests.Should().HaveCount(0); } #endregion @@ -79,10 +81,10 @@ public void GetTestsShouldReturnDeclaredTestMethods() ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); + tests.Should().NotBeNull(); // DummyBaseTestClass declares BaseTestMethod directly so it should always be discovered. - Verify(tests.Any(t => t.TestMethod.Name == "BaseTestMethod")); + tests.Should().Contain(t => t.TestMethod.Name == "BaseTestMethod"); } public void GetTestsShouldReturnBaseTestMethodsInSameAssembly() @@ -92,10 +94,10 @@ public void GetTestsShouldReturnBaseTestMethodsInSameAssembly() ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); + tests.Should().NotBeNull(); // DummyDerivedTestClass inherits DummyBaseTestClass from same assembly. BestTestMethod from DummyBaseTestClass should be discovered. - Verify(tests.Any(t => t.TestMethod.Name == "BaseTestMethod")); + tests.Should().Contain(t => t.TestMethod.Name == "BaseTestMethod"); } public void GetTestsShouldReturnBaseTestMethodsFromAnotherAssemblyByDefault() @@ -123,10 +125,10 @@ public void GetTestsShouldReturnBaseTestMethodsFromAnotherAssemblyByDefault() ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); + tests.Should().NotBeNull(); // DummyDerivedFromRemoteTestClass inherits DummyRemoteBaseTestClass from different assembly. BestTestMethod from DummyRemoteBaseTestClass should be discovered by default. - Verify(tests.Any(t => t.TestMethod.Name == "BaseTestMethod")); + tests.Should().Contain(t => t.TestMethod.Name == "BaseTestMethod"); } public void GetTestsShouldReturnBaseTestMethodsFromAnotherAssemblyByConfiguration() @@ -153,11 +155,11 @@ public void GetTestsShouldReturnBaseTestMethodsFromAnotherAssemblyByConfiguratio ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); + tests.Should().NotBeNull(); // DummyDerivedFromRemoteTestClass inherits DummyRemoteBaseTestClass from different assembly. // BestTestMethod from DummyRemoteBaseTestClass should be discovered when RunSettings MSTestV2 specifies EnableBaseClassTestMethodsFromOtherAssemblies = true. - Verify(tests.Any(t => t.TestMethod.Name == "BaseTestMethod")); + tests.Should().Contain(t => t.TestMethod.Name == "BaseTestMethod"); } public void GetTestsShouldNotReturnBaseTestMethodsFromAnotherAssemblyByConfiguration() @@ -184,11 +186,11 @@ public void GetTestsShouldNotReturnBaseTestMethodsFromAnotherAssemblyByConfigura ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); + tests.Should().NotBeNull(); // DummyDerivedFromRemoteTestClass inherits DummyRemoteBaseTestClass from different assembly. // BestTestMethod from DummyRemoteBaseTestClass should not be discovered when RunSettings MSTestV2 specifies EnableBaseClassTestMethodsFromOtherAssemblies = false. - Verify(tests.All(t => t.TestMethod.Name != "BaseTestMethod")); + tests.Should().NotContain(t => t.TestMethod.Name == "BaseTestMethod"); } public void GetTestsShouldNotReturnHiddenTestMethods() @@ -198,16 +200,16 @@ public void GetTestsShouldNotReturnHiddenTestMethods() ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); + tests.Should().NotBeNull(); // DummyHidingTestClass declares BaseTestMethod directly so it should always be discovered. - Verify(tests.Count(t => t.TestMethod.Name == "BaseTestMethod") == 1); + tests.Where(t => t.TestMethod.Name == "BaseTestMethod").Should().HaveCount(1); // DummyHidingTestClass declares BaseTestMethod directly so it should always be discovered. - Verify(tests.Count(t => t.TestMethod.Name == "DerivedTestMethod") == 1); + tests.Where(t => t.TestMethod.Name == "DerivedTestMethod").Should().HaveCount(1); // DummyHidingTestClass hides BaseTestMethod so declaring class should not be the base class - Verify(!tests.Any(t => t.TestMethod.DeclaringClassFullName == typeof(DummyBaseTestClass).FullName)); + tests.Should().NotContain(t => t.TestMethod.DeclaringClassFullName == typeof(DummyBaseTestClass).FullName); } public void GetTestsShouldReturnOverriddenTestMethods() @@ -217,20 +219,19 @@ public void GetTestsShouldReturnOverriddenTestMethods() ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); + tests.Should().NotBeNull(); // DummyOverridingTestClass inherits BaseTestMethod so it should be discovered. - Verify(tests.Count(t => t.TestMethod.Name == "BaseTestMethod") == 1); + tests.Where(t => t.TestMethod.Name == "BaseTestMethod").Should().HaveCount(1); // DummyOverridingTestClass overrides DerivedTestMethod directly so it should always be discovered. - Verify(tests.Count(t => t.TestMethod.Name == "DerivedTestMethod") == 1); + tests.Where(t => t.TestMethod.Name == "DerivedTestMethod").Should().HaveCount(1); // DummyOverridingTestClass inherits BaseTestMethod from DummyHidingTestClass specifically. - Verify(typeof(DummyHidingTestClass).FullName - == tests.Single(t => t.TestMethod.Name == "BaseTestMethod").TestMethod.DeclaringClassFullName); + tests.Single(t => t.TestMethod.Name == "BaseTestMethod").TestMethod.DeclaringClassFullName.Should().Be(typeof(DummyHidingTestClass).FullName); // DummyOverridingTestClass overrides DerivedTestMethod so is the declaring class. - Verify(tests.Single(t => t.TestMethod.Name == "DerivedTestMethod").TestMethod.DeclaringClassFullName is null); + tests.Single(t => t.TestMethod.Name == "DerivedTestMethod").TestMethod.DeclaringClassFullName.Should().BeNull(); } public void GetTestsShouldNotReturnHiddenTestMethodsFromAnyLevel() @@ -240,22 +241,22 @@ public void GetTestsShouldNotReturnHiddenTestMethodsFromAnyLevel() ICollection? tests = typeEnumerator.Enumerate(_warnings); - Verify(tests is not null); + tests.Should().NotBeNull(); // DummySecondHidingTestClass hides BaseTestMethod so it should be discovered. - Verify(tests.Count(t => t.TestMethod.Name == "BaseTestMethod") == 1); + tests.Where(t => t.TestMethod.Name == "BaseTestMethod").Should().HaveCount(1); // DummySecondHidingTestClass hides DerivedTestMethod so it should be discovered. - Verify(tests.Count(t => t.TestMethod.Name == "DerivedTestMethod") == 1); + tests.Where(t => t.TestMethod.Name == "DerivedTestMethod").Should().HaveCount(1); // DummySecondHidingTestClass hides all base test methods so declaring class should not be any base class. - Verify(!tests.Any(t => t.TestMethod.DeclaringClassFullName == typeof(DummyBaseTestClass).FullName)); + tests.Should().NotContain(t => t.TestMethod.DeclaringClassFullName == typeof(DummyBaseTestClass).FullName); // DummySecondHidingTestClass hides all base test methods so declaring class should not be any base class. - Verify(!tests.Any(t => t.TestMethod.DeclaringClassFullName == typeof(DummyHidingTestClass).FullName)); + tests.Should().NotContain(t => t.TestMethod.DeclaringClassFullName == typeof(DummyHidingTestClass).FullName); // DummySecondHidingTestClass hides all base test methods so declaring class should not be any base class. - Verify(!tests.Any(t => t.TestMethod.DeclaringClassFullName == typeof(DummyOverridingTestClass).FullName)); + tests.Should().NotContain(t => t.TestMethod.DeclaringClassFullName == typeof(DummyOverridingTestClass).FullName); } #endregion @@ -269,10 +270,21 @@ public void GetTestFromMethodShouldInitiateTestMethodWithCorrectParameters() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(typeof(DummyTestClass).GetMethod("MethodWithVoidReturnType")!, _warnings); - Verify(testElement is not null); - Verify(testElement.TestMethod.Name == "MethodWithVoidReturnType"); - Verify(typeof(DummyTestClass).FullName == testElement.TestMethod.FullClassName); - Verify(testElement.TestMethod.AssemblyName == "DummyAssemblyName"); + testElement.Should().NotBeNull(); + testElement.TestMethod.Name.Should().Be("MethodWithVoidReturnType"); + testElement.TestMethod.FullClassName.Should().Be(typeof(DummyTestClass).FullName); + testElement.TestMethod.AssemblyName.Should().Be("DummyAssemblyName"); + } + + public void GetTestFromMethodShouldInitializeAsyncTypeNameCorrectly() + { + SetupTestClassAndTestMethods(isValidTestClass: true, isValidTestMethod: true, isMethodFromSameAssembly: true); + TypeEnumerator typeEnumerator = GetTypeEnumeratorInstance(typeof(DummyTestClass), "DummyAssemblyName"); + MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("AsyncMethodWithTaskReturnType")!; + + MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); + + testElement.Should().NotBeNull(); } public void GetTestFromMethodShouldSetTestCategory() @@ -285,8 +297,8 @@ public void GetTestFromMethodShouldSetTestCategory() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testCategories.SequenceEqual(testElement.TestCategory)); + testElement.Should().NotBeNull(); + testElement.TestCategory.Should().BeEquivalentTo(testCategories); } public void GetTestFromMethodShouldSetDoNotParallelize() @@ -298,8 +310,8 @@ public void GetTestFromMethodShouldSetDoNotParallelize() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.DoNotParallelize); + testElement.Should().NotBeNull(); + testElement.DoNotParallelize.Should().BeTrue(); } public void GetTestFromMethodShouldFillTraitsWithTestProperties() @@ -315,12 +327,12 @@ public void GetTestFromMethodShouldFillTraitsWithTestProperties() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.Traits!.Length == 2); - Verify(testElement.Traits[0].Name == "foo"); - Verify(testElement.Traits[0].Value == "bar"); - Verify(testElement.Traits[1].Name == "fooprime"); - Verify(testElement.Traits[1].Value == "barprime"); + testElement.Should().NotBeNull(); + testElement.Traits.Should().HaveCount(2); + testElement.Traits![0].Name.Should().Be("foo"); + testElement.Traits[0].Value.Should().Be("bar"); + testElement.Traits[1].Name.Should().Be("fooprime"); + testElement.Traits[1].Value.Should().Be("barprime"); } public void GetTestFromMethodShouldFillTraitsWithTestOwnerPropertyIfPresent() @@ -337,14 +349,14 @@ public void GetTestFromMethodShouldFillTraitsWithTestOwnerPropertyIfPresent() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.Traits!.Length == 3); - Verify(testElement.Traits[0].Name == "foo"); - Verify(testElement.Traits[0].Value == "bar"); - Verify(testElement.Traits[1].Name == "fooprime"); - Verify(testElement.Traits[1].Value == "barprime"); - Verify(testElement.Traits[2].Name == "Owner"); - Verify(testElement.Traits[2].Value == "mike"); + testElement.Should().NotBeNull(); + testElement.Traits.Should().HaveCount(3); + testElement.Traits![0].Name.Should().Be("foo"); + testElement.Traits[0].Value.Should().Be("bar"); + testElement.Traits[1].Name.Should().Be("fooprime"); + testElement.Traits[1].Value.Should().Be("barprime"); + testElement.Traits[2].Name.Should().Be("Owner"); + testElement.Traits[2].Value.Should().Be("mike"); } public void GetTestFromMethodShouldFillTraitsWithTestPriorityPropertyIfPresent() @@ -356,14 +368,14 @@ public void GetTestFromMethodShouldFillTraitsWithTestPriorityPropertyIfPresent() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.Traits!.Length == 3); - Verify(testElement.Traits[0].Name == "foo"); - Verify(testElement.Traits[0].Value == "bar"); - Verify(testElement.Traits[1].Name == "fooprime"); - Verify(testElement.Traits[1].Value == "barprime"); - Verify(testElement.Traits[2].Name == "Priority"); - Verify(testElement.Traits[2].Value == "1"); + testElement.Should().NotBeNull(); + testElement.Traits.Should().HaveCount(3); + testElement.Traits![0].Name.Should().Be("foo"); + testElement.Traits[0].Value.Should().Be("bar"); + testElement.Traits[1].Name.Should().Be("fooprime"); + testElement.Traits[1].Value.Should().Be("barprime"); + testElement.Traits[2].Name.Should().Be("Priority"); + testElement.Traits[2].Value.Should().Be("1"); } public void GetTestFromMethodShouldSetPriority() @@ -375,8 +387,8 @@ public void GetTestFromMethodShouldSetPriority() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.Priority == 1); + testElement.Should().NotBeNull(); + testElement.Priority.Should().Be(1); } public void GetTestFromMethodShouldSetDescription() @@ -388,8 +400,8 @@ public void GetTestFromMethodShouldSetDescription() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement.Traits is not null); - Verify(testElement.Traits.Any(t => t.Name == "Description" && t.Value == "Dummy description")); + testElement.Traits.Should().NotBeNull(); + testElement.Traits.Should().Contain(t => t.Name == "Description" && t.Value == "Dummy description"); } public void GetTestFromMethodShouldSetWorkItemIds() @@ -401,7 +413,7 @@ public void GetTestFromMethodShouldSetWorkItemIds() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(new string[] { "123", "345" }.SequenceEqual(testElement.WorkItemIds)); + testElement.WorkItemIds.Should().BeEquivalentTo(["123", "345"]); } public void GetTestFromMethodShouldSetWorkItemIdsToNullIfNotAny() @@ -412,7 +424,7 @@ public void GetTestFromMethodShouldSetWorkItemIdsToNullIfNotAny() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement.WorkItemIds is null); + testElement.WorkItemIds.Should().BeNull(); } public void GetTestFromMethodShouldSetDeploymentItemsToNullIfNotPresent() @@ -428,8 +440,8 @@ public void GetTestFromMethodShouldSetDeploymentItemsToNullIfNotPresent() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.DeploymentItems is null); + testElement.Should().NotBeNull(); + testElement.DeploymentItems.Should().BeNull(); } public void GetTestFromMethodShouldSetDeploymentItems() @@ -445,9 +457,9 @@ public void GetTestFromMethodShouldSetDeploymentItems() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.DeploymentItems is not null); - Verify(deploymentItems.SequenceEqual(testElement.DeploymentItems)); + testElement.Should().NotBeNull(); + testElement.DeploymentItems.Should().NotBeNull(); + testElement.DeploymentItems.Should().BeEquivalentTo(deploymentItems); } public void GetTestFromMethodShouldSetDisplayNameToTestMethodNameIfDisplayNameIsNotPresent() @@ -459,8 +471,7 @@ public void GetTestFromMethodShouldSetDisplayNameToTestMethodNameIfDisplayNameIs MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.TestMethod.DisplayName == "MethodWithVoidReturnType"); + testElement.Should().NotBeNull(); } public void GetTestFromMethodShouldSetDisplayNameFromTestMethodAttribute() @@ -472,8 +483,7 @@ public void GetTestFromMethodShouldSetDisplayNameFromTestMethodAttribute() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.TestMethod.DisplayName == "Test method display name."); + testElement.Should().NotBeNull(); } public void GetTestFromMethodShouldSetDisplayNameFromDataTestMethodAttribute() @@ -485,8 +495,7 @@ public void GetTestFromMethodShouldSetDisplayNameFromDataTestMethodAttribute() MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, _warnings); - Verify(testElement is not null); - Verify(testElement.TestMethod.DisplayName == "Test method display name."); + testElement.Should().NotBeNull(); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs index 4699a14c7d..34e7b0db56 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/TypeValidatorTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; @@ -34,12 +36,12 @@ public TypeValidatorTests() #region Type is class, TestClassAttribute or attribute derived from TestClassAttribute - public void IsValidTestClassShouldReturnFalseForNonClassTypes() => Verify(!_typeValidator.IsValidTestClass(typeof(IDummyInterface), _warnings)); + public void IsValidTestClassShouldReturnFalseForNonClassTypes() => _typeValidator.IsValidTestClass(typeof(IDummyInterface), _warnings).Should().BeFalse(); public void IsValidTestClassShouldReturnFalseForClassesNotHavingTestClassAttributeOrDerivedAttributeTypes() { _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny())).Returns(false); - Verify(!_typeValidator.IsValidTestClass(typeof(TypeValidatorTests), _warnings)); + _typeValidator.IsValidTestClass(typeof(TypeValidatorTests), _warnings).Should().BeFalse(); } public void IsValidTestClassShouldReturnTrueForClassesMarkedByAnAttributeDerivedFromTestClass() @@ -47,7 +49,7 @@ public void IsValidTestClassShouldReturnTrueForClassesMarkedByAnAttributeDerived _mockReflectHelper.Setup(rh => rh.IsAttributeDefined(It.IsAny())).Returns(false); _mockReflectHelper.Setup( rh => rh.IsAttributeDefined(It.IsAny())).Returns(true); - Verify(_typeValidator.IsValidTestClass(typeof(TypeValidatorTests), _warnings)); + _typeValidator.IsValidTestClass(typeof(TypeValidatorTests), _warnings).Should().BeTrue(); } #endregion @@ -57,41 +59,41 @@ public void IsValidTestClassShouldReturnTrueForClassesMarkedByAnAttributeDerived public void IsValidTestClassShouldReturnFalseForNonPublicTestClasses() { SetupTestClass(); - Verify(!_typeValidator.IsValidTestClass(typeof(InternalTestClass), _warnings)); + _typeValidator.IsValidTestClass(typeof(InternalTestClass), _warnings).Should().BeFalse(); } public void IsValidTestClassShouldReportWarningForNonPublicTestClasses() { SetupTestClass(); _typeValidator.IsValidTestClass(typeof(InternalTestClass), _warnings); - Verify(_warnings.Count == 1); - Verify(_warnings.Contains(string.Format(CultureInfo.InvariantCulture, Resource.UTA_ErrorNonPublicTestClass, typeof(InternalTestClass).FullName))); + _warnings.Count.Should().Be(1); + _warnings.Should().Contain(string.Format(CultureInfo.InvariantCulture, Resource.UTA_ErrorNonPublicTestClass, typeof(InternalTestClass).FullName)); } public void IsValidTestClassShouldReturnFalseForNestedNonPublicTestClasses() { SetupTestClass(); - Verify(!_typeValidator.IsValidTestClass(typeof(OuterClass.NestedInternalClass), _warnings)); + _typeValidator.IsValidTestClass(typeof(OuterClass.NestedInternalClass), _warnings).Should().BeFalse(); } public void IsValidTestClassShouldReportWarningsForNestedNonPublicTestClasses() { SetupTestClass(); _typeValidator.IsValidTestClass(typeof(OuterClass.NestedInternalClass), _warnings); - Verify(_warnings.Count == 1); - Verify(_warnings.Contains(string.Format(CultureInfo.InvariantCulture, Resource.UTA_ErrorNonPublicTestClass, typeof(OuterClass.NestedInternalClass).FullName))); + _warnings.Count.Should().Be(1); + _warnings.Should().Contain(string.Format(CultureInfo.InvariantCulture, Resource.UTA_ErrorNonPublicTestClass, typeof(OuterClass.NestedInternalClass).FullName)); } public void IsValidTestClassShouldReturnTrueForPublicTestClasses() { SetupTestClass(); - Verify(_typeValidator.IsValidTestClass(typeof(PublicTestClass), _warnings)); + _typeValidator.IsValidTestClass(typeof(PublicTestClass), _warnings).Should().BeTrue(); } public void IsValidTestClassShouldReturnTrueForNestedPublicTestClasses() { SetupTestClass(); - Verify(_typeValidator.IsValidTestClass(typeof(OuterClass.NestedPublicClass), _warnings)); + _typeValidator.IsValidTestClass(typeof(OuterClass.NestedPublicClass), _warnings).Should().BeTrue(); } #endregion @@ -103,7 +105,7 @@ public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldReturnTrueForInt var typeValidator = new TypeValidator(_mockReflectHelper.Object, true); SetupTestClass(); - Verify(typeValidator.IsValidTestClass(typeof(InternalTestClass), _warnings)); + typeValidator.IsValidTestClass(typeof(InternalTestClass), _warnings).Should().BeTrue(); } public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldNotReportWarningForInternalTestClasses() @@ -112,7 +114,7 @@ public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldNotReportWarning SetupTestClass(); typeValidator.IsValidTestClass(typeof(InternalTestClass), _warnings); - Verify(_warnings.Count == 0); + _warnings.Count.Should().Be(0); } public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldReturnTrueForNestedInternalTestClasses() @@ -120,7 +122,7 @@ public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldReturnTrueForNes var typeValidator = new TypeValidator(_mockReflectHelper.Object, true); SetupTestClass(); - Verify(typeValidator.IsValidTestClass(typeof(OuterClass.NestedInternalClass), _warnings)); + typeValidator.IsValidTestClass(typeof(OuterClass.NestedInternalClass), _warnings).Should().BeTrue(); } public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldReturnFalseForPrivateTestClasses() @@ -130,7 +132,7 @@ public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldReturnFalseForPr Type nestedPrivateClassType = Assembly.GetExecutingAssembly().GetTypes().First(t => t.Name == "NestedPrivateClass"); SetupTestClass(); - Verify(!typeValidator.IsValidTestClass(nestedPrivateClassType, _warnings)); + typeValidator.IsValidTestClass(nestedPrivateClassType, _warnings).Should().BeFalse(); } public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldReturnFalseForInaccessibleTestClasses() @@ -140,7 +142,7 @@ public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldReturnFalseForIn Type inaccessibleClassType = Assembly.GetExecutingAssembly().GetTypes().First(t => t.Name == "InaccessiblePublicClass"); SetupTestClass(); - Verify(!typeValidator.IsValidTestClass(inaccessibleClassType, _warnings)); + typeValidator.IsValidTestClass(inaccessibleClassType, _warnings).Should().BeFalse(); } public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldNotReportWarningsForNestedInternalTestClasses() @@ -149,7 +151,7 @@ public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldNotReportWarning SetupTestClass(); typeValidator.IsValidTestClass(typeof(OuterClass.NestedInternalClass), _warnings); - Verify(_warnings.Count == 0); + _warnings.Count.Should().Be(0); } #endregion @@ -159,15 +161,15 @@ public void WhenInternalDiscoveryIsEnabledIsValidTestClassShouldNotReportWarning public void IsValidTestClassShouldReturnFalseForNonAbstractGenericTypes() { SetupTestClass(); - Verify(!_typeValidator.IsValidTestClass(typeof(GenericClass<>), _warnings)); + _typeValidator.IsValidTestClass(typeof(GenericClass<>), _warnings).Should().BeFalse(); } public void IsValidTestClassShouldReportWarningsForNonAbstractGenericTypes() { SetupTestClass(); _typeValidator.IsValidTestClass(typeof(GenericClass<>), _warnings); - Verify(_warnings.Count == 1); - Verify(_warnings.Contains(string.Format(CultureInfo.InvariantCulture, Resource.UTA_ErrorTestClassIsGenericNonAbstract, typeof(GenericClass<>).FullName))); + _warnings.Count.Should().Be(1); + _warnings.Should().Contain(string.Format(CultureInfo.InvariantCulture, Resource.UTA_ErrorTestClassIsGenericNonAbstract, typeof(GenericClass<>).FullName)); } #endregion @@ -177,14 +179,14 @@ public void IsValidTestClassShouldReportWarningsForNonAbstractGenericTypes() public void IsValidTestClassShouldReturnTrueForTestClassesWithReadOnlyTestContextSignature() { SetupTestClass(); - Verify(_typeValidator.IsValidTestClass(typeof(ClassWithTestContextGetterOnly), _warnings)); - Verify(_warnings.Count == 0); + _typeValidator.IsValidTestClass(typeof(ClassWithTestContextGetterOnly), _warnings).Should().BeTrue(); + _warnings.Count.Should().Be(0); } public void IsValidTestClassShouldReturnTrueForTestClassesWithValidTestContextSignature() { SetupTestClass(); - Verify(_typeValidator.IsValidTestClass(typeof(ClassWithTestContext), _warnings)); + _typeValidator.IsValidTestClass(typeof(ClassWithTestContext), _warnings).Should().BeTrue(); } #endregion @@ -194,40 +196,40 @@ public void IsValidTestClassShouldReturnTrueForTestClassesWithValidTestContextSi public void IsValidTestClassShouldReturnFalseForAbstractTestClasses() { SetupTestClass(); - Verify(!_typeValidator.IsValidTestClass(typeof(AbstractTestClass), _warnings)); + _typeValidator.IsValidTestClass(typeof(AbstractTestClass), _warnings).Should().BeFalse(); } public void IsValidTestClassShouldNotReportWarningsForAbstractTestClasses() { SetupTestClass(); _typeValidator.IsValidTestClass(typeof(AbstractTestClass), _warnings); - Verify(_warnings.Count == 0); + _warnings.Count.Should().Be(0); } public void IsValidTestClassShouldReturnFalseForGenericAbstractTestClasses() { SetupTestClass(); - Verify(!_typeValidator.IsValidTestClass(typeof(AbstractGenericClass<>), _warnings)); - Verify(_warnings.Count == 0); + _typeValidator.IsValidTestClass(typeof(AbstractGenericClass<>), _warnings).Should().BeFalse(); + _warnings.Count.Should().Be(0); } #endregion #region HasCorrectTestContext tests - public void HasCorrectTestContextSignatureShouldReturnTrueForClassesWithNoTestContextProperty() => Verify(TypeValidator.HasCorrectTestContextSignature(typeof(PublicTestClass))); + public void HasCorrectTestContextSignatureShouldReturnTrueForClassesWithNoTestContextProperty() => TypeValidator.HasCorrectTestContextSignature(typeof(PublicTestClass)).Should().BeTrue(); - public void HasCorrectTestContextSignatureShouldReturnTrueForTestContextsWithNoSetters() => Verify(TypeValidator.HasCorrectTestContextSignature(typeof(ClassWithTestContextGetterOnly))); + public void HasCorrectTestContextSignatureShouldReturnTrueForTestContextsWithNoSetters() => TypeValidator.HasCorrectTestContextSignature(typeof(ClassWithTestContextGetterOnly)).Should().BeTrue(); - public void HasCorrectTestContextSignatureShouldReturnTrueForTestContextsWithPrivateSetter() => Verify(TypeValidator.HasCorrectTestContextSignature(typeof(ClassWithTestContextPrivateSetter))); + public void HasCorrectTestContextSignatureShouldReturnTrueForTestContextsWithPrivateSetter() => TypeValidator.HasCorrectTestContextSignature(typeof(ClassWithTestContextPrivateSetter)).Should().BeTrue(); - public void HasCorrectTestContextSignatureShouldReturnFalseForTestContextsWithStaticSetter() => Verify(!TypeValidator.HasCorrectTestContextSignature(typeof(ClassWithStaticTestContext))); + public void HasCorrectTestContextSignatureShouldReturnFalseForTestContextsWithStaticSetter() => TypeValidator.HasCorrectTestContextSignature(typeof(ClassWithStaticTestContext)).Should().BeFalse(); - public void HasCorrectTestContextSignatureShouldReturnFalseForTestContextsWithAbstractSetter() => Verify(!TypeValidator.HasCorrectTestContextSignature(typeof(ClassWithAbstractTestContext))); + public void HasCorrectTestContextSignatureShouldReturnFalseForTestContextsWithAbstractSetter() => TypeValidator.HasCorrectTestContextSignature(typeof(ClassWithAbstractTestContext)).Should().BeFalse(); - public void HasCorrectTestContextSignatureShouldNotThrowForAGenericClassWithRandomProperties() => Verify(TypeValidator.HasCorrectTestContextSignature(typeof(GenericClassWithProperty<>))); + public void HasCorrectTestContextSignatureShouldNotThrowForAGenericClassWithRandomProperties() => TypeValidator.HasCorrectTestContextSignature(typeof(GenericClassWithProperty<>)).Should().BeTrue(); - public void HasCorrectTestContextSignatureShouldReturnTrueForAGenericClassWithTestContext() => Verify(TypeValidator.HasCorrectTestContextSignature(typeof(GenericClassWithTestContext<>))); + public void HasCorrectTestContextSignatureShouldReturnTrueForAGenericClassWithTestContext() => TypeValidator.HasCorrectTestContextSignature(typeof(GenericClassWithTestContext<>)).Should().BeTrue(); #endregion @@ -239,11 +241,11 @@ public void AllTypesContainAllPrivateClasses() // list of our test types, to avoid bugs caused by typos. string[] allTypes = [.. GetAllTestTypes().Select(t => t.Name)]; string[] privateTypes = [.. typeof(PrivateClassNames).GetProperties().Select(n => n.Name)]; - Verify(privateTypes.Length >= 1); + privateTypes.Length.Should().BeGreaterThanOrEqualTo(1); foreach (string type in privateTypes) { - Verify(allTypes.Contains(type)); + allTypes.Should().Contain(type); } } @@ -267,7 +269,7 @@ public void TypeHasValidAccessibilityShouldReturnTrueForAllPublicTypesIncludingN Array.Sort(actualDiscoveredTypes); Array.Sort(expectedDiscoveredTypes); - Verify(actualDiscoveredTypes.SequenceEqual(expectedDiscoveredTypes)); + actualDiscoveredTypes.Should().Equal(expectedDiscoveredTypes); } public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPublicOrOneOfTheirDeclaringTypesIsNotPublic() @@ -310,7 +312,7 @@ public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPubli Array.Sort(actualDiscoveredTypes); Array.Sort(expectedNonDiscoveredTypes); - Verify(actualDiscoveredTypes.SequenceEqual(expectedNonDiscoveredTypes)); + actualDiscoveredTypes.Should().Equal(expectedNonDiscoveredTypes); } public void TypeHasValidAccessibilityShouldReturnTrueForAllPublicAndInternalTypesIncludingNestedTypesWhenDiscoverInternalIsEnabled() @@ -345,7 +347,7 @@ public void TypeHasValidAccessibilityShouldReturnTrueForAllPublicAndInternalType Array.Sort(actualDiscoveredTypes); Array.Sort(expectedDiscoveredTypes); - Verify(actualDiscoveredTypes.SequenceEqual(expectedDiscoveredTypes)); + actualDiscoveredTypes.Should().Equal(expectedDiscoveredTypes); } public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPublicOrInternalOrOneOfTheirDeclaringTypesIsNotPublicOrInternalWhenDiscoverInternalIsEnabled() @@ -375,7 +377,7 @@ public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPubli Array.Sort(actualDiscoveredTypes); Array.Sort(expectedNonDiscoveredTypes); - Verify(actualDiscoveredTypes.SequenceEqual(expectedNonDiscoveredTypes)); + actualDiscoveredTypes.Should().Equal(expectedNonDiscoveredTypes); } private static Type[] GetAllTestTypes() diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs index f95e7cc9ff..36a648b608 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Discovery/UnitTestDiscovererTests.cs @@ -77,8 +77,9 @@ public void DiscoverTestsShouldThrowOnFileNotFound() .Returns(false); } - Exception ex = VerifyThrows(() => _unitTestDiscoverer.DiscoverTests(sources, _mockMessageLogger.Object, _mockTestCaseDiscoverySink.Object, _mockDiscoveryContext.Object)); - Verify(ex.Message == string.Format(CultureInfo.CurrentCulture, Resource.TestAssembly_FileDoesNotExist, sources[0])); + Action act = () => _unitTestDiscoverer.DiscoverTests(sources, _mockMessageLogger.Object, _mockTestCaseDiscoverySink.Object, _mockDiscoveryContext.Object); + act.Should().Throw() + .WithMessage(string.Format(CultureInfo.CurrentCulture, Resource.TestAssembly_FileDoesNotExist, sources[0])); } public void DiscoverTestsInSourceShouldThrowOnFileNotFound() @@ -89,8 +90,9 @@ public void DiscoverTestsInSourceShouldThrowOnFileNotFound() _testablePlatformServiceProvider.MockFileOperations.Setup(fo => fo.DoesFileExist(Source)) .Returns(false); - Exception ex = VerifyThrows(() => _unitTestDiscoverer.DiscoverTestsInSource(Source, _mockMessageLogger.Object, _mockTestCaseDiscoverySink.Object, _mockDiscoveryContext.Object)); - Verify(ex.Message == string.Format(CultureInfo.CurrentCulture, Resource.TestAssembly_FileDoesNotExist, Source)); + Action act = () => _unitTestDiscoverer.DiscoverTestsInSource(Source, _mockMessageLogger.Object, _mockTestCaseDiscoverySink.Object, _mockDiscoveryContext.Object); + act.Should().Throw() + .WithMessage(string.Format(CultureInfo.CurrentCulture, Resource.TestAssembly_FileDoesNotExist, Source)); } public void DiscoverTestsInSourceShouldSendBackTestCasesDiscovered() diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs index 320b2de9a5..64e70e9b80 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TcmTestPropertiesProviderTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -33,7 +35,7 @@ public class TcmTestPropertiesProviderTests : TestContainer public void GetTcmPropertiesShouldReturnEmptyDictionaryIfTestCaseIsNull() { IDictionary? tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(null); - Verify(tcmProperties is null); + tcmProperties.Should().BeNull(); } public void GetTcmPropertiesShouldReturnEmptyDictionaryIfTestCaseIdIsZero() @@ -60,7 +62,7 @@ public void GetTcmPropertiesShouldReturnEmptyDictionaryIfTestCaseIdIsZero() SetTestCaseProperties(testCase, propertiesValue); IDictionary? tcmProperties = TcmTestPropertiesProvider.GetTcmProperties(testCase); - Verify(tcmProperties is null); + tcmProperties.Should().BeNull(); } public void GetTcmPropertiesShouldGetAllPropertiesFromTestCase() @@ -232,10 +234,10 @@ private void SetTestCaseProperties(TestCase testCase, object[] propertiesValue) private void VerifyTcmProperties(IDictionary? tcmProperties, TestCase testCase) { - Verify(tcmProperties is not null); + tcmProperties.Should().NotBeNull(); foreach (TestProperty property in _tcmKnownProperties) { - Verify(testCase.GetPropertyValue(property)!.Equals(tcmProperties[property])); + testCase.GetPropertyValue(property)!.Equals(tcmProperties[property]).Should().BeTrue(); } } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblyInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblyInfoTests.cs index 378eb236a5..3b1e273435 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblyInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblyInfoTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; @@ -39,7 +41,7 @@ void Action() _testAssemblyInfo.AssemblyInitializeMethod = _dummyMethodInfo; } - VerifyThrows(Action); + new Action(Action).Should().Throw(); } public void TestAssemblyInfoAssemblyCleanupMethodThrowsForMultipleAssemblyCleanupMethods() @@ -50,24 +52,24 @@ void Action() _testAssemblyInfo.AssemblyCleanupMethod = _dummyMethodInfo; } - VerifyThrows(Action); + new Action(Action).Should().Throw(); } - public void TestAssemblyHasExecutableCleanupMethodShouldReturnFalseIfAssemblyHasNoCleanupMethod() => Verify(!_testAssemblyInfo.HasExecutableCleanupMethod); + public void TestAssemblyHasExecutableCleanupMethodShouldReturnFalseIfAssemblyHasNoCleanupMethod() => _testAssemblyInfo.HasExecutableCleanupMethod.Should().BeFalse(); public void TestAssemblyHasExecutableCleanupMethodShouldReturnTrueEvenIfAssemblyInitializationThrewAnException() { _testAssemblyInfo.AssemblyCleanupMethod = _dummyMethodInfo; _testAssemblyInfo.AssemblyInitializationException = new NotImplementedException(); - Verify(_testAssemblyInfo.HasExecutableCleanupMethod); + _testAssemblyInfo.HasExecutableCleanupMethod.Should().BeTrue(); } public void TestAssemblyHasExecutableCleanupMethodShouldReturnTrueIfAssemblyCleanupMethodIsAvailable() { _testAssemblyInfo.AssemblyCleanupMethod = _dummyMethodInfo; - Verify(_testAssemblyInfo.HasExecutableCleanupMethod); + _testAssemblyInfo.HasExecutableCleanupMethod.Should().BeTrue(); } #region Run Assembly Initialize tests @@ -81,7 +83,7 @@ public void RunAssemblyInitializeShouldNotInvokeIfAssemblyInitializeIsNull() _testAssemblyInfo.RunAssemblyInitialize(null!); - Verify(assemblyInitCallCount == 0); + assemblyInitCallCount.Should().Be(0); } public void RunAssemblyInitializeShouldThrowIfTestContextIsNull() @@ -90,7 +92,7 @@ public void RunAssemblyInitializeShouldThrowIfTestContextIsNull() _testAssemblyInfo.AssemblyInitializeMethod = typeof(DummyTestClass).GetMethod("AssemblyInitializeMethod")!; - VerifyThrows(() => _testAssemblyInfo.RunAssemblyInitialize(null!)); + new Action(() => _testAssemblyInfo.RunAssemblyInitialize(null!)).Should().Throw(); } public void RunAssemblyInitializeShouldNotExecuteAssemblyInitializeIfItHasAlreadyExecuted() @@ -103,7 +105,7 @@ public void RunAssemblyInitializeShouldNotExecuteAssemblyInitializeIfItHasAlread _testAssemblyInfo.RunAssemblyInitialize(_testContext); - Verify(assemblyInitCallCount == 0); + assemblyInitCallCount.Should().Be(0); } public void RunAssemblyInitializeShouldExecuteAssemblyInitialize() @@ -114,7 +116,7 @@ public void RunAssemblyInitializeShouldExecuteAssemblyInitialize() _testAssemblyInfo.RunAssemblyInitialize(_testContext); - Verify(assemblyInitCallCount == 1); + assemblyInitCallCount.Should().Be(1); } public void RunAssemblyInitializeShouldSetAssemblyInitializeExecutedFlag() @@ -125,7 +127,7 @@ public void RunAssemblyInitializeShouldSetAssemblyInitializeExecutedFlag() _testAssemblyInfo.RunAssemblyInitialize(_testContext); - Verify(_testAssemblyInfo.IsAssemblyInitializeExecuted); + _testAssemblyInfo.IsAssemblyInitializeExecuted.Should().BeTrue(); } public void RunAssemblyInitializeShouldSetAssemblyInitializationExceptionOnException() @@ -133,9 +135,10 @@ public void RunAssemblyInitializeShouldSetAssemblyInitializationExceptionOnExcep DummyTestClass.AssemblyInitializeMethodBody = _ => UTF.Assert.Inconclusive("Test Inconclusive"); _testAssemblyInfo.AssemblyInitializeMethod = typeof(DummyTestClass).GetMethod("AssemblyInitializeMethod")!; - Exception exception = VerifyThrows(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)); + Action action = () => _testAssemblyInfo.RunAssemblyInitialize(_testContext); - Verify(_testAssemblyInfo.AssemblyInitializationException is not null); + action.Should().Throw(); + _testAssemblyInfo.AssemblyInitializationException.Should().NotBeNull(); } public void RunAssemblyInitializeShouldThrowTestFailedExceptionOnAssertionFailure() @@ -143,16 +146,14 @@ public void RunAssemblyInitializeShouldThrowTestFailedExceptionOnAssertionFailur DummyTestClass.AssemblyInitializeMethodBody = tc => UTF.Assert.Fail("Test failure"); _testAssemblyInfo.AssemblyInitializeMethod = typeof(DummyTestClass).GetMethod("AssemblyInitializeMethod")!; - TestFailedException exception = VerifyThrows(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify( - exception.Message - == "Assembly Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests+DummyTestClass.AssemblyInitializeMethod threw exception. Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: Assert.Fail failed. Test failure. Aborting test execution."); + TestFailedException exception = new Action(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)).Should().Throw().Which; + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Assembly Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests+DummyTestClass.AssemblyInitializeMethod threw exception. Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: Assert.Fail failed. Test failure. Aborting test execution."); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.Contains( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.<>c.", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.Should().Contain( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.<>c."); #endif - Verify(exception.InnerException!.GetType() == typeof(AssertFailedException)); + exception.InnerException.Should().BeOfType(); } public void RunAssemblyInitializeShouldThrowTestFailedExceptionWithInconclusiveOnAssertInconclusive() @@ -160,16 +161,14 @@ public void RunAssemblyInitializeShouldThrowTestFailedExceptionWithInconclusiveO DummyTestClass.AssemblyInitializeMethodBody = tc => UTF.Assert.Inconclusive("Test Inconclusive"); _testAssemblyInfo.AssemblyInitializeMethod = typeof(DummyTestClass).GetMethod("AssemblyInitializeMethod")!; - TestFailedException exception = VerifyThrows(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)); - Verify(exception.Outcome == UTF.UnitTestOutcome.Inconclusive); - Verify( - exception.Message - == "Assembly Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests+DummyTestClass.AssemblyInitializeMethod threw exception. Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException: Assert.Inconclusive failed. Test Inconclusive. Aborting test execution."); + TestFailedException exception = new Action(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)).Should().Throw().Which; + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); + exception.Message.Should().Be("Assembly Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests+DummyTestClass.AssemblyInitializeMethod threw exception. Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException: Assert.Inconclusive failed. Test Inconclusive. Aborting test execution."); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.Contains( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.<>c.", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.Should().Contain( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.<>c."); #endif - Verify(exception.InnerException!.GetType() == typeof(AssertInconclusiveException)); + exception.InnerException.Should().BeOfType(); } public void RunAssemblyInitializeShouldThrowTestFailedExceptionWithNonAssertExceptions() @@ -177,18 +176,16 @@ public void RunAssemblyInitializeShouldThrowTestFailedExceptionWithNonAssertExce DummyTestClass.AssemblyInitializeMethodBody = tc => throw new ArgumentException("Some actualErrorMessage message", new InvalidOperationException("Inner actualErrorMessage message")); _testAssemblyInfo.AssemblyInitializeMethod = typeof(DummyTestClass).GetMethod("AssemblyInitializeMethod")!; - TestFailedException exception = VerifyThrows(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)); + TestFailedException exception = new Action(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)).Should().Throw().Which; - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify( - exception.Message - == "Assembly Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests+DummyTestClass.AssemblyInitializeMethod threw exception. System.ArgumentException: Some actualErrorMessage message. Aborting test execution."); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Assembly Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests+DummyTestClass.AssemblyInitializeMethod threw exception. System.ArgumentException: Some actualErrorMessage message. Aborting test execution."); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.<>c.", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.<>c.", StringComparison.Ordinal).Should().BeTrue(); #endif - Verify(exception.InnerException!.GetType() == typeof(ArgumentException)); - Verify(exception.InnerException.InnerException!.GetType() == typeof(InvalidOperationException)); + exception.InnerException.Should().BeOfType(); + exception.InnerException.InnerException.Should().BeOfType(); } public void RunAssemblyInitializeShouldThrowTheInnerMostExceptionWhenThereAreMultipleNestedTypeInitializationExceptions() @@ -200,17 +197,15 @@ public void RunAssemblyInitializeShouldThrowTheInnerMostExceptionWhenThereAreMul FailingStaticHelper.DoWork(); _testAssemblyInfo.AssemblyInitializeMethod = typeof(DummyTestClass).GetMethod("AssemblyInitializeMethod")!; - TestFailedException exception = VerifyThrows(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)); + TestFailedException exception = new Action(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)).Should().Throw().Which; - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify( - exception.Message - == "Assembly Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests+DummyTestClass.AssemblyInitializeMethod threw exception. System.InvalidOperationException: I fail.. Aborting test execution."); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Assembly Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests+DummyTestClass.AssemblyInitializeMethod threw exception. System.InvalidOperationException: I fail.. Aborting test execution."); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.FailingStaticHelper..cctor()", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.FailingStaticHelper..cctor()", StringComparison.Ordinal).Should().BeTrue(); #endif - Verify(exception.InnerException!.GetType() == typeof(InvalidOperationException)); + exception.InnerException.Should().BeOfType(); } public void RunAssemblyInitializeShouldThrowForAlreadyExecutedTestAssemblyInitWithException() @@ -220,14 +215,14 @@ public void RunAssemblyInitializeShouldThrowForAlreadyExecutedTestAssemblyInitWi _testAssemblyInfo.AssemblyInitializeMethod = typeof(DummyTestClass).GetMethod("AssemblyInitializeMethod")!; _testAssemblyInfo.AssemblyInitializationException = new TestFailedException(UTF.UnitTestOutcome.Failed, "Cached Test failure"); - TestFailedException exception = VerifyThrows(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception.Message == "Cached Test failure"); + TestFailedException exception = new Action(() => _testAssemblyInfo.RunAssemblyInitialize(_testContext)).Should().Throw().Which; + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Cached Test failure"); } public void RunAssemblyInitializeShouldPassOnTheTestContextToAssemblyInitMethod() { - DummyTestClass.AssemblyInitializeMethodBody = tc => Verify(tc == _testContext); + DummyTestClass.AssemblyInitializeMethodBody = tc => (tc == _testContext).Should().BeTrue(); _testAssemblyInfo.AssemblyInitializeMethod = typeof(DummyTestClass).GetMethod("AssemblyInitializeMethod")!; _testAssemblyInfo.RunAssemblyInitialize(_testContext); @@ -244,8 +239,8 @@ public void RunAssemblyCleanupShouldNotInvokeIfAssemblyCleanupIsNull() _testAssemblyInfo.AssemblyCleanupMethod = null; - Verify(_testAssemblyInfo.ExecuteAssemblyCleanup(GetTestContext()) is null); - Verify(assemblyCleanupCallCount == 0); + _testAssemblyInfo.ExecuteAssemblyCleanup(GetTestContext()).Should().BeNull(); + assemblyCleanupCallCount.Should().Be(0); } public void RunAssemblyCleanupShouldInvokeIfAssemblyCleanupMethod() @@ -255,8 +250,8 @@ public void RunAssemblyCleanupShouldInvokeIfAssemblyCleanupMethod() _testAssemblyInfo.AssemblyCleanupMethod = typeof(DummyTestClass).GetMethod("AssemblyCleanupMethod")!; - Verify(_testAssemblyInfo.ExecuteAssemblyCleanup(GetTestContext()) is null); - Verify(assemblyCleanupCallCount == 1); + _testAssemblyInfo.ExecuteAssemblyCleanup(GetTestContext()).Should().BeNull(); + assemblyCleanupCallCount.Should().Be(1); } public void RunAssemblyCleanupShouldReturnAssertFailureExceptionDetails() @@ -265,10 +260,8 @@ public void RunAssemblyCleanupShouldReturnAssertFailureExceptionDetails() _testAssemblyInfo.AssemblyCleanupMethod = typeof(DummyTestClass).GetMethod("AssemblyCleanupMethod")!; string? actualErrorMessage = _testAssemblyInfo.ExecuteAssemblyCleanup(GetTestContext())?.Message; - Verify( - actualErrorMessage!.StartsWith( - "Assembly Cleanup method DummyTestClass.AssemblyCleanupMethod failed. Error Message: Assert.Fail failed. Test Failure..", StringComparison.Ordinal), - $"Value: {actualErrorMessage}"); + actualErrorMessage!.StartsWith( + "Assembly Cleanup method DummyTestClass.AssemblyCleanupMethod failed. Error Message: Assert.Fail failed. Test Failure..", StringComparison.Ordinal).Should().BeTrue($"Value: {actualErrorMessage}"); } public void RunAssemblyCleanupShouldReturnAssertInconclusiveExceptionDetails() @@ -277,10 +270,8 @@ public void RunAssemblyCleanupShouldReturnAssertInconclusiveExceptionDetails() _testAssemblyInfo.AssemblyCleanupMethod = typeof(DummyTestClass).GetMethod("AssemblyCleanupMethod")!; string? actualErrorMessage = _testAssemblyInfo.ExecuteAssemblyCleanup(GetTestContext())?.Message; - Verify( - actualErrorMessage!.StartsWith( - "Assembly Cleanup method DummyTestClass.AssemblyCleanupMethod failed. Error Message: Assert.Inconclusive failed. Test Inconclusive..", StringComparison.Ordinal), - $"Value: {actualErrorMessage}"); + actualErrorMessage!.StartsWith( + "Assembly Cleanup method DummyTestClass.AssemblyCleanupMethod failed. Error Message: Assert.Inconclusive failed. Test Inconclusive..", StringComparison.Ordinal).Should().BeTrue($"Value: {actualErrorMessage}"); } public void RunAssemblyCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() @@ -289,10 +280,8 @@ public void RunAssemblyCleanupShouldReturnExceptionDetailsOfNonAssertExceptions( _testAssemblyInfo.AssemblyCleanupMethod = typeof(DummyTestClass).GetMethod("AssemblyCleanupMethod")!; string? actualErrorMessage = _testAssemblyInfo.ExecuteAssemblyCleanup(GetTestContext())?.Message; - Verify( - actualErrorMessage!.StartsWith( - "Assembly Cleanup method DummyTestClass.AssemblyCleanupMethod failed. Error Message: System.ArgumentException: Argument Exception.", StringComparison.Ordinal), - $"Value: {actualErrorMessage}"); + actualErrorMessage!.StartsWith( + "Assembly Cleanup method DummyTestClass.AssemblyCleanupMethod failed. Error Message: System.ArgumentException: Argument Exception.", StringComparison.Ordinal).Should().BeTrue($"Value: {actualErrorMessage}"); } public void RunAssemblyCleanupShouldThrowTheInnerMostExceptionWhenThereAreMultipleNestedTypeInitializationExceptions() @@ -305,8 +294,8 @@ public void RunAssemblyCleanupShouldThrowTheInnerMostExceptionWhenThereAreMultip string actualErrorMessage = _testAssemblyInfo.ExecuteAssemblyCleanup(GetTestContext())!.Message; - Verify(actualErrorMessage.StartsWith("Assembly Cleanup method DummyTestClass.AssemblyCleanupMethod failed. Error Message: System.InvalidOperationException: I fail.. StackTrace:", StringComparison.Ordinal)); - Verify(actualErrorMessage.Contains("at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.FailingStaticHelper..cctor()")); + actualErrorMessage.StartsWith("Assembly Cleanup method DummyTestClass.AssemblyCleanupMethod failed. Error Message: System.InvalidOperationException: I fail.. StackTrace:", StringComparison.Ordinal).Should().BeTrue(); + actualErrorMessage.Contains("at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestAssemblyInfoTests.FailingStaticHelper..cctor()").Should().BeTrue(); } private static TestContextImplementation GetTestContext() diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblySettingsProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblySettingsProviderTests.cs index 734788289c..1897eee11b 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblySettingsProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestAssemblySettingsProviderTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; @@ -46,7 +48,7 @@ public void GetSettingsShouldSetParallelWorkersToNegativeByDefault() MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); // Assert. - Verify(settings.Workers == -1); + settings.Workers.Should().Be(-1); } public void GetSettingsShouldSetParallelWorkers() @@ -65,7 +67,7 @@ public void GetSettingsShouldSetParallelWorkers() MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); // Assert. - Verify(settings.Workers == 10); + settings.Workers.Should().Be(10); } public void GetSettingsShouldSetParallelWorkersToProcessorCountIfZero() @@ -84,7 +86,7 @@ public void GetSettingsShouldSetParallelWorkersToProcessorCountIfZero() MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); // Assert. - Verify(Environment.ProcessorCount == settings.Workers); + settings.Workers.Should().Be(Environment.ProcessorCount); } public void GetSettingsShouldSetParallelScopeToClassLevelByDefault() @@ -99,7 +101,7 @@ public void GetSettingsShouldSetParallelScopeToClassLevelByDefault() MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); // Assert. - Verify(settings.Scope == ExecutionScope.ClassLevel); + settings.Scope.Should().Be(ExecutionScope.ClassLevel); } public void GetSettingsShouldSetParallelScope() @@ -118,7 +120,7 @@ public void GetSettingsShouldSetParallelScope() MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); // Assert. - Verify(settings.Scope == ExecutionScope.MethodLevel); + settings.Scope.Should().Be(ExecutionScope.MethodLevel); } public void GetSettingsShouldSetCanParallelizeAssemblyToTrueByDefault() @@ -133,7 +135,7 @@ public void GetSettingsShouldSetCanParallelizeAssemblyToTrueByDefault() MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); // Assert. - Verify(settings.CanParallelizeAssembly); + settings.CanParallelizeAssembly.Should().BeTrue(); } public void GetSettingsShouldSetCanParallelizeAssemblyToFalseIfDoNotParallelizeIsSet() @@ -152,6 +154,6 @@ public void GetSettingsShouldSetCanParallelizeAssemblyToFalseIfDoNotParallelizeI MSTest.TestAdapter.ObjectModel.TestAssemblySettings settings = new TestAssemblySettingsProvider().GetSettings("Foo"); // Assert. - Verify(!settings.CanParallelizeAssembly); + settings.CanParallelizeAssembly.Should().BeFalse(); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestCaseDiscoverySinkTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestCaseDiscoverySinkTests.cs index 13575e5617..8eb4ab7011 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestCaseDiscoverySinkTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestCaseDiscoverySinkTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -16,16 +18,16 @@ public class TestCaseDiscoverySinkTests : TestContainer public void TestCaseDiscoverySinkConstructorShouldInitializeTests() { - Verify(_testCaseDiscoverySink.Tests is not null); - Verify(_testCaseDiscoverySink.Tests.Count == 0); + _testCaseDiscoverySink.Tests.Should().NotBeNull(); + _testCaseDiscoverySink.Tests.Count.Should().Be(0); } public void SendTestCaseShouldNotAddTestIfTestCaseIsNull() { _testCaseDiscoverySink.SendTestCase(null); - Verify(_testCaseDiscoverySink.Tests is not null); - Verify(_testCaseDiscoverySink.Tests.Count == 0); + _testCaseDiscoverySink.Tests.Should().NotBeNull(); + _testCaseDiscoverySink.Tests.Count.Should().Be(0); } public void SendTestCaseShouldAddTheTestCaseToTests() @@ -33,8 +35,8 @@ public void SendTestCaseShouldAddTheTestCaseToTests() TestCase tc = new("TAttribute", new Uri("executor://TestExecutorUri"), "A"); _testCaseDiscoverySink.SendTestCase(tc); - Verify(_testCaseDiscoverySink.Tests is not null); - Verify(_testCaseDiscoverySink.Tests.Count == 1); - Verify(tc == _testCaseDiscoverySink.Tests.ToArray()[0]); + _testCaseDiscoverySink.Tests.Should().NotBeNull(); + _testCaseDiscoverySink.Tests.Count.Should().Be(1); + _testCaseDiscoverySink.Tests.ToArray()[0].Should().Be(tc); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs index c6e902ae27..07bb9c97ff 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestClassInfoTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using System.Threading.Tasks; +using AwesomeAssertions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; @@ -93,15 +93,20 @@ public TestClassInfoTests() DummyTestClass.ClassCleanupMethodBody = null!; } - public void TestClassInfoClassAttributeGetsAReferenceToTheTestClassAttribute() => Verify(_testClassAttribute == _testClassInfo.ClassAttribute); + public void TestClassInfoClassAttributeGetsAReferenceToTheTestClassAttribute() + => _testClassInfo.ClassAttribute.Should().Be(_testClassAttribute); - public void TestClassInfoClassTypeGetsAReferenceToTheActualTypeForTheTestClass() => Verify(typeof(DummyTestClass) == _testClassInfo.ClassType); + public void TestClassInfoClassTypeGetsAReferenceToTheActualTypeForTheTestClass() + => _testClassInfo.ClassType.Should().Be(); - public void TestClassInfoConstructorGetsTheConstructorInfoForTestClass() => Verify(_testClassConstructor == _testClassInfo.Constructor); + public void TestClassInfoConstructorGetsTheConstructorInfoForTestClass() + => _testClassInfo.Constructor.Should().BeSameAs(_testClassConstructor); - public void TestClassInfoTestContextPropertyGetsAReferenceToTheTestContextDefinedInTestClass() => Verify(_testClassInfo.TestContextProperty == _testClassType.GetProperty("TestContext")); + public void TestClassInfoTestContextPropertyGetsAReferenceToTheTestContextDefinedInTestClass() + => _testClassInfo.TestContextProperty.Should().BeSameAs(_testClassType.GetProperty("TestContext")); - public void TestClassInfoParentGetsAReferenceToTheParentAssemblyForTheTestClass() => Verify(_testAssemblyInfo == _testClassInfo.Parent); + public void TestClassInfoParentGetsAReferenceToTheParentAssemblyForTheTestClass() + => _testClassInfo.Parent.Should().Be(_testAssemblyInfo); public void TestClassInfoClassInitializeMethodSetShouldThrowForMultipleClassInitializeMethods() { @@ -111,7 +116,7 @@ void Action() _testClassInfo.ClassInitializeMethod = _testClassType.GetMethods().First(); } - VerifyThrows(Action); + new Action(Action).Should().Throw(); } public void TestClassInfoClassCleanupMethodSetShouldThrowForMultipleClassCleanupMethods() @@ -122,7 +127,7 @@ void Action() _testClassInfo.ClassCleanupMethod = _testClassType.GetMethods().First(); } - VerifyThrows(Action); + new Action(Action).Should().Throw(); } private static TestContextImplementation CreateDummyTestContextImplementation() @@ -137,8 +142,8 @@ public async Task TestClassInfoClassCleanupMethodShouldNotInvokeWhenNoTestClassI _testClassInfo.ClassInitializeMethod = typeof(DummyTestClass).GetMethod("ClassInitializeMethod")!; TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // call cleanup without calling init - Verify(ex is null); - Verify(classCleanupCallCount == 0); + ex.Should().BeNull(); + classCleanupCallCount.Should().Be(0); } public async Task TestClassInfoClassCleanupMethodShouldInvokeWhenTestClassInitializedIsCalled() @@ -152,8 +157,8 @@ public async Task TestClassInfoClassCleanupMethodShouldInvokeWhenTestClassInitia GetResultOrRunClassInitialize(); TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // call cleanup without calling init - Verify(ex is null); - Verify(classCleanupCallCount == 1); + ex.Should().BeNull(); + classCleanupCallCount.Should().Be(1); } public async Task TestClassInfoClassCleanupMethodShouldInvokeBaseClassCleanupMethodWhenTestClassInitializedIsCalled() @@ -167,25 +172,25 @@ public async Task TestClassInfoClassCleanupMethodShouldInvokeBaseClassCleanupMet GetResultOrRunClassInitialize(); TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); - Verify(ex is null); - Verify(classCleanupCallCount == 1); + ex.Should().BeNull(); + classCleanupCallCount.Should().Be(1); } - public void TestClassInfoHasExecutableCleanupMethodShouldReturnFalseIfClassDoesNotHaveCleanupMethod() => Verify(!_testClassInfo.HasExecutableCleanupMethod); + public void TestClassInfoHasExecutableCleanupMethodShouldReturnFalseIfClassDoesNotHaveCleanupMethod() => _testClassInfo.HasExecutableCleanupMethod.Should().BeFalse(); public void TestClassInfoHasExecutableCleanupMethodShouldReturnTrueEvenIfClassInitializeThrowsAnException() { _testClassInfo.ClassCleanupMethod = _testClassType.GetMethods().First(); _testClassInfo.ClassInitializationException = new NotImplementedException(); - Verify(_testClassInfo.HasExecutableCleanupMethod); + _testClassInfo.HasExecutableCleanupMethod.Should().BeTrue(); } public void TestClassInfoHasExecutableCleanupMethodShouldReturnTrueIfClassHasCleanupMethod() { _testClassInfo.ClassCleanupMethod = _testClassType.GetMethods().First(); - Verify(_testClassInfo.HasExecutableCleanupMethod); + _testClassInfo.HasExecutableCleanupMethod.Should().BeTrue(); } #region Run Class Initialize tests @@ -199,7 +204,7 @@ public void RunClassInitializeShouldNotInvokeIfClassInitializeIsNull() GetResultOrRunClassInitialize(null); - Verify(classInitCallCount == 0); + classInitCallCount.Should().Be(0); } public void RunClassInitializeShouldThrowIfTestContextIsNull() @@ -210,9 +215,9 @@ public void RunClassInitializeShouldThrowIfTestContextIsNull() TestResult result = GetResultOrRunClassInitialize(null); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(result.Outcome == UTF.UnitTestOutcome.Error); - Verify(exception.Message == "TestContext cannot be Null."); + exception.Should().NotBeNull(); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Error); + exception.Message.Should().Be("TestContext cannot be Null."); } public void RunClassInitializeShouldExecuteClassInitialize() @@ -222,12 +227,12 @@ public void RunClassInitializeShouldExecuteClassInitialize() _testClassInfo.ClassInitializeMethod = typeof(DummyTestClass).GetMethod("ClassInitializeMethod")!; GetResultOrRunClassInitialize(); - Verify(classInitCallCount == 1); - Verify(_testClassInfo.IsClassInitializeExecuted); + classInitCallCount.Should().Be(1); + _testClassInfo.IsClassInitializeExecuted.Should().BeTrue(); GetResultOrRunClassInitialize(); - Verify(classInitCallCount == 1); - Verify(_testClassInfo.IsClassInitializeExecuted); + classInitCallCount.Should().Be(1); + _testClassInfo.IsClassInitializeExecuted.Should().BeTrue(); } public void RunClassInitializeShouldSetClassInitializeExecutedFlag() @@ -237,7 +242,7 @@ public void RunClassInitializeShouldSetClassInitializeExecutedFlag() GetResultOrRunClassInitialize(); - Verify(_testClassInfo.IsClassInitializeExecuted); + _testClassInfo.IsClassInitializeExecuted.Should().BeTrue(); } public void RunClassInitializeShouldOnlyRunOnce() @@ -249,7 +254,7 @@ public void RunClassInitializeShouldOnlyRunOnce() GetResultOrRunClassInitialize(); GetResultOrRunClassInitialize(); - Verify(classInitCallCount == 1, "Class Initialize called only once"); + classInitCallCount.Should().Be(1, "Class Initialize called only once"); } public void RunClassInitializeShouldRunOnlyOnceIfThereIsNoDerivedClassInitializeAndSetClassInitializeExecutedFlag() @@ -259,10 +264,10 @@ public void RunClassInitializeShouldRunOnlyOnceIfThereIsNoDerivedClassInitialize _testClassInfo.BaseClassInitMethods.Add(typeof(DummyBaseTestClass).GetMethod("InitBaseClassMethod")!); GetResultOrRunClassInitialize(); - Verify(_testClassInfo.IsClassInitializeExecuted); + _testClassInfo.IsClassInitializeExecuted.Should().BeTrue(); GetResultOrRunClassInitialize(); - Verify(classInitCallCount == 1); + classInitCallCount.Should().Be(1); } public void RunClassInitializeShouldSetClassInitializationExceptionOnException() @@ -273,7 +278,7 @@ public void RunClassInitializeShouldSetClassInitializationExceptionOnException() var exception = GetResultOrRunClassInitialize().TestFailureException as TestFailedException; Assert.IsNotNull(exception); - Verify(_testClassInfo.ClassInitializationException is not null); + _testClassInfo.ClassInitializationException.Should().NotBeNull(); } public void RunClassInitializeShouldExecuteBaseClassInitializeMethod() @@ -287,7 +292,7 @@ public void RunClassInitializeShouldExecuteBaseClassInitializeMethod() GetResultOrRunClassInitialize(); - Verify(classInitCallCount == 2); + classInitCallCount.Should().Be(2); } public void RunClassInitializeShouldNotExecuteBaseClassInitializeMethodIfClassInitializeHasExecuted() @@ -301,10 +306,10 @@ public void RunClassInitializeShouldNotExecuteBaseClassInitializeMethodIfClassIn _testClassInfo.ClassInitializeMethod = typeof(DummyDerivedTestClass).GetMethod("InitDerivedClassMethod")!; GetResultOrRunClassInitialize(); - Verify(_testClassInfo.IsClassInitializeExecuted); + _testClassInfo.IsClassInitializeExecuted.Should().BeTrue(); GetResultOrRunClassInitialize(); // this one shouldn't run - Verify(classInitCallCount == 3); + classInitCallCount.Should().Be(3); } public void RunClassInitializeShouldExecuteBaseClassInitializeIfDerivedClassInitializeIsNull() @@ -315,7 +320,7 @@ public void RunClassInitializeShouldExecuteBaseClassInitializeIfDerivedClassInit GetResultOrRunClassInitialize(); - Verify(classInitCallCount == 1); + classInitCallCount.Should().Be(1); } public void RunClassInitializeShouldNotExecuteBaseClassIfBaseClassInitializeIsNull() @@ -327,7 +332,7 @@ public void RunClassInitializeShouldNotExecuteBaseClassIfBaseClassInitializeIsNu GetResultOrRunClassInitialize(); - Verify(classInitCallCount == 1); + classInitCallCount.Should().Be(1); } public void RunClassInitializeShouldThrowTestFailedExceptionOnBaseInitializeMethodWithNonAssertExceptions() @@ -339,16 +344,14 @@ public void RunClassInitializeShouldThrowTestFailedExceptionOnBaseInitializeMeth var exception = GetResultOrRunClassInitialize().TestFailureException as TestFailedException; Assert.IsNotNull(exception); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify( - exception.Message - == "Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.InitBaseClassMethod threw exception. System.ArgumentException: Some exception message."); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.InitBaseClassMethod threw exception. System.ArgumentException: Some exception message."); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal).Should().BeTrue(); #endif - Verify(exception.InnerException!.GetType() == typeof(ArgumentException)); - Verify(exception.InnerException.InnerException!.GetType() == typeof(InvalidOperationException)); + exception.InnerException.Should().BeOfType(); + exception.InnerException.InnerException.Should().BeOfType(); } public void RunClassInitializeShouldThrowTestFailedExceptionOnAssertionFailure() @@ -359,15 +362,13 @@ public void RunClassInitializeShouldThrowTestFailedExceptionOnAssertionFailure() var exception = GetResultOrRunClassInitialize().TestFailureException as TestFailedException; Assert.IsNotNull(exception); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify( - exception.Message - == "Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.ClassInitializeMethod threw exception. Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: Assert.Fail failed. Test failure."); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.ClassInitializeMethod threw exception. Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: Assert.Fail failed. Test failure."); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.Contains( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.Contains( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal).Should().BeTrue(); #endif - Verify(exception.InnerException!.GetType() == typeof(AssertFailedException)); + exception.InnerException.Should().BeOfType(); } public void RunClassInitializeShouldThrowTestFailedExceptionWithInconclusiveOnAssertInconclusive() @@ -378,15 +379,13 @@ public void RunClassInitializeShouldThrowTestFailedExceptionWithInconclusiveOnAs var exception = GetResultOrRunClassInitialize().TestFailureException as TestFailedException; Assert.IsNotNull(exception); - Verify(exception.Outcome == UTF.UnitTestOutcome.Inconclusive); - Verify( - exception.Message - == "Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.ClassInitializeMethod threw exception. Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException: Assert.Inconclusive failed. Test Inconclusive."); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); + exception.Message.Should().Be("Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.ClassInitializeMethod threw exception. Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException: Assert.Inconclusive failed. Test Inconclusive."); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.Contains( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.Contains( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal).Should().BeTrue(); #endif - Verify(exception.InnerException!.GetType() == typeof(AssertInconclusiveException)); + exception.InnerException.Should().BeOfType(); } public void RunClassInitializeShouldThrowTestFailedExceptionWithNonAssertExceptions() @@ -397,13 +396,11 @@ public void RunClassInitializeShouldThrowTestFailedExceptionWithNonAssertExcepti var exception = GetResultOrRunClassInitialize().TestFailureException as TestFailedException; Assert.IsNotNull(exception); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify( - exception.Message - == "Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.ClassInitializeMethod threw exception. System.ArgumentException: Argument exception."); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.ClassInitializeMethod threw exception. System.ArgumentException: Argument exception."); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.<>c.", StringComparison.Ordinal).Should().BeTrue(); #endif } @@ -415,13 +412,13 @@ public void RunClassInitializeShouldThrowForAlreadyExecutedTestClassInitWithExce var exception = GetResultOrRunClassInitialize().TestFailureException as TestFailedException; Assert.IsNotNull(exception); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception.Message == "Cached Test failure"); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Cached Test failure"); } public void RunAssemblyInitializeShouldPassOnTheTestContextToAssemblyInitMethod() { - DummyTestClass.ClassInitializeMethodBody = tc => Verify(tc == _testContext); + DummyTestClass.ClassInitializeMethodBody = tc => (tc == _testContext).Should().BeTrue(); _testClassInfo.ClassInitializeMethod = typeof(DummyTestClass).GetMethod("ClassInitializeMethod")!; GetResultOrRunClassInitialize(); @@ -439,16 +436,13 @@ public void RunClassInitializeShouldThrowTheInnerMostExceptionWhenThereAreMultip var exception = GetResultOrRunClassInitialize().TestFailureException as TestFailedException; Assert.IsNotNull(exception); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify( - exception.Message - == "Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.ClassInitializeMethod threw exception. System.InvalidOperationException: I fail.."); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be("Class Initialization method Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests+DummyTestClass.ClassInitializeMethod threw exception. System.InvalidOperationException: I fail.."); #if DEBUG - Verify( - exception.StackTraceInformation!.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.FailingStaticHelper..cctor()", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.FailingStaticHelper..cctor()", StringComparison.Ordinal).Should().BeTrue(); #endif - Verify(exception.InnerException!.GetType() == typeof(InvalidOperationException)); + exception.InnerException.Should().BeOfType(); } private TestResult GetResultOrRunClassInitialize() @@ -472,8 +466,8 @@ public async Task RunClassCleanupShouldInvokeIfClassCleanupMethod() TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert - Verify(ex is null); - Verify(classCleanupCallCount == 1); + ex.Should().BeNull(); + classCleanupCallCount.Should().Be(1); } public async Task RunClassCleanupShouldNotInvokeIfClassCleanupIsNull() @@ -487,8 +481,8 @@ public async Task RunClassCleanupShouldNotInvokeIfClassCleanupIsNull() TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert - Verify(ex is null); - Verify(classCleanupCallCount == 0); + ex.Should().BeNull(); + classCleanupCallCount.Should().Be(0); } public async Task RunClassCleanupShouldReturnAssertFailureExceptionDetails() @@ -502,14 +496,13 @@ public async Task RunClassCleanupShouldReturnAssertFailureExceptionDetails() TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert - Verify(classCleanupException is not null); - Verify(classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed.", StringComparison.Ordinal)); - Verify(classCleanupException.Message.Contains("Error Message: Assert.Fail failed. Test Failure.")); + classCleanupException.Should().NotBeNull(); + classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed.", StringComparison.Ordinal).Should().BeTrue(); + classCleanupException.Message.Contains("Error Message: Assert.Fail failed. Test Failure.").Should().BeTrue(); #if DEBUG - Verify( - classCleanupException.Message.Contains( - $"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunClassCleanupShouldReturnAssertFailureExceptionDetails)}>"), - $"Value: {classCleanupException.Message}"); + classCleanupException.Message.Should().Contain( + $"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunClassCleanupShouldReturnAssertFailureExceptionDetails)}>", + $"Value: {classCleanupException.Message}"); #endif } @@ -524,12 +517,12 @@ public async Task RunClassCleanupShouldReturnAssertInconclusiveExceptionDetails( TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert - Verify(classCleanupException is not null); - Verify(classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed.", StringComparison.Ordinal)); - Verify(classCleanupException.Message.Contains("Error Message: Assert.Inconclusive failed. Test Inconclusive.")); + classCleanupException.Should().NotBeNull(); + classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed.", StringComparison.Ordinal).Should().BeTrue(); + classCleanupException.Message.Contains("Error Message: Assert.Inconclusive failed. Test Inconclusive.").Should().BeTrue(); #if DEBUG - Verify( - classCleanupException.Message.Contains($"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunClassCleanupShouldReturnAssertInconclusiveExceptionDetails)}>"), + classCleanupException.Message.Should().Contain( + $"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunClassCleanupShouldReturnAssertInconclusiveExceptionDetails)}>", $"Value: {classCleanupException.Message}"); #endif } @@ -545,10 +538,10 @@ public async Task RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptio TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert - Verify(classCleanupException is not null); - Verify(classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed.", StringComparison.Ordinal)); - Verify(classCleanupException.Message.Contains("Error Message: System.ArgumentException: Argument Exception. Stack Trace:")); - Verify(classCleanupException.Message.Contains($"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions)}>")); + classCleanupException.Should().NotBeNull(); + classCleanupException.Message.Should().StartWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed."); + classCleanupException.Message.Should().Contain("Error Message: System.ArgumentException: Argument Exception. Stack Trace:"); + classCleanupException.Message.Should().Contain($"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions)}>"); } public async Task RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions() @@ -564,10 +557,10 @@ public async Task RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExcept TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert - Verify(classCleanupException is not null); - Verify(classCleanupException.Message.StartsWith("Class Cleanup method DummyBaseTestClass.CleanupClassMethod failed.", StringComparison.Ordinal)); - Verify(classCleanupException.Message.Contains("Error Message: System.ArgumentException: Argument Exception. Stack Trace:")); - Verify(classCleanupException.Message.Contains($"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions)}>")); + classCleanupException.Should().NotBeNull(); + classCleanupException.Message.Should().StartWith("Class Cleanup method DummyBaseTestClass.CleanupClassMethod failed."); + classCleanupException.Message.Should().Contain("Error Message: System.ArgumentException: Argument Exception. Stack Trace:"); + classCleanupException.Message.Should().Contain($"{typeof(TestClassInfoTests).FullName}.<>c.<{nameof(this.RunBaseClassCleanupWithNoDerivedClassCleanupShouldReturnExceptionDetailsOfNonAssertExceptions)}>"); } public async Task RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() @@ -583,27 +576,27 @@ public async Task RunBaseClassCleanupEvenIfThereIsNoDerivedClassCleanup() TestFailedException? ex = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert - Verify(ex is null); - Verify(_testClassInfo.HasExecutableCleanupMethod); - Verify(classCleanupCallCount == 0, "DummyBaseTestClass.CleanupClassMethod call count"); + ex.Should().BeNull(); + _testClassInfo.HasExecutableCleanupMethod.Should().BeTrue(); + classCleanupCallCount.Should().Be(0, "DummyBaseTestClass.CleanupClassMethod call count"); // Act 2 GetResultOrRunClassInitialize(null); ex = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert 2 - Verify(ex is null); - Verify(_testClassInfo.HasExecutableCleanupMethod); - Verify(_testClassInfo.IsClassInitializeExecuted); - Verify(classCleanupCallCount == 1, "DummyBaseTestClass.CleanupClassMethod call count"); + ex.Should().BeNull(); + _testClassInfo.HasExecutableCleanupMethod.Should().BeTrue(); + _testClassInfo.IsClassInitializeExecuted.Should().BeTrue(); + classCleanupCallCount.Should().Be(1, "DummyBaseTestClass.CleanupClassMethod call count"); // Act 3 ex = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); // Assert 3 - Verify(ex is null); - Verify(_testClassInfo.HasExecutableCleanupMethod); - Verify(classCleanupCallCount == 1, "DummyBaseTestClass.CleanupClassMethod call count"); + ex.Should().BeNull(); + _testClassInfo.HasExecutableCleanupMethod.Should().BeTrue(); + classCleanupCallCount.Should().Be(1, "DummyBaseTestClass.CleanupClassMethod call count"); } public async Task RunClassCleanupShouldThrowTheInnerMostExceptionWhenThereAreMultipleNestedTypeInitializationExceptions() @@ -617,9 +610,9 @@ public async Task RunClassCleanupShouldThrowTheInnerMostExceptionWhenThereAreMul GetResultOrRunClassInitialize(null); TestFailedException? classCleanupException = await _testClassInfo.ExecuteClassCleanupAsync(CreateDummyTestContextImplementation()); - Verify(classCleanupException is not null); - Verify(classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed. Error Message: System.InvalidOperationException: I fail..", StringComparison.Ordinal)); - Verify(classCleanupException.Message.Contains("at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.FailingStaticHelper..cctor()")); + classCleanupException.Should().NotBeNull(); + classCleanupException.Message.StartsWith("Class Cleanup method DummyTestClass.ClassCleanupMethod failed. Error Message: System.InvalidOperationException: I fail..", StringComparison.Ordinal).Should().BeTrue(); + classCleanupException.Message.Contains("at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestClassInfoTests.FailingStaticHelper..cctor()").Should().BeTrue(); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs index abf170d0f4..f760793c9b 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestExecutionManagerTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; @@ -93,9 +95,9 @@ public async Task RunTestsForTestWithFilterErrorShouldSendZeroResults() await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, _cancellationToken); // No Results - Verify(_frameworkHandle.TestCaseStartList.Count == 0); - Verify(_frameworkHandle.ResultsList.Count == 0); - Verify(_frameworkHandle.TestCaseEndList.Count == 0); + _frameworkHandle.TestCaseStartList.Count.Should().Be(0); + _frameworkHandle.ResultsList.Count.Should().Be(0); + _frameworkHandle.TestCaseEndList.Count.Should().Be(0); } public async Task RunTestsForTestWithFilterShouldSendResultsForFilteredTests() @@ -113,9 +115,9 @@ public async Task RunTestsForTestWithFilterShouldSendResultsForFilteredTests() List expectedTestCaseEndList = ["PassingTest:Passed"]; List expectedResultList = ["PassingTest Passed"]; - Verify(expectedTestCaseStartList.SequenceEqual(_frameworkHandle.TestCaseStartList)); - Verify(expectedTestCaseEndList.SequenceEqual(_frameworkHandle.TestCaseEndList)); - Verify(expectedResultList.SequenceEqual(_frameworkHandle.ResultsList)); + expectedTestCaseStartList.SequenceEqual(_frameworkHandle.TestCaseStartList).Should().BeTrue(); + expectedTestCaseEndList.SequenceEqual(_frameworkHandle.TestCaseEndList).Should().BeTrue(); + expectedResultList.SequenceEqual(_frameworkHandle.ResultsList).Should().BeTrue(); } public async Task RunTestsForIgnoredTestShouldSendResultsMarkingIgnoredTestsAsSkipped() @@ -125,9 +127,9 @@ public async Task RunTestsForIgnoredTestShouldSendResultsMarkingIgnoredTestsAsSk await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, _cancellationToken); - Verify(_frameworkHandle.TestCaseStartList[0] == "IgnoredTest"); - Verify(_frameworkHandle.TestCaseEndList[0] == "IgnoredTest:Skipped"); - Verify(_frameworkHandle.ResultsList[0] == "IgnoredTest Skipped"); + _frameworkHandle.TestCaseStartList[0].Should().Be("IgnoredTest"); + _frameworkHandle.TestCaseEndList[0].Should().Be("IgnoredTest:Skipped"); + _frameworkHandle.ResultsList[0].Should().Be("IgnoredTest Skipped"); } public async Task RunTestsForASingleTestShouldSendSingleResult() @@ -142,9 +144,9 @@ public async Task RunTestsForASingleTestShouldSendSingleResult() List expectedTestCaseEndList = ["PassingTest:Passed"]; List expectedResultList = ["PassingTest Passed"]; - Verify(expectedTestCaseStartList.SequenceEqual(_frameworkHandle.TestCaseStartList)); - Verify(expectedTestCaseEndList.SequenceEqual(_frameworkHandle.TestCaseEndList)); - Verify(expectedResultList.SequenceEqual(_frameworkHandle.ResultsList)); + expectedTestCaseStartList.SequenceEqual(_frameworkHandle.TestCaseStartList).Should().BeTrue(); + expectedTestCaseEndList.SequenceEqual(_frameworkHandle.TestCaseEndList).Should().BeTrue(); + expectedResultList.SequenceEqual(_frameworkHandle.ResultsList).Should().BeTrue(); } public async Task RunTestsForMultipleTestShouldSendMultipleResults() @@ -159,10 +161,10 @@ public async Task RunTestsForMultipleTestShouldSendMultipleResults() List expectedTestCaseEndList = ["PassingTest:Passed", "FailingTest:Failed"]; List expectedResultList = ["PassingTest Passed", "FailingTest Failed\r\n Message: Assert.Fail failed."]; - Verify(expectedTestCaseStartList.SequenceEqual(_frameworkHandle.TestCaseStartList)); - Verify(expectedTestCaseEndList.SequenceEqual(_frameworkHandle.TestCaseEndList)); - Verify(expectedResultList[0] == _frameworkHandle.ResultsList[0]); - Verify(_frameworkHandle.ResultsList[1].Contains(expectedResultList[1])); + expectedTestCaseStartList.SequenceEqual(_frameworkHandle.TestCaseStartList).Should().BeTrue(); + expectedTestCaseEndList.SequenceEqual(_frameworkHandle.TestCaseEndList).Should().BeTrue(); + _frameworkHandle.ResultsList[0].Should().Be(expectedResultList[0]); + _frameworkHandle.ResultsList[1].Should().Contain(expectedResultList[1]); } public async Task RunTestsForCancellationTokenCanceledSetToTrueShouldSendZeroResults() @@ -173,14 +175,13 @@ public async Task RunTestsForCancellationTokenCanceledSetToTrueShouldSendZeroRes // Cancel the test run _cancellationToken.Cancel(); - Exception exception = await VerifyThrowsAsync(() => _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, _cancellationToken)); - - Verify(exception is OperationCanceledException); + Func func = () => _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, _cancellationToken); + await func.Should().ThrowAsync(); // No Results - Verify(_frameworkHandle.TestCaseStartList.Count == 0); - Verify(_frameworkHandle.ResultsList.Count == 0); - Verify(_frameworkHandle.TestCaseEndList.Count == 0); + _frameworkHandle.TestCaseStartList.Should().BeEmpty(); + _frameworkHandle.ResultsList.Should().BeEmpty(); + _frameworkHandle.TestCaseEndList.Should().BeEmpty(); } public async Task RunTestsForTestShouldDeployBeforeExecution() @@ -199,8 +200,8 @@ await _testExecutionManager.RunTestsAsync( _frameworkHandle, new TestRunCancellationToken()); - Verify(_callers[0] == "Deploy", "Deploy should be called before execution."); - Verify(_callers[1] == "LoadAssembly", "Deploy should be called before execution."); + _callers[0].Should().Be("Deploy", "Deploy should be called before execution."); + _callers[1].Should().Be("LoadAssembly", "Deploy should be called before execution."); } public async Task RunTestsForTestShouldCleanupAfterExecution() @@ -215,8 +216,8 @@ public async Task RunTestsForTestShouldCleanupAfterExecution() await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(_callers[0] == "LoadAssembly", "Cleanup should be called after execution."); - Verify(_callers.LastOrDefault() == "Cleanup", "Cleanup should be called after execution."); + _callers[0].Should().Be("LoadAssembly", "Cleanup should be called after execution."); + _callers.LastOrDefault().Should().Be("Cleanup", "Cleanup should be called after execution."); } public async Task RunTestsForTestShouldNotCleanupOnTestFailure() @@ -272,8 +273,8 @@ public async Task RunTestsForTestShouldPassInTestRunParametersInformationAsPrope await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(DummyTestClass.TestContextProperties!.Contains( - new KeyValuePair("webAppUrl", "http://localhost"))); + DummyTestClass.TestContextProperties!.Contains( + new KeyValuePair("webAppUrl", "http://localhost")).Should().BeTrue(); } public async Task RunTestsForTestShouldPassInTcmPropertiesAsPropertiesToTheTest() @@ -348,7 +349,7 @@ public async Task RunTestsShouldClearSessionParametersAcrossRuns() // Trigger another Run await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify("http://updatedLocalHost".Equals(DummyTestClass.TestContextProperties!["webAppUrl"])); + "http://updatedLocalHost".Equals(DummyTestClass.TestContextProperties!["webAppUrl"]).Should().BeTrue(); } #endregion @@ -362,9 +363,9 @@ private async Task RunTestsForSourceShouldRunTestsInASource() await _testExecutionManager.RunTestsAsync(sources, _runContext, _frameworkHandle, _mockTestSourceHandler.Object, _cancellationToken); - Verify(_frameworkHandle.TestCaseStartList.Contains("PassingTest")); - Verify(_frameworkHandle.TestCaseEndList.Contains("PassingTest:Passed")); - Verify(_frameworkHandle.ResultsList.Contains("PassingTest Passed")); + _frameworkHandle.TestCaseStartList.Contains("PassingTest").Should().BeTrue(); + _frameworkHandle.TestCaseEndList.Contains("PassingTest:Passed").Should().BeTrue(); + _frameworkHandle.ResultsList.Contains("PassingTest Passed").Should().BeTrue(); } [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "This is currently ignored and that's why we marked it as private")] @@ -384,9 +385,8 @@ private async Task RunTestsForSourceShouldPassInTestRunParametersInformationAsPr await _testExecutionManager.RunTestsAsync(sources, _runContext, _frameworkHandle, _mockTestSourceHandler.Object, _cancellationToken); - Verify( - DummyTestClass.TestContextProperties!.Contains( - new KeyValuePair("webAppUrl", "http://localhost"))); + DummyTestClass.TestContextProperties!.Contains( + new KeyValuePair("webAppUrl", "http://localhost")).Should().BeTrue(); } [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "This is currently ignored and that's why we marked it as private")] @@ -396,7 +396,7 @@ private async Task RunTestsForSourceShouldPassInDeploymentInformationAsPropertie await _testExecutionManager.RunTestsAsync(sources, _runContext, _frameworkHandle, _mockTestSourceHandler.Object, _cancellationToken); - Verify(DummyTestClass.TestContextProperties is not null); + DummyTestClass.TestContextProperties.Should().NotBeNull(); } public async Task RunTestsForMultipleSourcesShouldRunEachTestJustOnce() @@ -409,7 +409,7 @@ public async Task RunTestsForMultipleSourcesShouldRunEachTestJustOnce() }; await testableTestExecutionManager.RunTestsAsync(sources, _runContext, _frameworkHandle, _mockTestSourceHandler.Object, _cancellationToken); - Verify(testsCount == 4); + testsCount.Should().Be(4); } #endregion @@ -422,8 +422,8 @@ public void SendTestResultsShouldFillInDataRowIndexIfTestIsDataDriven() TestTools.UnitTesting.TestResult unitTestResult1 = new() { DatarowIndex = 0, DisplayName = "DummyTest" }; TestTools.UnitTesting.TestResult unitTestResult2 = new() { DatarowIndex = 1, DisplayName = "DummyTest" }; _testExecutionManager.SendTestResults(testCase, [unitTestResult1, unitTestResult2], default, default, _frameworkHandle); - Verify(_frameworkHandle.TestDisplayNameList[0] == "DummyTest (Data Row 0)"); - Verify(_frameworkHandle.TestDisplayNameList[1] == "DummyTest (Data Row 1)"); + _frameworkHandle.TestDisplayNameList[0].Should().Be("DummyTest (Data Row 0)"); + _frameworkHandle.TestDisplayNameList[1].Should().Be("DummyTest (Data Row 1)"); } #endregion @@ -457,9 +457,9 @@ public async Task RunTestsForTestShouldRunTestsInParallelWhenEnabledInRunsetting MSTestSettings.PopulateSettings(_runContext, _mockMessageLogger.Object, null); await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(DummyTestClassForParallelize.ThreadIds.Count == 1); - Verify(DummyTestClassForParallelize2.ThreadIds.Count == 1); - Verify(_enqueuedParallelTestsCount == 2); + DummyTestClassForParallelize.ThreadIds.Count.Should().Be(1); + DummyTestClassForParallelize2.ThreadIds.Count.Should().Be(1); + _enqueuedParallelTestsCount.Should().Be(2); } finally { @@ -494,10 +494,10 @@ public async Task RunTestsForTestShouldRunTestsByMethodLevelWhenSpecified() MSTestSettings.PopulateSettings(_runContext, _mockMessageLogger.Object, null); await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(_enqueuedParallelTestsCount == 2); + _enqueuedParallelTestsCount.Should().Be(2); // Run on 1 or 2 threads - Verify(DummyTestClassForParallelize.ThreadIds.Count is 1 or 2); + DummyTestClassForParallelize.ThreadIds.Count.Should().BeOneOf(1, 2); } finally { @@ -531,11 +531,11 @@ public async Task RunTestsForTestShouldRunTestsWithSpecifiedNumberOfWorkers() MSTestSettings.PopulateSettings(_runContext, _mockMessageLogger.Object, null); await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(DummyTestClassForParallelize.ThreadIds.Count == 1); - Verify(DummyTestClassForParallelize2.ThreadIds.Count == 1); - Verify(DummyTestClassForParallelize3.ThreadIds.Count == 1); + DummyTestClassForParallelize.ThreadIds.Count.Should().Be(1); + DummyTestClassForParallelize2.ThreadIds.Count.Should().Be(1); + DummyTestClassForParallelize3.ThreadIds.Count.Should().Be(1); - Verify(_enqueuedParallelTestsCount == 3); + _enqueuedParallelTestsCount.Should().Be(3); } finally { @@ -594,7 +594,7 @@ public async Task RunTestsForTestShouldNotRunTestsInParallelWhenDisabledFromRuns await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(DummyTestClassForParallelize.ThreadIds.Count == 1); + DummyTestClassForParallelize.ThreadIds.Count.Should().Be(1); } finally { @@ -653,7 +653,7 @@ public async Task RunTestsForTestShouldNotRunTestsInParallelWhenDisabledFromSour await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(DummyTestClassForParallelize.ThreadIds.Count == 1); + DummyTestClassForParallelize.ThreadIds.Count.Should().Be(1); } finally { @@ -692,10 +692,10 @@ public async Task RunTestsForTestShouldRunNonParallelizableTestsSeparately() MSTestSettings.PopulateSettings(_runContext, _mockMessageLogger.Object, null); await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(_enqueuedParallelTestsCount == 2); - Verify(DummyTestClassWithDoNotParallelizeMethods.ParallelizableTestsThreadIds.Count is 1 or 2); - Verify(DummyTestClassWithDoNotParallelizeMethods.UnParallelizableTestsThreadIds.Count == 1); - Verify(DummyTestClassWithDoNotParallelizeMethods.LastParallelizableTestRun.TimeOfDay.TotalMilliseconds <= DummyTestClassWithDoNotParallelizeMethods.FirstUnParallelizableTestRun.TimeOfDay.TotalMilliseconds); + _enqueuedParallelTestsCount.Should().Be(2); + DummyTestClassWithDoNotParallelizeMethods.ParallelizableTestsThreadIds.Count.Should().BeOneOf(1, 2); + DummyTestClassWithDoNotParallelizeMethods.UnParallelizableTestsThreadIds.Count.Should().Be(1); + (DummyTestClassWithDoNotParallelizeMethods.LastParallelizableTestRun.TimeOfDay.TotalMilliseconds <= DummyTestClassWithDoNotParallelizeMethods.FirstUnParallelizableTestRun.TimeOfDay.TotalMilliseconds).Should().BeTrue(); } finally { @@ -758,10 +758,10 @@ public async Task RunTestsForTestShouldPreferParallelSettingsFromRunSettingsOver await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(_enqueuedParallelTestsCount == 2); + _enqueuedParallelTestsCount.Should().Be(2); // Run on 1 or 2 threads - Verify(DummyTestClassForParallelize.ThreadIds.Count is 1 or 2); + DummyTestClassForParallelize.ThreadIds.Count.Should().BeOneOf(1, 2); } finally { @@ -798,8 +798,8 @@ private async Task RunTestsForTestShouldRunTestsInTheParentDomainsApartmentState MSTestSettings.PopulateSettings(_runContext, _mockMessageLogger.Object, null); await _testExecutionManager.RunTestsAsync(tests, _runContext, _frameworkHandle, new TestRunCancellationToken()); - Verify(DummyTestClassWithDoNotParallelizeMethods.ThreadApartmentStates.Count == 1); - Verify(Thread.CurrentThread.GetApartmentState() == DummyTestClassWithDoNotParallelizeMethods.ThreadApartmentStates.ToArray()[0]); + DummyTestClassWithDoNotParallelizeMethods.ThreadApartmentStates.Count.Should().Be(1); + DummyTestClassWithDoNotParallelizeMethods.ThreadApartmentStates.ToArray()[0].Should().Be(Thread.CurrentThread.GetApartmentState()); } finally { @@ -857,7 +857,7 @@ private void VerifyTcmProperties(IDictionary? tcmProperties, Tes { foreach (TestProperty property in _tcmKnownProperties) { - Verify(testCase.GetPropertyValue(property)!.Equals(tcmProperties![property.Id])); + testCase.GetPropertyValue(property)!.Equals(tcmProperties![property.Id]).Should().BeTrue(); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs index 28f5710903..990bc3ddb1 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodFilterTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -20,37 +22,37 @@ public class TestMethodFilterTests : TestContainer public void PropertyProviderForFullyQualifiedNamePropertyReturnFullyQualifiedNameTestProperty() { TestProperty property = _testMethodFilter.PropertyProvider("FullyQualifiedName"); - Verify(property.Label == "FullyQualifiedName"); + property.Label.Should().Be("FullyQualifiedName"); } public void PropertyProviderForClassNamePropertyReturnClassNameTestProperty() { TestProperty property = _testMethodFilter.PropertyProvider("ClassName"); - Verify(property.Label == "ClassName"); + property.Label.Should().Be("ClassName"); } public void PropertyProviderForNamePropertyReturnNameTestProperty() { TestProperty property = _testMethodFilter.PropertyProvider("Name"); - Verify(property.Label == "Name"); + property.Label.Should().Be("Name"); } public void PropertyProviderForTestCategoryPropertyReturnTestCategoryTestProperty() { TestProperty property = _testMethodFilter.PropertyProvider("TestCategory"); - Verify(property.Label == "TestCategory"); + property.Label.Should().Be("TestCategory"); } public void PropertyProviderForPriorityPropertyReturnPriorityTestProperty() { TestProperty property = _testMethodFilter.PropertyProvider("Priority"); - Verify(property.Label == "Priority"); + property.Label.Should().Be("Priority"); } public void PropertyProviderValueForInvalidTestCaseReturnsNull() { object? result = _testMethodFilter.PropertyValueProvider(null, "Hello"); - Verify(result is null); + result.Should().BeNull(); } public void PropertyProviderValueForInvalidPropertyNameReturnsNull() @@ -60,7 +62,7 @@ public void PropertyProviderValueForInvalidPropertyNameReturnsNull() TestCase testCase = new(fullName, EngineConstants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); object? result = _testMethodFilter.PropertyValueProvider(testCase, null); - Verify(result is null); + result.Should().BeNull(); } public void PropertyProviderValueForSupportedPropertyNameWhichIsNotSetReturnsNull() @@ -70,7 +72,7 @@ public void PropertyProviderValueForSupportedPropertyNameWhichIsNotSetReturnsNul TestCase testCase = new(fullName, EngineConstants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); object? result = _testMethodFilter.PropertyValueProvider(testCase, "Priority"); - Verify(result is null); + result.Should().BeNull(); } public void PropertyProviderValueForValidTestAndSupportedPropertyNameReturnsValue() @@ -81,7 +83,7 @@ public void PropertyProviderValueForValidTestAndSupportedPropertyNameReturnsValu TestCase testCase = new(fullName, EngineConstants.ExecutorUri, Assembly.GetExecutingAssembly().FullName!); object? result = _testMethodFilter.PropertyValueProvider(testCase, "FullyQualifiedName"); - Verify(fullName.Equals(result)); + fullName.Equals(result).Should().BeTrue(); } public void GetFilterExpressionForNullRunContextReturnsNull() @@ -89,8 +91,8 @@ public void GetFilterExpressionForNullRunContextReturnsNull() TestableTestExecutionRecorder recorder = new(); ITestCaseFilterExpression? filterExpression = _testMethodFilter.GetFilterExpression(null, recorder, out bool filterHasError); - Verify(filterExpression is null); - Verify(!filterHasError); + filterExpression.Should().BeNull(); + filterHasError.Should().BeFalse(); } public void GetFilterExpressionForValidRunContextReturnsValidTestCaseFilterExpression() @@ -100,8 +102,8 @@ public void GetFilterExpressionForValidRunContextReturnsValidTestCaseFilterExpre TestableRunContext runContext = new(() => dummyFilterExpression); ITestCaseFilterExpression? filterExpression = _testMethodFilter.GetFilterExpression(runContext, recorder, out bool filterHasError); - Verify(dummyFilterExpression == filterExpression); - Verify(!filterHasError); + filterExpression.Should().Be(dummyFilterExpression); + filterHasError.Should().BeFalse(); } /// @@ -114,8 +116,8 @@ public void GetFilterExpressionForDiscoveryContextWithGetTestCaseFilterReturnsVa TestableDiscoveryContextWithGetTestCaseFilter discoveryContext = new(() => dummyFilterExpression); ITestCaseFilterExpression? filterExpression = _testMethodFilter.GetFilterExpression(discoveryContext, recorder, out bool filterHasError); - Verify(dummyFilterExpression == filterExpression); - Verify(!filterHasError); + filterExpression.Should().Be(dummyFilterExpression); + filterHasError.Should().BeFalse(); } /// @@ -127,8 +129,8 @@ public void GetFilterExpressionForDiscoveryContextWithoutGetTestCaseFilterReturn TestableDiscoveryContextWithoutGetTestCaseFilter discoveryContext = new(); ITestCaseFilterExpression? filterExpression = _testMethodFilter.GetFilterExpression(discoveryContext, recorder, out bool filterHasError); - Verify(filterExpression is null); - Verify(!filterHasError); + filterExpression.Should().BeNull(); + filterHasError.Should().BeFalse(); } public void GetFilterExpressionForRunContextGetTestCaseFilterThrowingExceptionReturnsNullWithFilterHasErrorTrue() @@ -137,10 +139,10 @@ public void GetFilterExpressionForRunContextGetTestCaseFilterThrowingExceptionRe TestableRunContext runContext = new(() => throw new TestPlatformFormatException("DummyException")); ITestCaseFilterExpression? filterExpression = _testMethodFilter.GetFilterExpression(runContext, recorder, out bool filterHasError); - Verify(filterExpression is null); - Verify(filterHasError); - Verify(recorder.Message == "DummyException"); - Verify(recorder.TestMessageLevel == TestMessageLevel.Error); + filterExpression.Should().BeNull(); + filterHasError.Should().BeTrue(); + recorder.Message.Should().Be("DummyException"); + recorder.TestMessageLevel.Should().Be(TestMessageLevel.Error); } /// @@ -152,10 +154,10 @@ public void GetFilterExpressionForDiscoveryContextWithGetTestCaseFilterThrowingE TestableDiscoveryContextWithGetTestCaseFilter discoveryContext = new(() => throw new TestPlatformFormatException("DummyException")); ITestCaseFilterExpression? filterExpression = _testMethodFilter.GetFilterExpression(discoveryContext, recorder, out bool filterHasError); - Verify(filterExpression is null); - Verify(filterHasError); - Verify(recorder.Message == "DummyException"); - Verify(recorder.TestMessageLevel == TestMessageLevel.Error); + filterExpression.Should().BeNull(); + filterHasError.Should().BeTrue(); + recorder.Message.Should().Be("DummyException"); + recorder.TestMessageLevel.Should().Be(TestMessageLevel.Error); } [DummyTestClass] diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs index 87a67534be..03dfee9987 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; @@ -72,10 +74,10 @@ public void SetArgumentsShouldSetArgumentsNeededForCurrentTestRun() object[] arguments = [10, 20, 30]; _testMethodInfo.SetArguments(arguments); - Verify(_testMethodInfo.Arguments!.Length == 3); - Verify((int?)_testMethodInfo.Arguments[0] == 10); - Verify((int?)_testMethodInfo.Arguments[1] == 20); - Verify((int?)_testMethodInfo.Arguments[2] == 30); + _testMethodInfo.Arguments!.Length.Should().Be(3); + ((int?)_testMethodInfo.Arguments[0]).Should().Be(10); + ((int?)_testMethodInfo.Arguments[1]).Should().Be(20); + ((int?)_testMethodInfo.Arguments[2]).Should().Be(30); } #region TestMethod invoke scenarios @@ -94,8 +96,8 @@ public async Task TestMethodInfoInvokeShouldWaitForAsyncTestMethodsToComplete() TestResult result = await method.InvokeAsync(null); - Verify(methodCalled); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + methodCalled.Should().BeTrue(); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeAsyncShouldHandleThrowAssertInconclusive() @@ -114,7 +116,7 @@ public async Task TestMethodInfoInvokeAsyncShouldHandleThrowAssertInconclusive() TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); } public async Task TestMethodInfoInvokeAsyncShouldHandleAssertInconclusive() @@ -133,7 +135,7 @@ public async Task TestMethodInfoInvokeAsyncShouldHandleAssertInconclusive() TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); } public async Task TestMethodInfoInvokeShouldHandleThrowAssertInconclusive() @@ -152,7 +154,7 @@ public async Task TestMethodInfoInvokeShouldHandleThrowAssertInconclusive() TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); } public async Task TestMethodInfoInvokeShouldHandleAssertInconclusive() @@ -171,7 +173,7 @@ public async Task TestMethodInfoInvokeShouldHandleAssertInconclusive() TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); } public async Task TestMethodInfoInvokeShouldReportTestContextMessages() @@ -189,7 +191,7 @@ public async Task TestMethodInfoInvokeShouldReportTestContextMessages() TestResult result = await method.InvokeAsync(null); - Verify(result.TestContextMessages!.Contains("TestContext")); + result.TestContextMessages!.Contains("TestContext").Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldClearTestContextMessagesAfterReporting() @@ -207,13 +209,13 @@ public async Task TestMethodInfoInvokeShouldClearTestContextMessagesAfterReporti TestResult result = await method.InvokeAsync(null); - Verify(result.TestContextMessages!.Contains("TestContext")); + result.TestContextMessages!.Contains("TestContext").Should().BeTrue(); DummyTestClass.TestMethodBody = o => _testContextImplementation.WriteLine("SeaShore"); result = await method.InvokeAsync(null); - Verify(result.TestContextMessages!.Contains("SeaShore")); + result.TestContextMessages!.Contains("SeaShore").Should().BeTrue(); } public async Task Invoke_WhenTestMethodThrowsMissingMethodException_TestOutcomeIsFailedAndExceptionIsPreserved() @@ -240,9 +242,9 @@ public async Task Invoke_WhenTestMethodThrowsMissingMethodException_TestOutcomeI TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); - Verify(result.TestFailureException is TestFailedException); - Verify(result.TestFailureException.InnerException is MissingMethodException); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + result.TestFailureException.Should().BeOfType(); + result.TestFailureException.InnerException.Should().BeOfType(); } #endregion @@ -257,8 +259,8 @@ public async Task TestMethodInfoInvokeShouldCreateNewInstanceOfTestClassOnEveryC TestResult result = await _testMethodInfo.InvokeAsync(null); await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); - Verify(ctorCallCount == 2); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + ctorCallCount.Should().Be(2); } public async Task TestMethodInfoInvokeShouldMarkOutcomeFailedIfTestClassConstructorThrows() @@ -267,7 +269,7 @@ public async Task TestMethodInfoInvokeShouldMarkOutcomeFailedIfTestClassConstruc TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrows() @@ -281,7 +283,7 @@ public async Task TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructo Resource.UTA_InstanceCreationError, typeof(DummyTestClass).FullName, "System.NotImplementedException: dummyExceptionMessage"); - Verify(errorMessage == result.TestFailureException!.Message); + result.TestFailureException!.Message.Should().Be(errorMessage); } public async Task TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructorThrowsWithoutInnerException() @@ -301,8 +303,8 @@ public async Task TestMethodInfoInvokeShouldSetErrorMessageIfTestClassConstructo typeof(DummyTestClassWithParameterizedCtor).FullName, "System.Reflection.TargetParameterCountException: Parameter count mismatch."); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); - Verify(errorMessage == result.TestFailureException!.Message); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + result.TestFailureException!.Message.Should().Be(errorMessage); } public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstructorThrows() @@ -311,11 +313,10 @@ public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassC var exception = (await _testMethodInfo.InvokeAsync(null)).TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(exception.StackTraceInformation is not null); - Verify( - exception.StackTraceInformation.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); + exception.Should().NotBeNull(); + exception.StackTraceInformation.Should().NotBeNull(); + exception.StackTraceInformation.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal).Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstructorThrowsWithoutInnerException() @@ -330,13 +331,12 @@ public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassC var exception = (await method.InvokeAsync(null)).TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(exception.StackTraceInformation is not null); + exception.Should().NotBeNull(); + exception.StackTraceInformation.Should().NotBeNull(); // NOTE: On net8.0 and later, the first frame is System.Reflection.MethodBaseInvoker.ThrowTargetParameterCountException() // So, we do a consistent Contains check to check that the stack trace is there. - Verify( - exception.StackTraceInformation.ErrorStackTrace.Contains( - " at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)", StringComparison.Ordinal)); + exception.StackTraceInformation.ErrorStackTrace.Contains( + " at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)", StringComparison.Ordinal).Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttachments() @@ -354,7 +354,7 @@ public async Task TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttach }; TestResult result = await method.InvokeAsync(null); - Verify(result.ResultFiles!.Contains("C:\\temp.txt")); + result.ResultFiles!.Contains("C:\\temp.txt").Should().BeTrue(); } public async Task TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContext_SetsItToTestContext() @@ -369,7 +369,7 @@ public async Task TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContext_ TestResult result = await testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } #endregion @@ -391,7 +391,7 @@ public async Task TestMethodInfoInvokeShouldNotThrowIfTestContextIsNotPresent() async Task RunMethod() => result = await method.InvokeAsync(null); await RunMethod(); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeShouldNotThrowIfTestContextDoesNotHaveASetter() @@ -409,7 +409,7 @@ public async Task TestMethodInfoInvokeShouldNotThrowIfTestContextDoesNotHaveASet async Task RunMethod() => result = await method.InvokeAsync(null); await RunMethod(); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeShouldSetTestContextForTestClassInstance() @@ -419,7 +419,7 @@ public async Task TestMethodInfoInvokeShouldSetTestContextForTestClassInstance() await _testMethodInfo.InvokeAsync(null); - Verify(_testContextImplementation.Equals(testContext)); + _testContextImplementation.Equals(testContext).Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldMarkOutcomeFailedIfSetTestContextThrows() @@ -428,7 +428,7 @@ public async Task TestMethodInfoInvokeShouldMarkOutcomeFailedIfSetTestContextThr TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task TestMethodInfoInvokeShouldSetErrorMessageIfSetTestContextThrows() @@ -442,8 +442,8 @@ public async Task TestMethodInfoInvokeShouldSetErrorMessageIfSetTestContextThrow Resource.UTA_TestContextSetError, typeof(DummyTestClass).FullName, "System.NotImplementedException: dummyExceptionMessage"); - Verify(exception is not null); - Verify(errorMessage == exception?.Message); + exception.Should().NotBeNull(); + exception?.Message.Should().Be(errorMessage); } public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfSetTestContextThrows() @@ -452,11 +452,10 @@ public async Task TestMethodInfoInvokeShouldSetStackTraceInformationIfSetTestCon var exception = (await _testMethodInfo.InvokeAsync(null)).TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(exception.StackTraceInformation is not null); - Verify( - exception.StackTraceInformation.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); + exception.Should().NotBeNull(); + exception.StackTraceInformation.Should().NotBeNull(); + exception.StackTraceInformation.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal).Should().BeTrue(); } public async Task TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContextAndTestContextProperty_InitializeBothTestContexts() @@ -473,8 +472,8 @@ public async Task TestMethodInfoInvoke_WhenCtorHasOneParameterOfTypeTestContextA TestResult result = await testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); - Verify(_testContextImplementation.Equals(testContext)); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + _testContextImplementation.Equals(testContext).Should().BeTrue(); } #endregion @@ -489,8 +488,8 @@ public async Task TestMethodInfoInvokeShouldCallTestInitialize() TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(testInitializeCalled); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + testInitializeCalled.Should().BeTrue(); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeShouldCallAsyncTestInitializeAndWaitForCompletion() @@ -501,8 +500,8 @@ public async Task TestMethodInfoInvokeShouldCallAsyncTestInitializeAndWaitForCom TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(testInitializeCalled); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + testInitializeCalled.Should().BeTrue(); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeShouldCallTestInitializeOfAllBaseClasses() @@ -523,8 +522,8 @@ public async Task TestMethodInfoInvokeShouldCallTestInitializeOfAllBaseClasses() "baseTestInitializeCalled2", "classTestInitializeCalled", }; - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); - Verify(expectedCallOrder.SequenceEqual(callOrder)); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + expectedCallOrder.SequenceEqual(callOrder).Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldNotThrowIfTestInitializeIsNull() @@ -533,7 +532,7 @@ public async Task TestMethodInfoInvokeShouldNotThrowIfTestInitializeIsNull() TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeShouldNotThrowIfTestInitializeForBaseClassIsNull() @@ -542,7 +541,7 @@ public async Task TestMethodInfoInvokeShouldNotThrowIfTestInitializeForBaseClass TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeWhenTestThrowsReturnsExpectedResult() @@ -567,17 +566,17 @@ public async Task TestMethodInfoInvokeWhenTestThrowsReturnsExpectedResult() TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(errorMessage == exception.Message); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception.InnerException!.GetType() == typeof(ArgumentException)); - Verify(exception.InnerException.InnerException!.GetType() == typeof(InvalidOperationException)); + exception.Should().NotBeNull(); + exception.Message.Should().Be(errorMessage); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.InnerException.Should().BeOfType(); + exception.InnerException.InnerException.Should().BeOfType(); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal).Should().BeTrue(); #endif } @@ -596,13 +595,13 @@ public async Task TestInitialize_WhenTestReturnsTaskFromException_DisplayProperE TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception.InnerException!.GetType() == typeof(Exception)); - Verify(exception.InnerException.InnerException!.GetType() == typeof(InvalidOperationException)); + exception.Should().NotBeNull(); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.InnerException.Should().BeOfType(); + exception.InnerException.InnerException.Should().BeOfType(); string expectedErrorMessage = string.Format( CultureInfo.InvariantCulture, @@ -610,8 +609,8 @@ public async Task TestInitialize_WhenTestReturnsTaskFromException_DisplayProperE typeof(DummyTestClass).FullName, _testClassInfo.TestInitializeMethod!.Name, "System.Exception: Outer ---> System.InvalidOperationException: Inner"); - Verify(expectedErrorMessage == exception.Message); - Verify(exception.StackTraceInformation is not null); + exception.Message.Should().Be(expectedErrorMessage); + exception.StackTraceInformation.Should().NotBeNull(); } public async Task TestMethodInfoInvokeWhenTestThrowsAssertFailReturnsExpectedResult() @@ -636,16 +635,16 @@ public async Task TestMethodInfoInvokeWhenTestThrowsAssertFailReturnsExpectedRes TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(errorMessage == exception.Message); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception.InnerException!.GetType() == typeof(AssertFailedException)); + exception.Should().NotBeNull(); + exception.Message.Should().Be(errorMessage); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.InnerException.Should().BeOfType(); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.Contains( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.Contains( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal).Should().BeTrue(); #endif } @@ -671,16 +670,16 @@ public async Task TestMethodInfoInvokeWhenTestThrowsAssertInconclusiveReturnsExp TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. - Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(errorMessage == exception.Message); - Verify(exception.Outcome == UTF.UnitTestOutcome.Inconclusive); - Verify(exception.InnerException!.GetType() == typeof(AssertInconclusiveException)); + exception.Should().NotBeNull(); + exception.Message.Should().Be(errorMessage); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); + exception.InnerException.Should().BeOfType(); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.Contains( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.Contains( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal).Should().BeTrue(); #endif } @@ -703,13 +702,13 @@ public async Task TestCleanup_WhenTestReturnsTaskFromException_DisplayProperExce TestResult result = await testMethodInfo.InvokeAsync(null); // Assert. - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception.InnerException!.GetType() == typeof(Exception)); - Verify(exception.InnerException.InnerException!.GetType() == typeof(InvalidOperationException)); + exception.Should().NotBeNull(); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.InnerException.Should().BeOfType(); + exception.InnerException.InnerException.Should().BeOfType(); string errorMessage = string.Format( CultureInfo.InvariantCulture, @@ -717,7 +716,7 @@ public async Task TestCleanup_WhenTestReturnsTaskFromException_DisplayProperExce typeof(DummyTestClass).FullName, _testClassInfo.TestCleanupMethod!.Name, "System.Exception: Outer ---> System.InvalidOperationException: Inner"); - Verify(errorMessage == exception.Message); + exception.Message.Should().Be(errorMessage); if (exception.StackTraceInformation is null) { @@ -733,8 +732,8 @@ public async Task TestMethodInfoInvokeShouldCallTestCleanup() TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); - Verify(cleanupMethodCalled); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + cleanupMethodCalled.Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldCallAsyncTestCleanup() @@ -745,8 +744,8 @@ public async Task TestMethodInfoInvokeShouldCallAsyncTestCleanup() TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); - Verify(cleanupMethodCalled); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + cleanupMethodCalled.Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldNotThrowIfTestCleanupMethodIsNull() @@ -755,7 +754,7 @@ public async Task TestMethodInfoInvokeShouldNotThrowIfTestCleanupMethodIsNull() TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClasses() @@ -775,8 +774,8 @@ public async Task TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClasses() "baseTestCleanupCalled1", "baseTestCleanupCalled2", }; - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); - Verify(expectedCallOrder.SequenceEqual(callOrder)); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + expectedCallOrder.SequenceEqual(callOrder).Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClassesAlways() @@ -801,8 +800,8 @@ public async Task TestMethodInfoInvokeShouldCallTestCleanupForBaseTestClassesAlw "baseTestCleanupCalled5", }; - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); - Verify(expectedCallOrder.SequenceEqual(callOrder)); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + expectedCallOrder.SequenceEqual(callOrder).Should().BeTrue(); } public async Task TestMethodInfoInvokeWhenTestCleanupThrowsReturnsExpectedResult() @@ -819,18 +818,18 @@ public async Task TestMethodInfoInvokeWhenTestCleanupThrowsReturnsExpectedResult TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(expectedErrorMessage == exception.Message); - Verify(exception.InnerException!.GetType() == typeof(ArgumentException)); - Verify(exception.InnerException.InnerException!.GetType() == typeof(InvalidOperationException)); + exception.Should().NotBeNull(); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be(expectedErrorMessage); + exception.InnerException.Should().BeOfType(); + exception.InnerException.InnerException.Should().BeOfType(); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.StartsWith( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.StartsWith( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal).Should().BeTrue(); #endif } @@ -848,16 +847,16 @@ public async Task TestMethodInfoInvokeWhenTestCleanupThrowsAssertInconclusiveRet TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(exception.Outcome == UTF.UnitTestOutcome.Inconclusive); - Verify(expectedErrorMessage == exception.Message); - Verify(exception.InnerException!.GetType() == typeof(AssertInconclusiveException)); + exception.Should().NotBeNull(); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); + exception.Message.Should().Be(expectedErrorMessage); + exception.InnerException.Should().BeOfType(); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.Contains( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.Contains( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal).Should().BeTrue(); #endif } @@ -875,16 +874,16 @@ public async Task TestMethodInfoInvokeWhenTestCleanupThrowsAssertFailedReturnsEx TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); var exception = result.TestFailureException as TestFailedException; - Verify(exception is not null); - Verify(exception.Outcome == UTF.UnitTestOutcome.Failed); - Verify(expectedErrorMessage == exception.Message); - Verify(exception.InnerException!.GetType() == typeof(AssertFailedException)); + exception.Should().NotBeNull(); + exception.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Message.Should().Be(expectedErrorMessage); + exception.InnerException.Should().BeOfType(); #if DEBUG - Verify(exception.StackTraceInformation!.ErrorStackTrace.Contains( - " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal)); + exception.StackTraceInformation!.ErrorStackTrace.Contains( + " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__", StringComparison.Ordinal).Should().BeTrue(); #endif } @@ -909,10 +908,10 @@ public async Task TestMethodInfoInvokeShouldAppendErrorMessagesIfBothTestMethodA _testClassInfo.TestCleanupMethod!.Name, "System.NotImplementedException: dummyErrorMessage"); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception is not null); - Verify(exception.InnerExceptions[0].Message.Contains(errorMessage)); - Verify(exception.InnerExceptions[1].Message.Contains(cleanupError)); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Should().NotBeNull(); + exception.InnerExceptions[0].Message.Contains(errorMessage).Should().BeTrue(); + exception.InnerExceptions[1].Message.Contains(cleanupError).Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldAppendStackTraceInformationIfBothTestMethodAndTestCleanupThrows() @@ -924,11 +923,11 @@ public async Task TestMethodInfoInvokeShouldAppendStackTraceInformationIfBothTes TestResult result = await _testMethodInfo.InvokeAsync(null); var exception = result.TestFailureException as AggregateException; - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); - Verify(exception is not null); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exception.Should().NotBeNull(); #if DEBUG - Verify(((TestFailedException)exception.InnerExceptions[0]).StackTraceInformation!.ErrorStackTrace.Contains("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.DummyTestClass.DummyTestMethod()")); - Verify(((TestFailedException)exception.InnerExceptions[1]).StackTraceInformation!.ErrorStackTrace.Contains("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.DummyTestClass.DummyTestCleanupMethod()")); + ((TestFailedException)exception.InnerExceptions[0]).StackTraceInformation!.ErrorStackTrace.Contains("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.DummyTestClass.DummyTestMethod()").Should().BeTrue(); + ((TestFailedException)exception.InnerExceptions[1]).StackTraceInformation!.ErrorStackTrace.Contains("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.DummyTestClass.DummyTestCleanupMethod()").Should().BeTrue(); #endif } @@ -940,20 +939,20 @@ public async Task TestMethodInfoInvokeShouldSetOutcomeAsInconclusiveIfTestCleanu TestResult result = await _testMethodInfo.InvokeAsync(null); var exception = result.TestFailureException as TestFailedException; - Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); - Verify(exception is not null); - Verify(exception.Message.Contains("Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException")); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); + exception.Should().NotBeNull(); + exception.Message.Contains("Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException").Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldSetMoreImportantOutcomeIfTestCleanupIsInconclusiveButTestMethodFails() { DummyTestClass.TestCleanupMethodBody = classInstance => throw new AssertInconclusiveException(); - DummyTestClass.TestMethodBody = classInstance => Fail(); + DummyTestClass.TestMethodBody = classInstance => throw new Exception(); _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod("DummyTestCleanupMethod")!; TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task TestMethodInfoInvokeShouldCallDisposeForDisposableTestClass() @@ -970,7 +969,7 @@ public async Task TestMethodInfoInvokeShouldCallDisposeForDisposableTestClass() await method.InvokeAsync(null); - Verify(disposeCalled); + disposeCalled.Should().BeTrue(); } #if NET6_0_OR_GREATER @@ -991,7 +990,7 @@ public async Task TestMethodInfoInvoke_WhenTestClassIsAsyncDisposable_ShouldDisp await method.InvokeAsync(null); // Assert - Verify(asyncDisposeCalled); + asyncDisposeCalled.Should().BeTrue(); } public async Task TestMethodInfoInvoke_WhenTestClassIsDisposableAndAsyncDisposable_ShouldCallAsyncDisposeThenDispose() @@ -1016,8 +1015,8 @@ public async Task TestMethodInfoInvoke_WhenTestClassIsDisposableAndAsyncDisposab await method.InvokeAsync(null); // Assert - Verify(disposeCalledOrder == 2); - Verify(disposeAsyncCalledOrder == 1); + disposeCalledOrder.Should().Be(2); + disposeAsyncCalledOrder.Should().Be(1); } #endif @@ -1039,7 +1038,7 @@ public async Task TestMethodInfoInvokeShouldCallDisposeForDisposableTestClassIfT await method.InvokeAsync(null); - Verify(disposeCalled); + disposeCalled.Should().BeTrue(); } public async Task TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestMethodThrows() @@ -1051,8 +1050,8 @@ public async Task TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestMethodThrow TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(testCleanupMethodCalled); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + testCleanupMethodCalled.Should().BeTrue(); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestInitializeMethodThrows() @@ -1065,8 +1064,8 @@ public async Task TestMethodInfoInvokeShouldCallTestCleanupEvenIfTestInitializeM TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(testCleanupMethodCalled); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + testCleanupMethodCalled.Should().BeTrue(); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task TestMethodInfoInvokeShouldCallTestCleanupIfTestClassInstanceIsNotNull() @@ -1079,8 +1078,8 @@ public async Task TestMethodInfoInvokeShouldCallTestCleanupIfTestClassInstanceIs TestResult result = await _testMethodInfo.InvokeAsync(null); - Verify(!testCleanupMethodCalled); - Verify(result.Outcome == UTF.UnitTestOutcome.Failed); + testCleanupMethodCalled.Should().BeFalse(); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task TestMethodInfoInvokeShouldNotCallTestCleanupIfClassSetContextThrows() @@ -1092,7 +1091,7 @@ public async Task TestMethodInfoInvokeShouldNotCallTestCleanupIfClassSetContextT await _testMethodInfo.InvokeAsync(null); - Verify(!testCleanupCalled); + testCleanupCalled.Should().BeFalse(); } public async Task TestMethodInfoInvokeShouldSetResultAsInconclusiveWhenExceptionIsAssertInconclusiveException() @@ -1104,9 +1103,9 @@ public async Task TestMethodInfoInvokeShouldSetResultAsInconclusiveWhenException Executor = _testMethodAttribute, }; TestResult result = await testMethodInfo.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Inconclusive); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); string message = "Exception of type 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException' was thrown."; - Verify(message == result.TestFailureException!.Message); + result.TestFailureException!.Message.Should().Be(message); } public async Task TestMethodInfoInvokeShouldSetTestOutcomeBeforeTestCleanup() @@ -1129,7 +1128,7 @@ public async Task TestMethodInfoInvokeShouldSetTestOutcomeBeforeTestCleanup() TestResult result = await testMethodInfo.InvokeAsync(null); - Verify(testOutcome == UTF.UnitTestOutcome.Inconclusive); + testOutcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); } #endregion @@ -1158,8 +1157,8 @@ public async Task TestMethodInfoInvokeShouldInitializeClassInstanceTestInitializ "testMethodInfo", "testCleanup", }; - Verify(expectedCallOrder.SequenceEqual(callOrder)); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + expectedCallOrder.SequenceEqual(callOrder).Should().BeTrue(); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } #endregion @@ -1186,8 +1185,8 @@ await RunWithTestablePlatformService(testablePlatformServiceProvider, async () = TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); - Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' timed out after 1ms", StringComparison.Ordinal)); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Timeout); + result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' timed out after 1ms", StringComparison.Ordinal).Should().BeTrue(); }); } @@ -1200,7 +1199,7 @@ public async Task TestMethodInfoInvokeShouldReturnTestPassedOnCompletionWithinTi Executor = _testMethodAttribute, }; TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Passed); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task TestMethodInfoInvokeShouldCancelTokenSourceOnTimeout() @@ -1221,9 +1220,9 @@ await RunWithTestablePlatformService(testablePlatformServiceProvider, async () = }; TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); - Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' timed out after 1ms", StringComparison.Ordinal)); - Verify(_testContextImplementation.CancellationTokenSource.IsCancellationRequested, "Not canceled.."); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Timeout); + result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' timed out after 1ms", StringComparison.Ordinal).Should().BeTrue(); + _testContextImplementation.CancellationTokenSource.IsCancellationRequested.Should().BeTrue("Not canceled.."); }); } @@ -1255,9 +1254,9 @@ await RunWithTestablePlatformService(testablePlatformServiceProvider, async () = }; TestResult result = await method.InvokeAsync(null); - Verify(result.Outcome == UTF.UnitTestOutcome.Timeout); - Verify(result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' was canceled", StringComparison.Ordinal)); - Verify(_testContextImplementation.CancellationTokenSource.IsCancellationRequested, "Not canceled.."); + result.Outcome.Should().Be(UTF.UnitTestOutcome.Timeout); + result.TestFailureException!.Message.Equals("Test 'DummyTestMethod' was canceled", StringComparison.Ordinal).Should().BeTrue(); + _testContextImplementation.CancellationTokenSource.IsCancellationRequested.Should().BeTrue("Not canceled.."); }); } @@ -1280,8 +1279,8 @@ public void ResolveArgumentsShouldReturnProvidedArgumentsWhenTooFewParameters() object[] expectedArguments = ["RequiredStr1"]; object?[] resolvedArguments = method.ResolveArguments(arguments); - Verify(resolvedArguments.Length == 1); - Verify(expectedArguments.SequenceEqual(resolvedArguments)); + resolvedArguments.Length.Should().Be(1); + expectedArguments.SequenceEqual(resolvedArguments).Should().BeTrue(); } public void ResolveArgumentsShouldReturnProvidedArgumentsWhenTooManyParameters() @@ -1301,8 +1300,8 @@ public void ResolveArgumentsShouldReturnProvidedArgumentsWhenTooManyParameters() object?[] expectedArguments = ["RequiredStr1", "RequiredStr2", "ExtraStr3"]; object?[] resolvedArguments = method.ResolveArguments(arguments); - Verify(resolvedArguments.Length == 3); - Verify(expectedArguments.SequenceEqual(resolvedArguments)); + resolvedArguments.Length.Should().Be(3); + expectedArguments.SequenceEqual(resolvedArguments).Should().BeTrue(); } public void ResolveArgumentsShouldReturnAdditionalOptionalParametersWithNoneProvided() @@ -1322,8 +1321,8 @@ public void ResolveArgumentsShouldReturnAdditionalOptionalParametersWithNoneProv object?[] expectedArguments = ["RequiredStr1", null, null]; object?[] resolvedArguments = method.ResolveArguments(arguments); - Verify(resolvedArguments.Length == 3); - Verify(expectedArguments.SequenceEqual(resolvedArguments)); + resolvedArguments.Length.Should().Be(3); + expectedArguments.SequenceEqual(resolvedArguments).Should().BeTrue(); } public void ResolveArgumentsShouldReturnAdditionalOptionalParametersWithSomeProvided() @@ -1343,8 +1342,8 @@ public void ResolveArgumentsShouldReturnAdditionalOptionalParametersWithSomeProv object?[] expectedArguments = ["RequiredStr1", "OptionalStr1", null]; object?[] resolvedArguments = method.ResolveArguments(arguments); - Verify(resolvedArguments.Length == 3); - Verify(expectedArguments.SequenceEqual(resolvedArguments)); + resolvedArguments.Length.Should().Be(3); + expectedArguments.SequenceEqual(resolvedArguments).Should().BeTrue(); } public void ResolveArgumentsShouldReturnEmptyParamsWithNoneProvided() @@ -1364,10 +1363,10 @@ public void ResolveArgumentsShouldReturnEmptyParamsWithNoneProvided() object[] expectedArguments = [1, Array.Empty()]; object?[] resolvedArguments = method.ResolveArguments(arguments); - Verify(resolvedArguments.Length == 2); - Verify(expectedArguments[0].Equals(resolvedArguments[0])); - Verify(resolvedArguments[1]!.GetType() == typeof(string[])); - Verify(((string[])expectedArguments[1]).SequenceEqual((string[])resolvedArguments[1]!)); + resolvedArguments.Length.Should().Be(2); + expectedArguments[0].Equals(resolvedArguments[0]).Should().BeTrue(); + resolvedArguments[1].Should().BeOfType(); + ((string[])expectedArguments[1]).SequenceEqual((string[])resolvedArguments[1]!).Should().BeTrue(); } public void ResolveArgumentsShouldReturnPopulatedParamsWithAllProvided() @@ -1387,10 +1386,10 @@ public void ResolveArgumentsShouldReturnPopulatedParamsWithAllProvided() object[] expectedArguments = [1, new string[] { "str1", "str2", "str3" }]; object?[] resolvedArguments = method.ResolveArguments(arguments); - Verify(resolvedArguments.Length == 2); - Verify(expectedArguments[0].Equals(resolvedArguments[0])); - Verify(resolvedArguments[1]!.GetType() == typeof(string[])); - Verify(((string[])expectedArguments[1]).SequenceEqual((string[])resolvedArguments[1]!)); + resolvedArguments.Length.Should().Be(2); + expectedArguments[0].Equals(resolvedArguments[0]).Should().BeTrue(); + resolvedArguments[1].Should().BeOfType(); + ((string[])expectedArguments[1]).SequenceEqual((string[])resolvedArguments[1]!).Should().BeTrue(); } #region helper methods @@ -1428,7 +1427,7 @@ public class DummyTestClass : DummyTestClassBase public DummyTestClass() => TestConstructorMethodBody(); - public DummyTestClass(TestContext tc) => Verify(tc is not null); + public DummyTestClass(TestContext tc) => (tc is not null).Should().BeTrue(); public static Action TestConstructorMethodBody { get; set; } = null!; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs index d9ae2c111f..07737ac300 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodRunnerTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; @@ -83,13 +85,13 @@ public async Task ExecuteForTestThrowingExceptionShouldReturnTestResultWithFaile var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); TestResult[] results = await testMethodRunner.ExecuteAsync(string.Empty, string.Empty, string.Empty, string.Empty); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Failed); - Verify(results[0].ExceptionMessage!.StartsWith( + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + results[0].ExceptionMessage!.StartsWith( """ An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute 'Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute'. System.Exception: DummyException """, - StringComparison.Ordinal)); + StringComparison.Ordinal).Should().BeTrue(); } public async Task ExecuteForPassingTestShouldReturnTestResultWithPassedOutcome() @@ -98,7 +100,7 @@ public async Task ExecuteForPassingTestShouldReturnTestResultWithPassedOutcome() var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); TestResult[] results = await testMethodRunner.ExecuteAsync(string.Empty, string.Empty, string.Empty, string.Empty); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Passed); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task ExecuteShouldNotFillInDebugAndTraceLogsIfDebugTraceDisabled() @@ -107,7 +109,7 @@ public async Task ExecuteShouldNotFillInDebugAndTraceLogsIfDebugTraceDisabled() var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); TestResult[] results = await testMethodRunner.ExecuteAsync(string.Empty, string.Empty, string.Empty, string.Empty); - Verify(results[0].DebugTrace == string.Empty); + results[0].DebugTrace.Should().Be(string.Empty); } public async Task ExecuteShouldNotFillInDebugAndTraceLogsFromRunningTestMethod() @@ -128,7 +130,7 @@ public async Task ExecuteShouldNotFillInDebugAndTraceLogsFromRunningTestMethod() TestResult[] results = await testMethodRunner.ExecuteAsync(string.Empty, string.Empty, string.Empty, string.Empty); - Verify(results[0].DebugTrace == string.Empty); + results[0].DebugTrace.Should().Be(string.Empty); } public async Task RunTestMethodForTestThrowingExceptionShouldReturnTestResultWithFailedOutcome() @@ -137,13 +139,13 @@ public async Task RunTestMethodForTestThrowingExceptionShouldReturnTestResultWit var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); TestResult[] results = await testMethodRunner.RunTestMethodAsync(); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Failed); - Verify(results[0].ExceptionMessage!.StartsWith( + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + results[0].ExceptionMessage!.StartsWith( """ An unhandled exception was thrown by the 'Execute' method. Please report this error to the author of the attribute 'Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute'. System.Exception: Dummy Exception """, - StringComparison.Ordinal)); + StringComparison.Ordinal).Should().BeTrue(); } private sealed class TestMethodWithFailingAndPassingResultsAttribute : TestMethodAttribute @@ -164,10 +166,10 @@ public async Task RunTestMethodForMultipleResultsReturnMultipleResults() var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); TestResult[] results = await testMethodRunner.ExecuteAsync(string.Empty, string.Empty, string.Empty, string.Empty); - Verify(results.Length == 2); + results.Length.Should().Be(2); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Passed); - Verify(results[1].Outcome == UTF.UnitTestOutcome.Failed); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + results[1].Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task RunTestMethodForPassingTestThrowingExceptionShouldReturnTestResultWithPassedOutcome() @@ -176,7 +178,7 @@ public async Task RunTestMethodForPassingTestThrowingExceptionShouldReturnTestRe var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); TestResult[] results = await testMethodRunner.ExecuteAsync(string.Empty, string.Empty, string.Empty, string.Empty); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Passed); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task RunTestMethodForFailingTestThrowingExceptionShouldReturnTestResultWithFailedOutcome() @@ -185,7 +187,7 @@ public async Task RunTestMethodForFailingTestThrowingExceptionShouldReturnTestRe var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); TestResult[] results = await testMethodRunner.ExecuteAsync(string.Empty, string.Empty, string.Empty, string.Empty); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Failed); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task RunTestMethodShouldGiveTestResultAsPassedWhenTestMethodPasses() @@ -196,7 +198,7 @@ public async Task RunTestMethodShouldGiveTestResultAsPassedWhenTestMethodPasses( TestResult[] results = await testMethodRunner.RunTestMethodAsync(); // Since data is not provided, tests run normally giving passed as outcome. - Verify(results[0].Outcome == UTF.UnitTestOutcome.Passed); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task RunTestMethodShouldGiveTestResultAsFailedWhenTestMethodFails() @@ -207,7 +209,7 @@ public async Task RunTestMethodShouldGiveTestResultAsFailedWhenTestMethodFails() TestResult[] results = await testMethodRunner.RunTestMethodAsync(); // Since data is not provided, tests run normally giving passed as outcome. - Verify(results[0].Outcome == UTF.UnitTestOutcome.Failed); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Failed); } public async Task RunTestMethodShouldRunDataDrivenTestsWhenDataIsProvidedUsingDataSourceAttribute() @@ -227,9 +229,9 @@ public async Task RunTestMethodShouldRunDataDrivenTestsWhenDataIsProvidedUsingDa TestResult[] results = await testMethodRunner.RunTestMethodAsync(); // check for outcome - Verify(results[0].Outcome == UTF.UnitTestOutcome.Passed); - Verify(results[1].Outcome == UTF.UnitTestOutcome.Passed); - Verify(results[2].Outcome == UTF.UnitTestOutcome.Passed); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + results[1].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + results[2].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task RunTestMethodShouldRunDataDrivenTestsWhenDataIsProvidedUsingDataRowAttribute() @@ -254,7 +256,7 @@ public async Task RunTestMethodShouldRunDataDrivenTestsWhenDataIsProvidedUsingDa _testablePlatformServiceProvider.MockReflectionOperations.Setup(ro => ro.GetCustomAttributes(_methodInfo, It.IsAny())).Returns(attributes); TestResult[] results = await testMethodRunner.RunTestMethodAsync(); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Inconclusive); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); } public async Task RunTestMethodShouldSetDataRowIndexForDataDrivenTestsWhenDataIsProvidedUsingDataSourceAttribute() @@ -273,9 +275,9 @@ public async Task RunTestMethodShouldSetDataRowIndexForDataDrivenTestsWhenDataIs TestResult[] results = await testMethodRunner.RunTestMethodAsync(); // check for datarowIndex - Verify(results[0].DatarowIndex == 0); - Verify(results[1].DatarowIndex == 1); - Verify(results[2].DatarowIndex == 2); + results[0].DatarowIndex.Should().Be(0); + results[1].DatarowIndex.Should().Be(1); + results[2].DatarowIndex.Should().Be(2); } public async Task RunTestMethodShouldRunOnlyDataSourceTestsWhenBothDataSourceAndDataRowAreProvided() @@ -300,9 +302,9 @@ public async Task RunTestMethodShouldRunOnlyDataSourceTestsWhenBothDataSourceAnd TestResult[] results = await testMethodRunner.RunTestMethodAsync(); // check for datarowIndex as only DataSource Tests are Run - Verify(results[0].DatarowIndex == 0); - Verify(results[1].DatarowIndex == 1); - Verify(results[2].DatarowIndex == 2); + results[0].DatarowIndex.Should().Be(0); + results[1].DatarowIndex.Should().Be(1); + results[2].DatarowIndex.Should().Be(2); } public async Task RunTestMethodShouldFillInDisplayNameWithDataRowDisplayNameIfProvidedForDataDrivenTests() @@ -326,8 +328,8 @@ public async Task RunTestMethodShouldFillInDisplayNameWithDataRowDisplayNameIfPr TestResult[] results = await testMethodRunner.RunTestMethodAsync(); - Verify(results.Length == 1); - Verify(results[0].DisplayName == "DataRowTestDisplayName"); + results.Length.Should().Be(1); + results[0].DisplayName.Should().Be("DataRowTestDisplayName"); } public async Task RunTestMethodShouldFillInDisplayNameWithDataRowArgumentsIfNoDisplayNameIsProvidedForDataDrivenTests() @@ -350,8 +352,8 @@ public async Task RunTestMethodShouldFillInDisplayNameWithDataRowArgumentsIfNoDi TestResult[] results = await testMethodRunner.RunTestMethodAsync(); - Verify(results.Length == 1); - Verify(results[0].DisplayName is "dummyTestName (2,\"DummyString\")" or "DummyTestMethod (2,DummyString)", $"Display name: {results[0].DisplayName}"); + results.Length.Should().Be(1); + results[0].DisplayName.Should().BeOneOf("dummyTestName (2,\"DummyString\")", "DummyTestMethod (2,DummyString)"); } public async Task RunTestMethodShouldSetResultFilesIfPresentForDataDrivenTests() @@ -375,8 +377,8 @@ public async Task RunTestMethodShouldSetResultFilesIfPresentForDataDrivenTests() var testMethodRunner = new TestMethodRunner(testMethodInfo, _testMethod, _testContextImplementation); TestResult[] results = await testMethodRunner.RunTestMethodAsync(); - Verify(results[0].ResultFiles!.Contains("C:\\temp.txt")); - Verify(results[1].ResultFiles!.Contains("C:\\temp.txt")); + results[0].ResultFiles!.Should().Contain("C:\\temp.txt"); + results[1].ResultFiles!.Should().Contain("C:\\temp.txt"); } public async Task RunTestMethodWithEmptyDataSourceShouldFailBecauseConsiderEmptyDataSourceAsInconclusiveIsFalse() @@ -415,12 +417,13 @@ private async Task RunTestMethodWithEmptyDataSourceShouldFailIfConsiderEmptyData if (considerEmptyAsInconclusive) { TestResult[] results = await testMethodRunner.RunTestMethodAsync(); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Inconclusive); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); } else { - ArgumentException thrownException = await VerifyThrowsAsync(testMethodRunner.RunTestMethodAsync); - Verify(thrownException.Message == string.Format(CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataIEnumerableEmpty, nameof(DummyTestClassEmptyDataSource.EmptyProperty), typeof(DummyTestClassEmptyDataSource).FullName)); + Func func = testMethodRunner.RunTestMethodAsync; + (await func.Should().ThrowAsync()) + .And.Message.Should().Be(string.Format(CultureInfo.InvariantCulture, FrameworkMessages.DynamicDataIEnumerableEmpty, nameof(DummyTestClassEmptyDataSource.EmptyProperty), typeof(DummyTestClassEmptyDataSource).FullName)); } } finally diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs index a9f1de559b..619da755ca 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TypeCacheTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; @@ -60,33 +62,34 @@ public void GetTestMethodInfoShouldThrowIfTestMethodIsNull() var testMethod = new TestMethod("M", "C", "A", displayName: null); TestContextImplementation context = CreateTestContextImplementationForMethod(testMethod); - VerifyThrows(() => _typeCache.GetTestMethodInfo(null!, context)); + Action action = () => _typeCache.GetTestMethodInfo(null!, context); + action.Should().Throw(); } public void GetTestMethodInfoShouldThrowIfTestContextIsNull() { var testMethod = new TestMethod("M", "C", "A", displayName: null); - VerifyThrows(() => _typeCache.GetTestMethodInfo(testMethod, null!)); + new Action(() => _typeCache.GetTestMethodInfo(testMethod, null!)).Should().Throw(); } public void GetTestMethodInfoShouldReturnNullIfClassInfoForTheMethodIsNull() { var testMethod = new TestMethod("M", "C", "A", displayName: null); - Verify( - _typeCache.GetTestMethodInfo( - testMethod, - CreateTestContextImplementationForMethod(testMethod)) is null); + _typeCache.GetTestMethodInfo( + testMethod, + CreateTestContextImplementationForMethod(testMethod)) + .Should().BeNull(); } public void GetTestMethodInfoShouldReturnNullIfLoadingTypeThrowsTypeLoadException() { var testMethod = new TestMethod("M", "System.TypedReference[]", "A", displayName: null); - Verify( - _typeCache.GetTestMethodInfo( - testMethod, - CreateTestContextImplementationForMethod(testMethod)) is null); + _typeCache.GetTestMethodInfo( + testMethod, + CreateTestContextImplementationForMethod(testMethod)) + .Should().BeNull(); } public void GetTestMethodInfoShouldThrowIfLoadingTypeThrowsException() @@ -101,9 +104,9 @@ void Action() => testMethod, CreateTestContextImplementationForMethod(testMethod)); - TypeInspectionException exception = VerifyThrows(Action); + TypeInspectionException exception = new Action(Action).Should().Throw().Which; - Verify(exception.Message.StartsWith("Unable to get type C. Error: System.Exception: Load failure", StringComparison.Ordinal)); + exception.Message.StartsWith("Unable to get type C. Error: System.Exception: Load failure", StringComparison.Ordinal).Should().BeTrue(); } public void GetTestMethodInfoShouldThrowIfTypeDoesNotHaveADefaultConstructor() @@ -116,8 +119,8 @@ void Action() => testMethod, CreateTestContextImplementationForMethod(testMethod)); - TypeInspectionException exception = VerifyThrows(Action); - Verify(exception.Message.StartsWith("Cannot find a valid constructor for test class 'Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TypeCacheTests+DummyTestClassWithNoDefaultConstructor'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'.", StringComparison.Ordinal)); + TypeInspectionException exception = new Action(Action).Should().Throw().Which; + exception.Message.StartsWith("Cannot find a valid constructor for test class 'Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TypeCacheTests+DummyTestClassWithNoDefaultConstructor'. Valid constructors are 'public' and either parameterless or with one parameter of type 'TestContext'.", StringComparison.Ordinal).Should().BeTrue(); } public void GetTestMethodInfoShouldThrowIfTestContextHasATypeMismatch() @@ -130,8 +133,8 @@ void Action() => testMethod, CreateTestContextImplementationForMethod(testMethod)); - TypeInspectionException exception = VerifyThrows(Action); - Verify(exception.Message.StartsWith($"The {className}.TestContext has incorrect type.", StringComparison.Ordinal)); + TypeInspectionException exception = new Action(Action).Should().Throw().Which; + exception.Message.StartsWith($"The {className}.TestContext has incorrect type.", StringComparison.Ordinal).Should().BeTrue(); } public void GetTestMethodInfoShouldThrowIfTestContextHasMultipleAmbiguousTestContextProperties() @@ -139,13 +142,13 @@ public void GetTestMethodInfoShouldThrowIfTestContextHasMultipleAmbiguousTestCon string className = typeof(DummyTestClassWithMultipleTestContextProperties).FullName!; var testMethod = new TestMethod("M", className, "A", displayName: null); - void Action() => + Action action = () => _typeCache.GetTestMethodInfo( testMethod, CreateTestContextImplementationForMethod(testMethod)); - TypeInspectionException exception = VerifyThrows(Action); - Verify(exception.Message.StartsWith($"Unable to find property {className}.TestContext. Error:Ambiguous match found", StringComparison.Ordinal)); + action.Should().Throw() + .And.Message.Should().StartWith($"Unable to find property {className}.TestContext. Error:Ambiguous match found"); } public void GetTestMethodInfoShouldSetTestContextIfPresent() @@ -161,8 +164,8 @@ public void GetTestMethodInfoShouldSetTestContextIfPresent() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(testMethodInfo is not null); - Verify(testMethodInfo.Parent.TestContextProperty is not null); + testMethodInfo.Should().NotBeNull(); + testMethodInfo.Parent.TestContextProperty.Should().NotBeNull(); } public void GetTestMethodInfoShouldSetTestContextToNullIfNotPresent() @@ -178,8 +181,8 @@ public void GetTestMethodInfoShouldSetTestContextToNullIfNotPresent() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(testMethodInfo is not null); - Verify(testMethodInfo.Parent.TestContextProperty is null); + testMethodInfo.Should().NotBeNull(); + testMethodInfo.Parent.TestContextProperty.Should().BeNull(); } #region Assembly Info Creation tests. @@ -197,7 +200,7 @@ public void GetTestMethodInfoShouldAddAssemblyInfoToTheCache() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.AssemblyInfoCache.Count == 1); + _typeCache.AssemblyInfoCache.Count.Should().Be(1); } public void GetTestMethodInfoShouldNotThrowIfWeFailToDiscoverTypeFromAnAssembly() @@ -216,7 +219,7 @@ public void GetTestMethodInfoShouldNotThrowIfWeFailToDiscoverTypeFromAnAssembly( testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.AssemblyInfoCache.Count == 1); + _typeCache.AssemblyInfoCache.Count.Should().Be(1); } public void GetTestMethodInfoShouldCacheAssemblyInitializeAttribute() @@ -234,8 +237,8 @@ public void GetTestMethodInfoShouldCacheAssemblyInitializeAttribute() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.AssemblyInfoCache.Count == 1); - Verify(type.GetMethod("AssemblyInit")! == _typeCache.AssemblyInfoCache.First().AssemblyInitializeMethod); + _typeCache.AssemblyInfoCache.Count.Should().Be(1); + _typeCache.AssemblyInfoCache.First().AssemblyInitializeMethod.Should().BeSameAs(type.GetMethod("AssemblyInit")!); } public void GetTestMethodInfoShouldCacheAssemblyCleanupAttribute() @@ -253,8 +256,8 @@ public void GetTestMethodInfoShouldCacheAssemblyCleanupAttribute() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.AssemblyInfoCache.Count == 1); - Verify(type.GetMethod("AssemblyCleanup")! == _typeCache.AssemblyInfoCache.First().AssemblyCleanupMethod); + _typeCache.AssemblyInfoCache.Count.Should().Be(1); + _typeCache.AssemblyInfoCache.First().AssemblyCleanupMethod.Should().BeSameAs(type.GetMethod("AssemblyCleanup")!); } public void GetTestMethodInfoShouldCacheAssemblyInitAndCleanupAttribute() @@ -274,9 +277,9 @@ public void GetTestMethodInfoShouldCacheAssemblyInitAndCleanupAttribute() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.AssemblyInfoCache.Count == 1); - Verify(type.GetMethod("AssemblyCleanup")! == _typeCache.AssemblyInfoCache.First().AssemblyCleanupMethod); - Verify(type.GetMethod("AssemblyInit")! == _typeCache.AssemblyInfoCache.First().AssemblyInitializeMethod); + _typeCache.AssemblyInfoCache.Count.Should().Be(1); + _typeCache.AssemblyInfoCache.First().AssemblyCleanupMethod.Should().BeSameAs(type.GetMethod("AssemblyCleanup")!); + _typeCache.AssemblyInfoCache.First().AssemblyInitializeMethod.Should().BeSameAs(type.GetMethod("AssemblyInit")!); } public void GetTestMethodInfoShouldThrowIfAssemblyInitHasIncorrectSignature() @@ -295,7 +298,7 @@ void A() => testMethod, CreateTestContextImplementationForMethod(testMethod)); - Exception exception = VerifyThrows(A); + Exception exception = new Action(A).Should().Throw().Which; MethodInfo methodInfo = type.GetMethod("AssemblyInit")!; string expectedMessage = @@ -305,7 +308,7 @@ void A() => methodInfo.DeclaringType!.FullName!, methodInfo.Name); - Verify(expectedMessage == exception.Message); + exception.Message.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldThrowIfAssemblyCleanupHasIncorrectSignature() @@ -324,7 +327,7 @@ void A() => testMethod, CreateTestContextImplementationForMethod(testMethod)); - Exception exception = VerifyThrows(A); + Exception exception = new Action(A).Should().Throw().Which; MethodInfo methodInfo = type.GetMethod("AssemblyCleanup")!; string expectedMessage = @@ -334,7 +337,7 @@ void A() => methodInfo.DeclaringType!.FullName!, methodInfo.Name); - Verify(expectedMessage == exception.Message); + exception.Message.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldCacheAssemblyInfoInstanceAndReuseTheCache() @@ -355,7 +358,7 @@ public void GetTestMethodInfoShouldCacheAssemblyInfoInstanceAndReuseTheCache() CreateTestContextImplementationForMethod(testMethod)); _mockReflectHelper.Verify(rh => rh.IsAttributeDefined(type), Times.Once); - Verify(_typeCache.AssemblyInfoCache.Count == 1); + _typeCache.AssemblyInfoCache.Should().HaveCount(1); } #endregion @@ -375,9 +378,9 @@ public void GetTestMethodInfoShouldAddClassInfoToTheCache() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(_typeCache.ClassInfoCache.First()!.TestInitializeMethod is null); - Verify(_typeCache.ClassInfoCache.First()!.TestCleanupMethod is null); + _typeCache.ClassInfoCache.Count.Should().Be(1); + _typeCache.ClassInfoCache.First()!.TestInitializeMethod.Should().BeNull(); + _typeCache.ClassInfoCache.First()!.TestCleanupMethod.Should().BeNull(); } public void GetTestMethodInfoShouldCacheClassInitializeAttribute() @@ -395,9 +398,9 @@ public void GetTestMethodInfoShouldCacheClassInitializeAttribute() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(_typeCache.ClassInfoCache.First()!.BaseClassInitMethods.Count == 0); - Verify(type.GetMethod("AssemblyInit")! == _typeCache.ClassInfoCache.First()!.ClassInitializeMethod); + _typeCache.ClassInfoCache.Count.Should().Be(1); + _typeCache.ClassInfoCache.First()!.BaseClassInitMethods.Count.Should().Be(0); + _typeCache.ClassInfoCache.First()!.ClassInitializeMethod.Should().BeSameAs(type.GetMethod("AssemblyInit")!); } public void GetTestMethodInfoShouldCacheBaseClassInitializeAttributes() @@ -423,9 +426,9 @@ public void GetTestMethodInfoShouldCacheBaseClassInitializeAttributes() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(_typeCache.ClassInfoCache.First()!.BaseClassCleanupMethods.Count == 0, "No base class cleanup"); - Verify(baseType.GetMethod("AssemblyInit")! == _typeCache.ClassInfoCache.First()!.BaseClassInitMethods[0]); + _typeCache.ClassInfoCache.Count.Should().Be(1); + _typeCache.ClassInfoCache.First()!.BaseClassCleanupMethods.Count.Should().Be(0, "No base class cleanup"); + _typeCache.ClassInfoCache.First()!.BaseClassInitMethods[0].Should().BeSameAs(baseType.GetMethod("AssemblyInit")!); } public void GetTestMethodInfoShouldCacheClassCleanupAttribute() @@ -443,8 +446,8 @@ public void GetTestMethodInfoShouldCacheClassCleanupAttribute() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(type.GetMethod("AssemblyCleanup")! == _typeCache.ClassInfoCache.First()!.ClassCleanupMethod); + _typeCache.ClassInfoCache.Count.Should().Be(1); + _typeCache.ClassInfoCache.First()!.ClassCleanupMethod.Should().BeSameAs(type.GetMethod("AssemblyCleanup")!); } public void GetTestMethodInfoShouldCacheBaseClassCleanupAttributes() @@ -466,9 +469,9 @@ public void GetTestMethodInfoShouldCacheBaseClassCleanupAttributes() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(_typeCache.ClassInfoCache.First()!.BaseClassInitMethods.Count == 0, "No base class init"); - Verify(baseType.GetMethod("AssemblyCleanup")! == _typeCache.ClassInfoCache.First()!.BaseClassCleanupMethods[0]); + _typeCache.ClassInfoCache.Count.Should().Be(1); + _typeCache.ClassInfoCache.First()!.BaseClassInitMethods.Count.Should().Be(0, "No base class init"); + _typeCache.ClassInfoCache.First()!.BaseClassCleanupMethods[0].Should().BeSameAs(baseType.GetMethod("AssemblyCleanup")!); } public void GetTestMethodInfoShouldCacheClassInitAndCleanupAttribute() @@ -487,9 +490,9 @@ public void GetTestMethodInfoShouldCacheClassInitAndCleanupAttribute() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(type.GetMethod("AssemblyInit")! == _typeCache.ClassInfoCache.First()!.ClassInitializeMethod); - Verify(type.GetMethod("AssemblyCleanup")! == _typeCache.ClassInfoCache.First()!.ClassCleanupMethod); + _typeCache.ClassInfoCache.Count.Should().Be(1); + _typeCache.ClassInfoCache.First()!.ClassInitializeMethod.Should().BeSameAs(type.GetMethod("AssemblyInit")!); + _typeCache.ClassInfoCache.First()!.ClassCleanupMethod.Should().BeSameAs(type.GetMethod("AssemblyCleanup")!); } public void GetTestMethodInfoShouldCacheBaseClassInitAndCleanupAttributes() @@ -524,12 +527,12 @@ public void GetTestMethodInfoShouldCacheBaseClassInitAndCleanupAttributes() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(type.GetMethod("AssemblyInit")! == _typeCache.ClassInfoCache.First()!.ClassInitializeMethod); - Verify(type.GetMethod("AssemblyCleanup")! == _typeCache.ClassInfoCache.First()!.ClassCleanupMethod); + _typeCache.ClassInfoCache.Count.Should().Be(1); + _typeCache.ClassInfoCache.First()!.ClassInitializeMethod.Should().BeSameAs(type.GetMethod("AssemblyInit")!); + _typeCache.ClassInfoCache.First()!.ClassCleanupMethod.Should().BeSameAs(type.GetMethod("AssemblyCleanup")!); - Verify(baseInitializeMethod == _typeCache.ClassInfoCache.First()!.BaseClassInitMethods[0]); - Verify(baseCleanupMethod == _typeCache.ClassInfoCache.First()!.BaseClassCleanupMethods[0]); + _typeCache.ClassInfoCache.First()!.BaseClassInitMethods[0].Should().BeSameAs(baseInitializeMethod); + _typeCache.ClassInfoCache.First()!.BaseClassCleanupMethods[0].Should().BeSameAs(baseCleanupMethod); } public void GetTestMethodInfoShouldCacheParentAndGrandparentClassInitAndCleanupAttributes() @@ -581,17 +584,17 @@ public void GetTestMethodInfoShouldCacheParentAndGrandparentClassInitAndCleanupA CreateTestContextImplementationForMethod(testMethod)); TestClassInfo? classInfo = _typeCache.ClassInfoCache.FirstOrDefault(); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(classInfo!.ClassInitializeMethod is null); - Verify(classInfo.ClassCleanupMethod is null); + _typeCache.ClassInfoCache.Count.Should().Be(1); + classInfo!.ClassInitializeMethod.Should().BeNull(); + classInfo.ClassCleanupMethod.Should().BeNull(); - Verify(classInfo.BaseClassCleanupMethods.Count == 2); - Verify(parentCleanupMethod == classInfo.BaseClassCleanupMethods[0]); - Verify(grandparentCleanupMethod == classInfo.BaseClassCleanupMethods[1]); + classInfo.BaseClassCleanupMethods.Count.Should().Be(2); + classInfo.BaseClassCleanupMethods[0].Should().BeSameAs(parentCleanupMethod); + classInfo.BaseClassCleanupMethods[1].Should().BeSameAs(grandparentCleanupMethod); - Verify(classInfo.BaseClassInitMethods.Count == 2); - Verify(parentInitMethod == classInfo.BaseClassInitMethods[0]); - Verify(grandparentInitMethod == classInfo.BaseClassInitMethods[1]); + classInfo.BaseClassInitMethods.Count.Should().Be(2); + classInfo.BaseClassInitMethods[0].Should().BeSameAs(parentInitMethod); + classInfo.BaseClassInitMethods[1].Should().BeSameAs(grandparentInitMethod); } public void GetTestMethodInfoShouldThrowIfClassInitHasIncorrectSignature() @@ -610,7 +613,7 @@ void A() => testMethod, CreateTestContextImplementationForMethod(testMethod)); - Exception exception = VerifyThrows(A); + Exception exception = new Action(A).Should().Throw().Which; MethodInfo methodInfo = type.GetMethod("AssemblyInit")!; string expectedMessage = @@ -620,7 +623,7 @@ void A() => methodInfo.DeclaringType!.FullName!, methodInfo.Name); - Verify(expectedMessage == exception.Message); + exception.Message.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldThrowIfClassCleanupHasIncorrectSignature() @@ -639,7 +642,7 @@ void A() => testMethod, CreateTestContextImplementationForMethod(testMethod)); - Exception exception = VerifyThrows(A); + Exception exception = new Action(A).Should().Throw().Which; MethodInfo methodInfo = type.GetMethod("AssemblyCleanup")!; string expectedMessage = @@ -649,7 +652,7 @@ void A() => methodInfo.DeclaringType!.FullName!, methodInfo.Name); - Verify(expectedMessage == exception.Message); + exception.Message.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldCacheTestInitializeAttribute() @@ -667,8 +670,8 @@ public void GetTestMethodInfoShouldCacheTestInitializeAttribute() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(type.GetMethod("TestInit")! == _typeCache.ClassInfoCache.First()!.TestInitializeMethod); + _typeCache.ClassInfoCache.Should().HaveCount(1); + type.GetMethod("TestInit").Should().BeSameAs(_typeCache.ClassInfoCache.First()!.TestInitializeMethod); } public void GetTestMethodInfoShouldCacheTestCleanupAttribute() @@ -686,8 +689,8 @@ public void GetTestMethodInfoShouldCacheTestCleanupAttribute() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(type.GetMethod("TestCleanup")! == _typeCache.ClassInfoCache.First()!.TestCleanupMethod); + _typeCache.ClassInfoCache.Should().HaveCount(1); + type.GetMethod("TestCleanup").Should().BeSameAs(_typeCache.ClassInfoCache.First()!.TestCleanupMethod); } public void GetTestMethodInfoShouldThrowIfTestInitOrCleanupHasIncorrectSignature() @@ -701,12 +704,12 @@ public void GetTestMethodInfoShouldThrowIfTestInitOrCleanupHasIncorrectSignature _mockReflectHelper.Setup( rh => rh.IsAttributeDefined(type.GetMethod("TestInit")!)).Returns(true); - void A() => + Action action = () => _typeCache.GetTestMethodInfo( testMethod, CreateTestContextImplementationForMethod(testMethod)); - TypeInspectionException exception = VerifyThrows(A); + TypeInspectionException exception = action.Should().Throw().Which; MethodInfo methodInfo = type.GetMethod("TestInit")!; string expectedMessage = @@ -716,7 +719,7 @@ void A() => methodInfo.DeclaringType!.FullName!, methodInfo.Name); - Verify(expectedMessage == exception.Message); + exception.Message.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldCacheTestInitializeAttributeDefinedInBaseClass() @@ -735,8 +738,8 @@ public void GetTestMethodInfoShouldCacheTestInitializeAttributeDefinedInBaseClas testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(baseType.GetMethod("TestInit")! == _typeCache.ClassInfoCache.First()!.BaseTestInitializeMethodsQueue.Peek()); + _typeCache.ClassInfoCache.Should().HaveCount(1); + baseType.GetMethod("TestInit").Should().BeSameAs(_typeCache.ClassInfoCache.First()!.BaseTestInitializeMethodsQueue.Peek()); } public void GetTestMethodInfoShouldCacheTestCleanupAttributeDefinedInBaseClass() @@ -755,8 +758,8 @@ public void GetTestMethodInfoShouldCacheTestCleanupAttributeDefinedInBaseClass() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(_typeCache.ClassInfoCache.Count == 1); - Verify(baseType.GetMethod("TestCleanup")! == _typeCache.ClassInfoCache.First()!.BaseTestCleanupMethodsQueue.Peek()); + _typeCache.ClassInfoCache.Should().HaveCount(1); + baseType.GetMethod("TestCleanup").Should().BeSameAs(_typeCache.ClassInfoCache.First()!.BaseTestCleanupMethodsQueue.Peek()); } public void GetTestMethodInfoShouldCacheClassInfoInstanceAndReuseFromCache() @@ -777,7 +780,7 @@ public void GetTestMethodInfoShouldCacheClassInfoInstanceAndReuseFromCache() CreateTestContextImplementationForMethod(testMethod)); _testablePlatformServiceProvider.MockFileOperations.Verify(fo => fo.LoadAssembly(It.IsAny()), Times.Once); - Verify(_typeCache.ClassInfoCache.Count == 1); + _typeCache.ClassInfoCache.Should().HaveCount(1); } #endregion @@ -795,7 +798,7 @@ void A() => testMethod, CreateTestContextImplementationForMethod(testMethod)); - Exception exception = VerifyThrows(A); + Exception exception = new Action(A).Should().Throw().Which; string expectedMessage = string.Format( CultureInfo.InvariantCulture, @@ -803,7 +806,7 @@ void A() => testMethod.FullClassName, testMethod.Name); - Verify(expectedMessage == exception.Message); + exception.Message.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldReturnTestMethodInfo() @@ -817,10 +820,10 @@ public void GetTestMethodInfoShouldReturnTestMethodInfo() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(methodInfo == testMethodInfo!.MethodInfo); - Verify(testMethodInfo.TimeoutInfo.Timeout == 0); - Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); - Verify(testMethodInfo.Executor is not null); + testMethodInfo!.MethodInfo.Should().BeSameAs(methodInfo); + testMethodInfo.TimeoutInfo.Timeout.Should().Be(0); + testMethodInfo.Parent.Should().Be(_typeCache.ClassInfoCache.First()); + testMethodInfo.Executor.Should().NotBeNull(); } public void GetTestMethodInfoShouldReturnTestMethodInfoWithTimeout() @@ -837,10 +840,10 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoWithTimeout() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(methodInfo == testMethodInfo!.MethodInfo); - Verify(testMethodInfo.TimeoutInfo.Timeout == 10); - Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); - Verify(testMethodInfo.Executor is not null); + testMethodInfo!.MethodInfo.Should().BeSameAs(methodInfo); + testMethodInfo.TimeoutInfo.Timeout.Should().Be(10); + testMethodInfo.Parent.Should().Be(_typeCache.ClassInfoCache.First()); + testMethodInfo.Executor.Should().NotBeNull(); } public void GetTestMethodInfoShouldThrowWhenTimeoutIsNegative() @@ -858,7 +861,7 @@ void A() => _typeCache.GetTestMethodInfo( testMethod, CreateTestContextImplementationForMethod(testMethod)); - Exception exception = VerifyThrows(A); + Exception exception = new Action(A).Should().Throw().Which; string expectedMessage = string.Format( @@ -867,7 +870,7 @@ void A() => _typeCache.GetTestMethodInfo( testMethod.FullClassName, testMethod.Name); - Verify(expectedMessage == exception.Message); + exception.Message.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldThrowWhenTimeoutIsZero() @@ -885,7 +888,7 @@ void A() => _typeCache.GetTestMethodInfo( testMethod, CreateTestContextImplementationForMethod(testMethod)); - TypeInspectionException exception = VerifyThrows(A); + TypeInspectionException exception = new Action(A).Should().Throw().Which; string expectedMessage = string.Format( @@ -894,7 +897,7 @@ void A() => _typeCache.GetTestMethodInfo( testMethod.FullClassName, testMethod.Name); - Verify(expectedMessage == exception.Message); + exception.Message.Should().Be(expectedMessage); } public void GetTestMethodInfoWhenTimeoutAttributeNotSetShouldReturnTestMethodInfoWithGlobalTimeout() @@ -918,7 +921,7 @@ public void GetTestMethodInfoWhenTimeoutAttributeNotSetShouldReturnTestMethodInf testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(testMethodInfo!.TimeoutInfo.Timeout == 4000); + testMethodInfo!.TimeoutInfo.Timeout.Should().Be(4000); } public void GetTestMethodInfoWhenTimeoutAttributeSetShouldReturnTimeoutBasedOnAttributeEvenIfGlobalTimeoutSet() @@ -947,7 +950,7 @@ public void GetTestMethodInfoWhenTimeoutAttributeSetShouldReturnTimeoutBasedOnAt testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(testMethodInfo!.TimeoutInfo.Timeout == 10); + testMethodInfo!.TimeoutInfo.Timeout.Should().Be(10); } public void GetTestMethodInfoForInvalidGlobalTimeoutShouldReturnTestMethodInfoWithTimeoutZero() @@ -971,7 +974,7 @@ public void GetTestMethodInfoForInvalidGlobalTimeoutShouldReturnTestMethodInfoWi testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(testMethodInfo!.TimeoutInfo.Timeout == 0); + testMethodInfo!.TimeoutInfo.Timeout.Should().Be(0); } public void GetTestMethodInfoShouldReturnTestMethodInfoForMethodsAdornedWithADerivedTestMethodAttribute() @@ -985,11 +988,11 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForMethodsAdornedWithADer testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(methodInfo == testMethodInfo!.MethodInfo); - Verify(testMethodInfo.TimeoutInfo.Timeout == 0); - Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); - Verify(testMethodInfo.Executor is not null); - Verify(testMethodInfo.Executor is DerivedTestMethodAttribute); + testMethodInfo!.MethodInfo.Should().BeSameAs(methodInfo); + testMethodInfo.TimeoutInfo.Timeout.Should().Be(0); + testMethodInfo.Parent.Should().Be(_typeCache.ClassInfoCache.First()); + testMethodInfo.Executor.Should().NotBeNull(); + testMethodInfo.Executor.Should().BeOfType(); } public void GetTestMethodInfoShouldSetTestContextWithCustomProperty() @@ -1006,8 +1009,8 @@ public void GetTestMethodInfoShouldSetTestContextWithCustomProperty() typeCache.GetTestMethodInfo(testMethod, testContext); KeyValuePair customProperty = testContext.Properties.FirstOrDefault(p => p.Key.Equals("WhoAmI", StringComparison.Ordinal)); - Verify((object)customProperty is not null); - Verify((customProperty.Value as string) == "Me"); + customProperty.Should().NotBeNull(); + (customProperty.Value as string).Should().Be("Me"); } public void GetTestMethodInfoShouldReportWarningIfCustomPropertyHasSameNameAsPredefinedProperties() @@ -1022,14 +1025,14 @@ public void GetTestMethodInfoShouldReportWarningIfCustomPropertyHasSameNameAsPre TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); - Verify(testMethodInfo is not null); + testMethodInfo.Should().NotBeNull(); string expectedMessage = string.Format( CultureInfo.InvariantCulture, "UTA023: {0}: Cannot define predefined property {2} on method {1}.", methodInfo.DeclaringType!.FullName!, methodInfo.Name, "TestCategory"); - Verify(expectedMessage == testMethodInfo.NotRunnableReason); + testMethodInfo.NotRunnableReason.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldReportWarningIfCustomOwnerPropertyIsDefined() @@ -1043,14 +1046,14 @@ public void GetTestMethodInfoShouldReportWarningIfCustomOwnerPropertyIsDefined() TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); - Verify(testMethodInfo is not null); + testMethodInfo.Should().NotBeNull(); string expectedMessage = string.Format( CultureInfo.InvariantCulture, "UTA023: {0}: Cannot define predefined property {2} on method {1}.", methodInfo.DeclaringType!.FullName!, methodInfo.Name, "Owner"); - Verify(expectedMessage == testMethodInfo.NotRunnableReason); + testMethodInfo.NotRunnableReason.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldReportWarningIfCustomPriorityPropertyIsDefined() @@ -1064,14 +1067,14 @@ public void GetTestMethodInfoShouldReportWarningIfCustomPriorityPropertyIsDefine TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); - Verify(testMethodInfo is not null); + testMethodInfo.Should().NotBeNull(); string expectedMessage = string.Format( CultureInfo.InvariantCulture, "UTA023: {0}: Cannot define predefined property {2} on method {1}.", methodInfo.DeclaringType!.FullName!, methodInfo.Name, "Priority"); - Verify(expectedMessage == testMethodInfo.NotRunnableReason); + testMethodInfo.NotRunnableReason.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldAllowActualOwnerAttribute() @@ -1085,12 +1088,12 @@ public void GetTestMethodInfoShouldAllowActualOwnerAttribute() TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); - Verify(testMethodInfo is not null); + testMethodInfo.Should().NotBeNull(); // Owner should be allowed - no NotRunnableReason should be set - Verify(string.IsNullOrEmpty(testMethodInfo.NotRunnableReason)); + string.IsNullOrEmpty(testMethodInfo.NotRunnableReason).Should().BeTrue(); // The Owner property should be added to the test context - Verify(testContext.TryGetPropertyValue("Owner", out object? ownerValue)); - Verify(ownerValue?.ToString() == "TestOwner"); + testContext.TryGetPropertyValue("Owner", out object? ownerValue).Should().BeTrue(); + ownerValue?.ToString().Should().Be("TestOwner"); } public void GetTestMethodInfoShouldAllowActualPriorityAttribute() @@ -1104,12 +1107,12 @@ public void GetTestMethodInfoShouldAllowActualPriorityAttribute() TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); - Verify(testMethodInfo is not null); + testMethodInfo.Should().NotBeNull(); // Priority should be allowed - no NotRunnableReason should be set - Verify(string.IsNullOrEmpty(testMethodInfo.NotRunnableReason)); + string.IsNullOrEmpty(testMethodInfo.NotRunnableReason).Should().BeTrue(); // The Priority property should be added to the test context - Verify(testContext.TryGetPropertyValue("Priority", out object? priorityValue)); - Verify(priorityValue?.ToString() == "1"); + testContext.TryGetPropertyValue("Priority", out object? priorityValue).Should().BeTrue(); + priorityValue?.ToString().Should().Be("1"); } public void GetTestMethodInfoShouldReportWarningIfCustomPropertyNameIsEmpty() @@ -1124,13 +1127,13 @@ public void GetTestMethodInfoShouldReportWarningIfCustomPropertyNameIsEmpty() TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); - Verify(testMethodInfo is not null); + testMethodInfo.Should().NotBeNull(); string expectedMessage = string.Format( CultureInfo.InvariantCulture, "UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name.", methodInfo.DeclaringType!.FullName!, methodInfo.Name); - Verify(expectedMessage == testMethodInfo.NotRunnableReason); + testMethodInfo.NotRunnableReason.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldReportWarningIfCustomPropertyNameIsNull() @@ -1145,13 +1148,13 @@ public void GetTestMethodInfoShouldReportWarningIfCustomPropertyNameIsNull() TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); - Verify(testMethodInfo is not null); + testMethodInfo.Should().NotBeNull(); string expectedMessage = string.Format( CultureInfo.InvariantCulture, "UTA021: {0}: Null or empty custom property defined on method {1}. The custom property must have a valid name.", methodInfo.DeclaringType!.FullName!, methodInfo.Name); - Verify(expectedMessage == testMethodInfo.NotRunnableReason); + testMethodInfo.NotRunnableReason.Should().Be(expectedMessage); } public void GetTestMethodInfoShouldNotAddDuplicateTestPropertiesToTestContext() @@ -1166,11 +1169,11 @@ public void GetTestMethodInfoShouldNotAddDuplicateTestPropertiesToTestContext() TestMethodInfo? testMethodInfo = typeCache.GetTestMethodInfo(testMethod, testContext); - Verify(testMethodInfo is not null); + testMethodInfo.Should().NotBeNull(); // Verify that the first value gets set. - Verify(testContext.Properties.TryGetValue("WhoAmI", out object? value)); - Verify((value as string) == "Me"); + testContext.Properties.TryGetValue("WhoAmI", out object? value).Should().BeTrue(); + value.Should().Be("Me"); } public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedTestClasses() @@ -1184,10 +1187,10 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedTestClasses() testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(methodInfo == testMethodInfo!.MethodInfo); - Verify(testMethodInfo.TimeoutInfo.Timeout == 0); - Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); - Verify(testMethodInfo.Executor is not null); + testMethodInfo!.MethodInfo.Should().BeSameAs(methodInfo); + testMethodInfo.TimeoutInfo.Timeout.Should().Be(0); + testMethodInfo.Parent.Should().Be(_typeCache.ClassInfoCache.First()); + testMethodInfo.Executor.Should().NotBeNull(); } public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedClassMethodOverloadByDefault() @@ -1201,10 +1204,10 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedClassMethodOver testMethod, CreateTestContextImplementationForMethod(testMethod)); - Verify(methodInfo == testMethodInfo!.MethodInfo); - Verify(testMethodInfo.TimeoutInfo.Timeout == 0); - Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); - Verify(testMethodInfo.Executor is not null); + testMethodInfo!.MethodInfo.Should().BeSameAs(methodInfo); + testMethodInfo.TimeoutInfo.Timeout.Should().Be(0); + testMethodInfo.Parent.Should().Be(_typeCache.ClassInfoCache.First()); + testMethodInfo.Executor.Should().NotBeNull(); } public void GetTestMethodInfoShouldReturnTestMethodInfoForDeclaringTypeMethodOverload() @@ -1224,10 +1227,10 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDeclaringTypeMethodOve // The two MethodInfo instances will have different ReflectedType properties, // so cannot be compared directly. Use MethodHandle to verify it's the same. - Verify(methodInfo.MethodHandle == testMethodInfo!.MethodInfo.MethodHandle); - Verify(testMethodInfo.TimeoutInfo.Timeout == 0); - Verify(_typeCache.ClassInfoCache.First() == testMethodInfo.Parent); - Verify(testMethodInfo.Executor is not null); + testMethodInfo!.MethodInfo.MethodHandle.Should().Be(methodInfo.MethodHandle); + testMethodInfo.TimeoutInfo.Timeout.Should().Be(0); + testMethodInfo.Parent.Should().Be(_typeCache.ClassInfoCache.First()); + testMethodInfo.Executor.Should().NotBeNull(); } #endregion @@ -1240,7 +1243,7 @@ public void ClassInfoListWithExecutableCleanupMethodsShouldReturnEmptyListWhenCl { IEnumerable cleanupMethods = _typeCache.ClassInfoListWithExecutableCleanupMethods; - Verify(!cleanupMethods.Any()); + cleanupMethods.Any().Should().BeFalse(); } public void ClassInfoListWithExecutableCleanupMethodsShouldReturnEmptyListWhenClassInfoCacheDoesNotHaveTestCleanupMethods() @@ -1261,7 +1264,7 @@ public void ClassInfoListWithExecutableCleanupMethodsShouldReturnEmptyListWhenCl IEnumerable cleanupMethods = _typeCache.ClassInfoListWithExecutableCleanupMethods; - Verify(!cleanupMethods.Any()); + cleanupMethods.Any().Should().BeFalse(); } public void ClassInfoListWithExecutableCleanupMethodsShouldReturnClassInfosWithExecutableCleanupMethods() @@ -1282,8 +1285,8 @@ public void ClassInfoListWithExecutableCleanupMethodsShouldReturnClassInfosWithE IEnumerable cleanupMethods = _typeCache.ClassInfoListWithExecutableCleanupMethods; - Verify(cleanupMethods.Count() == 1); - Verify(type.GetMethod("AssemblyCleanup")! == cleanupMethods.First().ClassCleanupMethod); + cleanupMethods.Count().Should().Be(1); + cleanupMethods.First().ClassCleanupMethod.Should().BeSameAs(type.GetMethod("AssemblyCleanup")!); } #endregion @@ -1294,7 +1297,7 @@ public void AssemblyInfoListWithExecutableCleanupMethodsShouldReturnEmptyListWhe { IEnumerable cleanupMethods = _typeCache.AssemblyInfoListWithExecutableCleanupMethods; - Verify(!cleanupMethods.Any()); + cleanupMethods.Any().Should().BeFalse(); } public void AssemblyInfoListWithExecutableCleanupMethodsShouldReturnEmptyListWhenAssemblyInfoCacheDoesNotHaveTestCleanupMethods() @@ -1315,7 +1318,7 @@ public void AssemblyInfoListWithExecutableCleanupMethodsShouldReturnEmptyListWhe IEnumerable cleanupMethods = _typeCache.AssemblyInfoListWithExecutableCleanupMethods; - Verify(!cleanupMethods.Any()); + cleanupMethods.Any().Should().BeFalse(); } public void AssemblyInfoListWithExecutableCleanupMethodsShouldReturnAssemblyInfoWithExecutableCleanupMethods() @@ -1336,8 +1339,8 @@ public void AssemblyInfoListWithExecutableCleanupMethodsShouldReturnAssemblyInfo IEnumerable cleanupMethods = _typeCache.AssemblyInfoListWithExecutableCleanupMethods; - Verify(cleanupMethods.Count() == 1); - Verify(type.GetMethod("AssemblyCleanup")! == cleanupMethods.First().AssemblyCleanupMethod); + cleanupMethods.Count().Should().Be(1); + cleanupMethods.First().AssemblyCleanupMethod.Should().BeSameAs(type.GetMethod("AssemblyCleanup")!); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestResultTest.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestResultTest.cs index 3242ccac01..f67277bfd4 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestResultTest.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestResultTest.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using TestFramework.ForTestingMSTest; @@ -15,8 +17,8 @@ public void UnitTestResultConstructorWithOutcomeAndErrorMessageShouldSetRequired { UnitTestResult result = new(UnitTestOutcome.Error, "DummyMessage"); - Verify(result.Outcome == UnitTestOutcome.Error); - Verify(result.ErrorMessage == "DummyMessage"); + result.Outcome.Should().Be(UnitTestOutcome.Error); + result.ErrorMessage.Should().Be("DummyMessage"); } public void UnitTestResultConstructorWithTestFailedExceptionShouldSetRequiredFields() @@ -26,11 +28,11 @@ public void UnitTestResultConstructorWithTestFailedExceptionShouldSetRequiredFie UnitTestResult result = new(ex); - Verify(result.Outcome == UnitTestOutcome.Error); - Verify(result.ErrorMessage == "DummyMessage"); - Verify(result.ErrorStackTrace == "trace"); - Verify(result.ErrorFilePath == "filePath"); - Verify(result.ErrorLineNumber == 2); - Verify(result.ErrorColumnNumber == 3); + result.Outcome.Should().Be(UnitTestOutcome.Error); + result.ErrorMessage.Should().Be("DummyMessage"); + result.ErrorStackTrace.Should().Be("trace"); + result.ErrorFilePath.Should().Be("filePath"); + result.ErrorLineNumber.Should().Be(2); + result.ErrorColumnNumber.Should().Be(3); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestRunnerTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestRunnerTests.cs index 17b50b5d0b..1e0ceb294d 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/UnitTestRunnerTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; @@ -66,20 +68,24 @@ public void ConstructorShouldPopulateSettings() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object)!; var assemblyEnumerator = new UnitTestRunner(adapterSettings, []); - Verify(MSTestSettings.CurrentSettings.TestSettingsFile == "DummyPath\\TestSettings1.testsettings"); + MSTestSettings.CurrentSettings.TestSettingsFile.Should().Be("DummyPath\\TestSettings1.testsettings"); } #endregion #region RunSingleTest tests - public async Task RunSingleTestShouldThrowIfTestMethodIsNull() => - await VerifyThrowsAsync(async () => await _unitTestRunner.RunSingleTestAsync(null!, null!, null!)); + public async Task RunSingleTestShouldThrowIfTestMethodIsNull() + { + Func func = () => _unitTestRunner.RunSingleTestAsync(null!, null!, null!); + await func.Should().ThrowAsync(); + } public async Task RunSingleTestShouldThrowIfTestRunParametersIsNull() { var testMethod = new TestMethod("M", "C", "A", displayName: null); - await VerifyThrowsAsync(async () => await _unitTestRunner.RunSingleTestAsync(testMethod, null!, null!)); + Func func = () => _unitTestRunner.RunSingleTestAsync(testMethod, null!, null!); + await func.Should().ThrowAsync(); } public async Task RunSingleTestShouldReturnTestResultIndicateATestNotFoundIfTestMethodCannotBeFound() @@ -91,10 +97,10 @@ public async Task RunSingleTestShouldReturnTestResultIndicateATestNotFoundIfTest TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.NotFound); - Verify(results[0].IgnoreReason == "Test method M was not found."); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.NotFound); + results[0].IgnoreReason.Should().Be("Test method M was not found."); } public async Task RunSingleTestShouldReturnTestResultIndicatingNotRunnableTestIfTestMethodCannotBeRun() @@ -114,10 +120,10 @@ public async Task RunSingleTestShouldReturnTestResultIndicatingNotRunnableTestIf methodInfo.DeclaringType!.FullName, methodInfo.Name); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.NotRunnable); - Verify(expectedMessage == results[0].IgnoreReason); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.NotRunnable); + results[0].IgnoreReason.Should().Be(expectedMessage); } public async Task ExecuteShouldSkipTestAndFillInClassIgnoreMessageIfIgnoreAttributeIsPresentOnTestClassAndHasMessage() @@ -131,10 +137,10 @@ public async Task ExecuteShouldSkipTestAndFillInClassIgnoreMessageIfIgnoreAttrib TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Ignored); - Verify(results[0].IgnoreReason == "IgnoreTestClassMessage"); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Ignored); + results[0].IgnoreReason.Should().Be("IgnoreTestClassMessage"); } public async Task ExecuteShouldSkipTestAndSkipFillingIgnoreMessageIfIgnoreAttributeIsPresentOnTestClassButHasNoMessage() @@ -148,10 +154,10 @@ public async Task ExecuteShouldSkipTestAndSkipFillingIgnoreMessageIfIgnoreAttrib TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Ignored); - Verify(results[0].IgnoreReason == string.Empty); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Ignored); + results[0].IgnoreReason.Should().Be(string.Empty); } public async Task ExecuteShouldSkipTestAndFillInMethodIgnoreMessageIfIgnoreAttributeIsPresentOnTestMethodAndHasMessage() @@ -165,10 +171,10 @@ public async Task ExecuteShouldSkipTestAndFillInMethodIgnoreMessageIfIgnoreAttri TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Ignored); - Verify(results[0].IgnoreReason == "IgnoreTestMessage"); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Ignored); + results[0].IgnoreReason.Should().Be("IgnoreTestMessage"); } public async Task ExecuteShouldSkipTestAndSkipFillingIgnoreMessageIfIgnoreAttributeIsPresentOnTestMethodButHasNoMessage() @@ -182,10 +188,10 @@ public async Task ExecuteShouldSkipTestAndSkipFillingIgnoreMessageIfIgnoreAttrib TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Ignored); - Verify(results[0].IgnoreReason == string.Empty); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Ignored); + results[0].IgnoreReason.Should().Be(string.Empty); } public async Task ExecuteShouldSkipTestAndFillInClassIgnoreMessageIfIgnoreAttributeIsPresentOnBothClassAndMethod() @@ -199,10 +205,10 @@ public async Task ExecuteShouldSkipTestAndFillInClassIgnoreMessageIfIgnoreAttrib TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Ignored); - Verify(results[0].IgnoreReason == "IgnoreTestClassMessage"); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Ignored); + results[0].IgnoreReason.Should().Be("IgnoreTestClassMessage"); } public async Task ExecuteShouldSkipTestAndFillInMethodIgnoreMessageIfIgnoreAttributeIsPresentOnBothClassAndMethodButClassHasNoMessage() @@ -216,10 +222,10 @@ public async Task ExecuteShouldSkipTestAndFillInMethodIgnoreMessageIfIgnoreAttri TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Ignored); - Verify(results[0].IgnoreReason == "IgnoreTestMessage"); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Ignored); + results[0].IgnoreReason.Should().Be("IgnoreTestMessage"); } public async Task RunSingleTestShouldReturnTestResultIndicatingFailureIfThereIsAnyTypeInspectionExceptionWhenInspectingTestMethod() @@ -238,10 +244,10 @@ public async Task RunSingleTestShouldReturnTestResultIndicatingFailureIfThereIsA testMethod.FullClassName, testMethod.Name); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Failed); - Verify(expectedMessage == results[0].IgnoreReason); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Failed); + results[0].IgnoreReason.Should().Be(expectedMessage); } public async Task RunSingleTestShouldReturnTestResultsForAPassingTestMethod() @@ -255,10 +261,10 @@ public async Task RunSingleTestShouldReturnTestResultsForAPassingTestMethod() TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Passed); - Verify(results[0].IgnoreReason is null); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); + results[0].IgnoreReason.Should().BeNull(); } public async Task RunSingleTestShouldSetTestsAsInProgressInTestContext() @@ -273,9 +279,9 @@ public async Task RunSingleTestShouldSetTestsAsInProgressInTestContext() // Asserting in the test method execution flow itself. TestResult[] results = await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(results is not null); - Verify(results.Length == 1); - Verify(results[0].Outcome == UTF.UnitTestOutcome.Passed); + results.Should().NotBeNull(); + results.Length.Should().Be(1); + results[0].Outcome.Should().Be(UTF.UnitTestOutcome.Passed); } public async Task RunSingleTestShouldCallAssemblyInitializeAndClassInitializeMethodsInOrder() @@ -299,7 +305,7 @@ public async Task RunSingleTestShouldCallAssemblyInitializeAndClassInitializeMet await _unitTestRunner.RunSingleTestAsync(testMethod, _testRunParameters, null!); - Verify(validator == 1); + validator.Should().Be(1); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs index bf28034646..c0233e5221 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/ExceptionExtensionsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; @@ -16,7 +18,7 @@ public class ExceptionExtensionsTests : TestContainer public void GetExceptionMessageShouldReturnExceptionMessage() { Exception ex = new("something bad happened"); - Verify(ex.GetExceptionMessage() == "something bad happened"); + ex.GetExceptionMessage().Should().Be("something bad happened"); } public void GetExceptionMessageShouldReturnInnerExceptionMessageAsWell() @@ -29,7 +31,7 @@ public void GetExceptionMessageShouldReturnInnerExceptionMessageAsWell() Environment.NewLine, "the real exception"); - Verify(expectedMessage == ex.GetExceptionMessage()); + ex.GetExceptionMessage().Should().Be(expectedMessage); } #region TryGetExceptionMessage scenarios @@ -38,14 +40,14 @@ public void ExceptionTryGetMessageGetsTheExceptionMessage() { var exception = new Exception("dummyMessage"); - Verify(exception.TryGetMessage() == "dummyMessage"); + exception.TryGetMessage().Should().Be("dummyMessage"); } public void ExceptionTryGetMessageReturnsEmptyStringIfExceptionMessageIsNull() { var exception = new DummyException(() => null!); - Verify(exception.TryGetMessage() == string.Empty); + exception.TryGetMessage().Should().Be(string.Empty); } public void ExceptionTryGetMessageReturnsErrorMessageIfExceptionIsNull() @@ -54,14 +56,15 @@ public void ExceptionTryGetMessageReturnsErrorMessageIfExceptionIsNull() var exception = (Exception?)null; - Verify(errorMessage == exception.TryGetMessage()); + exception.TryGetMessage().Should().Be(errorMessage); } public void ExceptionTryGetMessageShouldThrowIfExceptionMessageThrows() { var exception = new DummyException(() => throw new NotImplementedException()); - VerifyThrows(() => exception.TryGetMessage()); + Action action = () => exception.TryGetMessage(); + action.Should().Throw(); } #endregion @@ -72,7 +75,7 @@ public void TryGetStackTraceInformationReturnsNullIfExceptionStackTraceIsNullOrE { var exception = new DummyExceptionForStackTrace(() => null!); - Verify(exception.TryGetStackTraceInformation() is null); + exception.TryGetStackTraceInformation().Should().BeNull(); } public void TryGetStackTraceInformationReturnsStackTraceForAnException() @@ -81,16 +84,17 @@ public void TryGetStackTraceInformationReturnsStackTraceForAnException() StackTraceInformation? stackTraceInformation = exception.TryGetStackTraceInformation(); - Verify(stackTraceInformation!.ErrorStackTrace.StartsWith(" at A()", StringComparison.Ordinal)); - Verify(stackTraceInformation.ErrorFilePath is null); - Verify(stackTraceInformation.ErrorLineNumber == 0); + stackTraceInformation!.ErrorStackTrace.Should().StartWith(" at A()"); + stackTraceInformation.ErrorFilePath.Should().BeNull(); + stackTraceInformation.ErrorLineNumber.Should().Be(0); } public void TryGetStackTraceInformationShouldThrowIfStackTraceThrows() { var exception = new DummyExceptionForStackTrace(() => throw new NotImplementedException()); - VerifyThrows(() => exception.TryGetStackTraceInformation()); + Action action = () => exception.TryGetStackTraceInformation(); + action.Should().Throw(); } #pragma warning disable CA1710 // Identifiers should have correct suffix @@ -120,13 +124,13 @@ internal class DummyException : Exception public void IsUnitTestAssertExceptionReturnsTrueIfExceptionIsAssertException() { var exception = new AssertInconclusiveException(); - Verify(exception.TryGetUnitTestAssertException(out _, out _, out _)); + exception.TryGetUnitTestAssertException(out _, out _, out _).Should().BeTrue(); } public void IsUnitTestAssertExceptionReturnsFalseIfExceptionIsNotAssertException() { var exception = new NotImplementedException(); - Verify(!exception.TryGetUnitTestAssertException(out _, out _, out _)); + exception.TryGetUnitTestAssertException(out _, out _, out _).Should().BeFalse(); } public void IsUnitTestAssertExceptionSetsOutcomeAsInconclusiveIfAssertInconclusiveException() @@ -134,8 +138,8 @@ public void IsUnitTestAssertExceptionSetsOutcomeAsInconclusiveIfAssertInconclusi var exception = new AssertInconclusiveException("Dummy Message", new NotImplementedException("notImplementedException")); exception.TryGetUnitTestAssertException(out UTF.UnitTestOutcome outcome, out string? exceptionMessage, out _); - Verify(outcome == UTF.UnitTestOutcome.Inconclusive); - Verify(exceptionMessage == "Dummy Message"); + outcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); + exceptionMessage.Should().Be("Dummy Message"); } public void IsUnitTestAssertExceptionSetsOutcomeAsFailedIfAssertFailedException() @@ -143,8 +147,8 @@ public void IsUnitTestAssertExceptionSetsOutcomeAsFailedIfAssertFailedException( var exception = new AssertFailedException("Dummy Message", new NotImplementedException("notImplementedException")); exception.TryGetUnitTestAssertException(out UTF.UnitTestOutcome outcome, out string? exceptionMessage, out _); - Verify(outcome == UTF.UnitTestOutcome.Failed); - Verify(exceptionMessage == "Dummy Message"); + outcome.Should().Be(UTF.UnitTestOutcome.Failed); + exceptionMessage.Should().Be("Dummy Message"); } #endregion @@ -154,7 +158,7 @@ public void GetRealExceptionGetsTheTopExceptionWhenThereIsJustOne() var exception = new InvalidOperationException(); Exception actual = exception.GetRealException(); - Verify(actual is InvalidOperationException); + actual.Should().BeOfType(); } public void GetRealExceptionGetsTheInnerExceptionWhenTheExceptionIsTargetInvocation() @@ -162,7 +166,7 @@ public void GetRealExceptionGetsTheInnerExceptionWhenTheExceptionIsTargetInvocat var exception = new TargetInvocationException(new InvalidOperationException()); Exception actual = exception.GetRealException(); - Verify(actual is InvalidOperationException); + actual.Should().BeOfType(); } public void GetRealExceptionGetsTheTargetInvocationExceptionWhenTargetInvocationIsProvidedWithNullInnerException() @@ -170,7 +174,7 @@ public void GetRealExceptionGetsTheTargetInvocationExceptionWhenTargetInvocation var exception = new TargetInvocationException(null); Exception actual = exception.GetRealException(); - Verify(actual is TargetInvocationException); + actual.Should().BeOfType(); } public void GetRealExceptionGetsTheInnerMostRealException() @@ -178,7 +182,7 @@ public void GetRealExceptionGetsTheInnerMostRealException() var exception = new TargetInvocationException(new TargetInvocationException(new TargetInvocationException(new InvalidOperationException()))); Exception actual = exception.GetRealException(); - Verify(actual is InvalidOperationException); + actual.Should().BeOfType(); } public void GetRealExceptionGetsTheInnerMostTargetInvocationException() @@ -186,8 +190,8 @@ public void GetRealExceptionGetsTheInnerMostTargetInvocationException() var exception = new TargetInvocationException(new TargetInvocationException(new TargetInvocationException("inner most", null))); Exception actual = exception.GetRealException(); - Verify(actual is TargetInvocationException); - Verify(actual.Message == "inner most"); + actual.Should().BeOfType(); + actual.Message.Should().Be("inner most"); } public void GetRealExceptionGetsTheInnerExceptionWhenTheExceptionIsTypeInitialization() @@ -195,7 +199,7 @@ public void GetRealExceptionGetsTheInnerExceptionWhenTheExceptionIsTypeInitializ var exception = new TypeInitializationException("some type", new InvalidOperationException()); Exception actual = exception.GetRealException(); - Verify(actual is InvalidOperationException); + actual.Should().BeOfType(); } public void GetRealExceptionGetsTheTypeInitializationExceptionWhenTypeInitializationIsProvidedWithNullInnerException() @@ -203,7 +207,7 @@ public void GetRealExceptionGetsTheTypeInitializationExceptionWhenTypeInitializa var exception = new TypeInitializationException("some type", null); Exception actual = exception.GetRealException(); - Verify(actual is TypeInitializationException); + actual.Should().BeOfType(); } public void GetRealExceptionGetsTheInnerMostRealExceptionOfTypeInitialization() @@ -211,7 +215,7 @@ public void GetRealExceptionGetsTheInnerMostRealExceptionOfTypeInitialization() var exception = new TypeInitializationException("some type", new TypeInitializationException("some type", new TypeInitializationException("some type", new InvalidOperationException()))); Exception actual = exception.GetRealException(); - Verify(actual is InvalidOperationException); + actual.Should().BeOfType(); } public void GetRealExceptionGetsTheInnerMostTypeInitializationException() @@ -219,8 +223,8 @@ public void GetRealExceptionGetsTheInnerMostTypeInitializationException() var exception = new TypeInitializationException("some type", new TypeInitializationException("some type", new TypeInitializationException("inner most", null))); Exception actual = exception.GetRealException(); - Verify(actual is TypeInitializationException); - Verify(actual.Message == "The type initializer for 'inner most' threw an exception."); + actual.Should().BeOfType(); + actual.Message.Should().Be("The type initializer for 'inner most' threw an exception."); } #endregion } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs index d330dc42e8..c38747a6e0 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/MethodInfoExtensionsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions; @@ -19,55 +21,55 @@ public class MethodInfoExtensionsTests : TestContainer public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnFalseForNonStaticMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethod")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnFalseForNonPublicMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("InternalStaticMethod", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; - Verify(!methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnFalseForMethodsNotHavingOneParameter() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethod")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnFalseForMethodsNotTestContextParameter() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethodWithInt")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnFalseForMethodsNotHavingVoidOrAsyncReturnType() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethodWithTCReturningInt")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnTrueForTestMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethodWithTC")!; - Verify(methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeTrue(); } public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnTrueForAsyncTestMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticAsyncTaskMethodWithTC")!; - Verify(methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeTrue(); } public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnTrueForTestMethodsWithoutAsync() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticNonAsyncTaskMethodWithTC")!; - Verify(methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeTrue(); } public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnFalseForAsyncTestMethodsWithNonTaskReturnTypes() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticAsyncVoidMethodWithTC")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyInitializeSignature()); + methodInfo.HasCorrectClassOrAssemblyInitializeSignature().Should().BeFalse(); } #endregion @@ -77,49 +79,49 @@ public void HasCorrectClassOrAssemblyInitializeSignatureShouldReturnFalseForAsyn public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnFalseForNonStaticMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethod")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyCleanupSignature()); + methodInfo.HasCorrectClassOrAssemblyCleanupSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnFalseForNonPublicMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("InternalStaticMethod", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; - Verify(!methodInfo.HasCorrectClassOrAssemblyCleanupSignature()); + methodInfo.HasCorrectClassOrAssemblyCleanupSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnFalseForMethodsHavingParameters() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethodWithInt")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyCleanupSignature()); + methodInfo.HasCorrectClassOrAssemblyCleanupSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnFalseForMethodsNotHavingVoidOrAsyncReturnType() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethodReturningInt")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyCleanupSignature()); + methodInfo.HasCorrectClassOrAssemblyCleanupSignature().Should().BeFalse(); } public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnTrueForTestMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethod")!; - Verify(methodInfo.HasCorrectClassOrAssemblyCleanupSignature()); + methodInfo.HasCorrectClassOrAssemblyCleanupSignature().Should().BeTrue(); } public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnTrueForAsyncTestMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticAsyncTaskMethod")!; - Verify(methodInfo.HasCorrectClassOrAssemblyCleanupSignature()); + methodInfo.HasCorrectClassOrAssemblyCleanupSignature().Should().BeTrue(); } public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnTrueForTestMethodsWithoutAsync() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticNonAsyncTaskMethod")!; - Verify(methodInfo.HasCorrectClassOrAssemblyCleanupSignature()); + methodInfo.HasCorrectClassOrAssemblyCleanupSignature().Should().BeTrue(); } public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnFalseForAsyncTestMethodsWithNonTaskReturnTypes() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticAsyncVoidMethod")!; - Verify(!methodInfo.HasCorrectClassOrAssemblyCleanupSignature()); + methodInfo.HasCorrectClassOrAssemblyCleanupSignature().Should().BeFalse(); } #endregion @@ -129,49 +131,49 @@ public void HasCorrectClassOrAssemblyCleanupSignatureShouldReturnFalseForAsyncTe public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnFalseForStaticMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethod")!; - Verify(!methodInfo.HasCorrectTestInitializeOrCleanupSignature()); + methodInfo.HasCorrectTestInitializeOrCleanupSignature().Should().BeFalse(); } public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnFalseForNonPublicMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("InternalMethod", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!; - Verify(!methodInfo.HasCorrectTestInitializeOrCleanupSignature()); + methodInfo.HasCorrectTestInitializeOrCleanupSignature().Should().BeFalse(); } public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnFalseForMethodsHavingParameters() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethodWithInt")!; - Verify(!methodInfo.HasCorrectTestInitializeOrCleanupSignature()); + methodInfo.HasCorrectTestInitializeOrCleanupSignature().Should().BeFalse(); } public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnFalseForMethodsNotHavingVoidOrAsyncReturnType() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethodReturningInt")!; - Verify(!methodInfo.HasCorrectTestInitializeOrCleanupSignature()); + methodInfo.HasCorrectTestInitializeOrCleanupSignature().Should().BeFalse(); } public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnTrueForTestMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethod")!; - Verify(methodInfo.HasCorrectTestInitializeOrCleanupSignature()); + methodInfo.HasCorrectTestInitializeOrCleanupSignature().Should().BeTrue(); } public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnTrueForAsyncTestMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicAsyncTaskMethod")!; - Verify(methodInfo.HasCorrectTestInitializeOrCleanupSignature()); + methodInfo.HasCorrectTestInitializeOrCleanupSignature().Should().BeTrue(); } public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnTrueForTestMethodsWithoutAsync() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicNonAsyncTaskMethod")!; - Verify(methodInfo.HasCorrectTestInitializeOrCleanupSignature()); + methodInfo.HasCorrectTestInitializeOrCleanupSignature().Should().BeTrue(); } public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnFalseForAsyncTestMethodsWithNonTaskReturnTypes() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicAsyncVoidMethod")!; - Verify(!methodInfo.HasCorrectTestInitializeOrCleanupSignature()); + methodInfo.HasCorrectTestInitializeOrCleanupSignature().Should().BeFalse(); } #endregion @@ -181,61 +183,61 @@ public void HasCorrectTestInitializeOrCleanupSignatureShouldReturnFalseForAsyncT public void HasCorrectTestMethodSignatureShouldReturnFalseForAbstractMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicAbstractMethod")!; - Verify(!methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeFalse(); } public void HasCorrectTestMethodSignatureShouldReturnFalseForStaticMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicStaticMethod")!; - Verify(!methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeFalse(); } public void HasCorrectTestMethodSignatureShouldReturnFalseForGenericMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicGenericMethod")!; - Verify(!methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeFalse(); } public void HasCorrectTestMethodSignatureShouldReturnFalseForNonPublicMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("InternalMethod", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!; - Verify(!methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeFalse(); } public void HasCorrectTestMethodSignatureShouldReturnFalseForMethodsHavingParameters() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethodWithInt")!; - Verify(!methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeFalse(); } public void HasCorrectTestMethodSignatureShouldReturnTrueForMethodsWithParametersWhenParameterCountIsIgnored() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethodWithInt")!; - Verify(methodInfo.HasCorrectTestMethodSignature(true)); + methodInfo.HasCorrectTestMethodSignature(true).Should().BeTrue(); } public void HasCorrectTestMethodSignatureShouldReturnTrueForTestMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethod")!; - Verify(methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeTrue(); } public void HasCorrectTestMethodSignatureShouldReturnTrueForAsyncTestMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicAsyncTaskMethod")!; - Verify(methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeTrue(); } public void HasCorrectTestMethodSignatureShouldReturnTrueForTaskTestMethodsWithoutAsync() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicNonAsyncTaskMethod")!; - Verify(methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeTrue(); } public void HasCorrectTestMethodSignatureShouldReturnFalseForAsyncTestMethodsWithNonTaskReturnTypes() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicAsyncVoidMethod")!; - Verify(!methodInfo.HasCorrectTestMethodSignature(false)); + methodInfo.HasCorrectTestMethodSignature(false).Should().BeFalse(); } #endregion @@ -245,13 +247,13 @@ public void HasCorrectTestMethodSignatureShouldReturnFalseForAsyncTestMethodsWit public void HasCorrectTimeoutShouldReturnFalseForMethodsWithInvalidTimeoutAttribute() { var timeoutAttribute = new TimeoutAttribute(-11); - Verify(!timeoutAttribute.HasCorrectTimeout); + timeoutAttribute.HasCorrectTimeout.Should().BeFalse(); } public void HasCorrectTimeoutShouldReturnTrueForMethodsWithTimeoutAttribute() { var timeoutAttribute = new TimeoutAttribute(11); - Verify(timeoutAttribute.HasCorrectTimeout); + timeoutAttribute.HasCorrectTimeout.Should().BeTrue(); } #endregion @@ -261,31 +263,31 @@ public void HasCorrectTimeoutShouldReturnTrueForMethodsWithTimeoutAttribute() public void IsVoidOrTaskReturnTypeShouldReturnTrueForVoidMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethod")!; - Verify(methodInfo.IsValidReturnType()); + methodInfo.IsValidReturnType().Should().BeTrue(); } public void IsVoidOrTaskReturnTypeShouldReturnTrueForAsyncTaskMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicAsyncTaskMethod")!; - Verify(methodInfo.IsValidReturnType()); + methodInfo.IsValidReturnType().Should().BeTrue(); } public void IsVoidOrTaskReturnTypeShouldReturnTrueForTaskMethodsWithoutAsync() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicNonAsyncTaskMethod")!; - Verify(methodInfo.IsValidReturnType()); + methodInfo.IsValidReturnType().Should().BeTrue(); } public void IsVoidOrTaskReturnTypeShouldReturnFalseForNonVoidMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethodReturningInt")!; - Verify(!methodInfo.IsValidReturnType()); + methodInfo.IsValidReturnType().Should().BeFalse(); } public void IsVoidOrTaskReturnTypeShouldReturnTrueForAsyncNonTaskMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicAsyncVoidMethod")!; - Verify(!methodInfo.IsValidReturnType()); + methodInfo.IsValidReturnType().Should().BeFalse(); } #endregion @@ -295,13 +297,13 @@ public void IsVoidOrTaskReturnTypeShouldReturnTrueForAsyncNonTaskMethods() public void GetAsyncTypeNameShouldReturnNullForVoidMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicMethod")!; - Verify(methodInfo.GetAsyncTypeName() is null); + methodInfo.GetAsyncTypeName().Should().BeNull(); } public void GetAsyncTypeNameShouldReturnStateMachineTypeNameForAsyncMethods() { MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PublicAsyncVoidMethod")!; - Verify(methodInfo.GetAsyncTypeName()!.StartsWith("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass+", StringComparison.Ordinal)); + methodInfo.GetAsyncTypeName()!.Should().StartWith("Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass+"); } #endregion @@ -314,8 +316,8 @@ public void MethodInfoInvokeAsSynchronousTaskWaitsForCompletionOfAMethodWhichRet DummyTestClass2.DummyAsyncMethodBody = (x, y) => Task.Run( () => { - Verify(x == 10); - Verify(y == 20); + x.Should().Be(10); + y.Should().Be(20); testMethodCalled = true; }); @@ -324,7 +326,7 @@ public void MethodInfoInvokeAsSynchronousTaskWaitsForCompletionOfAMethodWhichRet dummyAsyncMethod.InvokeAsSynchronousTask(dummyTestClass, 10, 20); - Verify(testMethodCalled); + testMethodCalled.Should().BeTrue(); } public void MethodInfoInvokeAsSynchronousTaskExecutesAMethodWhichDoesNotReturnATask() @@ -332,8 +334,8 @@ public void MethodInfoInvokeAsSynchronousTaskExecutesAMethodWhichDoesNotReturnAT bool testMethodCalled = false; DummyTestClass2.DummyMethodBody = (x, y) => { - Verify(x == 10); - Verify(y == 20); + x.Should().Be(10); + y.Should().Be(20); testMethodCalled = true; return true; }; @@ -343,7 +345,7 @@ public void MethodInfoInvokeAsSynchronousTaskExecutesAMethodWhichDoesNotReturnAT dummyMethod.InvokeAsSynchronousTask(dummyTestClass, 10, 20); - Verify(testMethodCalled); + testMethodCalled.Should().BeTrue(); } public void InvokeAsSynchronousShouldThrowIfParametersWereExpectedButWereNotProvided() @@ -357,8 +359,8 @@ public void InvokeAsSynchronousShouldThrowIfParametersWereExpectedButWereNotProv } catch (TestFailedException ex) { - Verify(ex.Outcome == UTF.UnitTestOutcome.Error); - Verify(ex.TryGetMessage() == string.Format(CultureInfo.InvariantCulture, Resource.CannotRunTestMethodNoDataError, "Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass2", "PublicMethodWithParameters")); + ex.Outcome.Should().Be(UTF.UnitTestOutcome.Error); + ex.TryGetMessage().Should().Be(string.Format(CultureInfo.InvariantCulture, Resource.CannotRunTestMethodNoDataError, "Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass2", "PublicMethodWithParameters")); } } @@ -382,13 +384,13 @@ public void InvokeAsSynchronousShouldThrowIfParametersWereExpectedButIncorrectCo } catch (TestFailedException ex) { - Verify(ex.Outcome == UTF.UnitTestOutcome.Error); + ex.Outcome.Should().Be(UTF.UnitTestOutcome.Error); // Error in English is: // Cannot run test method 'Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass2.PublicMethodWithParameters': Test data doesn't match method parameters. Either the count or types are different. // Test expected 2 parameter(s), with types 'Int32, Int32', // but received 1 argument(s), with types 'Int32'. - Verify(ex.TryGetMessage() == string.Format(CultureInfo.InvariantCulture, Resource.CannotRunTestArgumentsMismatchError, "Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass2", "PublicMethodWithParameters", + ex.TryGetMessage().Should().Be(string.Format(CultureInfo.InvariantCulture, Resource.CannotRunTestArgumentsMismatchError, "Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass2", "PublicMethodWithParameters", 2, "Int32, Int32", 1, "Int32")); } @@ -405,13 +407,13 @@ public void InvokeAsSynchronousShouldThrowIfParametersWereExpectedButIncorrectTy } catch (TestFailedException ex) { - Verify(ex.Outcome == UTF.UnitTestOutcome.Error); + ex.Outcome.Should().Be(UTF.UnitTestOutcome.Error); // Error in English is: // Cannot run test method 'Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass2.PublicMethodWithParameters': Test data doesn't match method parameters. Either the count or types are different. // Test expected 2 parameter(s), with types 'Int32, Int32', // but received 2 argument(s), with types 'String, String'. - Verify(ex.TryGetMessage() == string.Format(CultureInfo.InvariantCulture, Resource.CannotRunTestArgumentsMismatchError, "Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass2", "PublicMethodWithParameters", + ex.TryGetMessage().Should().Be(string.Format(CultureInfo.InvariantCulture, Resource.CannotRunTestArgumentsMismatchError, "Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Extensions.MethodInfoExtensionsTests+DummyTestClass2", "PublicMethodWithParameters", 2, "Int32, Int32", 2, "String, String")); } @@ -447,8 +449,8 @@ public class DummyTestClass2 public void PublicMethodWithParameters(int x, int y) { - Verify((object)x is not null); - Verify((object)y is not null); + ((object)x).Should().NotBeNull(); + ((object)y).Should().NotBeNull(); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestCaseExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestCaseExtensionsTests.cs index 24f735ad6d..22ac717e4b 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestCaseExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestCaseExtensionsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; @@ -26,12 +28,11 @@ public void ToUnitTestElementShouldReturnUnitTestElementWithFieldsSet() UnitTestElement resultUnitTestElement = testCase.ToUnitTestElementWithUpdatedSource(testCase.Source); - Verify(resultUnitTestElement.Priority == 2); - Verify(testCategories == resultUnitTestElement.TestCategory); - Verify(resultUnitTestElement.TestMethod.DisplayName == "DummyDisplayName"); - Verify(resultUnitTestElement.TestMethod.Name == "DummyMethod"); - Verify(resultUnitTestElement.TestMethod.FullClassName == "DummyClassName"); - Verify(resultUnitTestElement.TestMethod.DeclaringClassFullName is null); + resultUnitTestElement.Priority.Should().Be(2); + resultUnitTestElement.TestCategory.Should().Equal(testCategories); + resultUnitTestElement.TestMethod.Name.Should().Be("DummyMethod"); + resultUnitTestElement.TestMethod.FullClassName.Should().Be("DummyClassName"); + resultUnitTestElement.TestMethod.DeclaringClassFullName.Should().BeNull(); } public void ToUnitTestElementForTestCaseWithNoPropertiesShouldReturnUnitTestElementWithDefaultFields() @@ -42,8 +43,8 @@ public void ToUnitTestElementForTestCaseWithNoPropertiesShouldReturnUnitTestElem UnitTestElement resultUnitTestElement = testCase.ToUnitTestElementWithUpdatedSource(testCase.Source); // These are set for testCase by default by ObjectModel. - Verify(resultUnitTestElement.Priority == 0); - Verify(resultUnitTestElement.TestCategory is null); + resultUnitTestElement.Priority.Should().Be(0); + resultUnitTestElement.TestCategory.Should().BeNull(); } public void ToUnitTestElementShouldAddDeclaringClassNameToTestElementWhenAvailable() @@ -54,7 +55,7 @@ public void ToUnitTestElementShouldAddDeclaringClassNameToTestElementWhenAvailab UnitTestElement resultUnitTestElement = testCase.ToUnitTestElementWithUpdatedSource(testCase.Source); - Verify(resultUnitTestElement.TestMethod.FullClassName == "DummyClassName"); - Verify(resultUnitTestElement.TestMethod.DeclaringClassFullName == "DummyDeclaringClassName"); + resultUnitTestElement.TestMethod.FullClassName.Should().Be("DummyClassName"); + resultUnitTestElement.TestMethod.DeclaringClassFullName.Should().Be("DummyDeclaringClassName"); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestContextExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestContextExtensionsTests.cs index e91d40a89f..4bfe9c1c2a 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestContextExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestContextExtensionsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; @@ -18,7 +20,7 @@ public void GetAndClearDiagnosticMessagesShouldReturnTestContextMessages() mockTestContext.Setup(tc => tc.GetDiagnosticMessages()).Returns("foo"); - Verify(mockTestContext.Object.GetAndClearDiagnosticMessages() == "foo"); + mockTestContext.Object.GetAndClearDiagnosticMessages().Should().Be("foo"); } public void GetAndClearDiagnosticMessagesShouldClearContextMessages() @@ -32,6 +34,6 @@ public void GetAndClearDiagnosticMessagesShouldClearContextMessages() mockTestContext.Object.GetAndClearDiagnosticMessages(); message = "bar"; - Verify(mockTestContext.Object.GetAndClearDiagnosticMessages() == "bar"); + mockTestContext.Object.GetAndClearDiagnosticMessages().Should().Be("bar"); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestResultExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestResultExtensionsTests.cs index 28f878600d..12af2c947f 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestResultExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/TestResultExtensionsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; @@ -19,7 +21,7 @@ public void ToUnitTestResultsForTestResultWithExceptionConvertsToUnitTestResults var result = new TestResult { TestFailureException = new Exception() }; var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.Outcome == VSTestTestOutcome.Failed); + convertedResult.Outcome.Should().Be(VSTestTestOutcome.Failed); } public void ToUnitTestResultsForTestResultWithExceptionConvertsToUnitTestResultsWithInconclusiveOutcome() @@ -27,7 +29,7 @@ public void ToUnitTestResultsForTestResultWithExceptionConvertsToUnitTestResults var result = new TestResult { TestFailureException = new Exception(), Outcome = UTF.UnitTestOutcome.Inconclusive }; var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.Outcome == VSTestTestOutcome.Skipped); + convertedResult.Outcome.Should().Be(VSTestTestOutcome.Skipped); } public void ToUnitTestResultsForTestResultShouldSetLoggingDataForConvertedUnitTestResults() @@ -45,16 +47,16 @@ public void ToUnitTestResultsForTestResultShouldSetLoggingDataForConvertedUnitTe var convertedResult = result.ToTestResult(new() { DisplayName = result.DisplayName }, default, default, string.Empty, new()); VSTestTestResultMessage[] stdOutMessages = [.. convertedResult.Messages.Where(m => m.Category == VSTestTestResultMessage.StandardOutCategory)]; - Verify(stdOutMessages[0].Text == "logOutput"); - Verify(convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardErrorCategory).Text == "logError"); - Verify(convertedResult.DisplayName == "displayName (Data Row 1)"); - Verify(stdOutMessages[1].Text == """ + stdOutMessages[0].Text.Should().Be("logOutput"); + convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardErrorCategory).Text.Should().Be("logError"); + convertedResult.DisplayName.Should().Be("displayName (Data Row 1)"); + stdOutMessages[1].Text.Should().Be(""" Debug Trace: debugTrace """); - Verify(timespan == convertedResult.Duration); + convertedResult.Duration.Should().Be(timespan); } public void ToUnitTestResultsForTestResultShouldSetStandardOut() @@ -66,7 +68,7 @@ public void ToUnitTestResultsForTestResultShouldSetStandardOut() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardOutCategory).Text == "logOutput"); + convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardOutCategory).Text.Should().Be("logOutput"); } public void ToUnitTestResultsForTestResultShouldSetStandardError() @@ -78,7 +80,7 @@ public void ToUnitTestResultsForTestResultShouldSetStandardError() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardErrorCategory).Text == "logError"); + convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardErrorCategory).Text.Should().Be("logError"); } public void ToUnitTestResultsForTestResultShouldSetDebugTrace() @@ -90,7 +92,7 @@ public void ToUnitTestResultsForTestResultShouldSetDebugTrace() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardOutCategory).Text == """ + convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardOutCategory).Text.Should().Be(""" Debug Trace: @@ -107,7 +109,7 @@ public void ToUnitTestResultsForTestResultShouldSetTestContextMessages() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardOutCategory).Text == """ + convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardOutCategory).Text.Should().Be(""" TestContext Messages: @@ -125,7 +127,7 @@ public void ToUnitTestResultsForTestResultShouldSetDuration() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(timespan == convertedResult.Duration); + convertedResult.Duration.Should().Be(timespan); } public void ToUnitTestResultsForTestResultShouldSetDisplayName() @@ -137,7 +139,7 @@ public void ToUnitTestResultsForTestResultShouldSetDisplayName() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.DisplayName == "displayName"); + convertedResult.DisplayName.Should().Be("displayName"); } public void ToUnitTestResultsForTestResultShouldSetDataRowIndex() @@ -149,7 +151,7 @@ public void ToUnitTestResultsForTestResultShouldSetDataRowIndex() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.DisplayName == " (Data Row 1)"); + convertedResult.DisplayName.Should().Be(" (Data Row 1)"); } public void ToUnitTestResultsForTestResultShouldSetParentInfo() @@ -167,9 +169,9 @@ public void ToUnitTestResultsForTestResultShouldSetParentInfo() var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(executionId == (Guid)convertedResult.GetPropertyValue(EngineConstants.ExecutionIdProperty)!); - Verify(parentExecId == (Guid)convertedResult.GetPropertyValue(EngineConstants.ParentExecIdProperty)!); - Verify(innerResultsCount == (int)convertedResult.GetPropertyValue(EngineConstants.InnerResultsCountProperty)!); + ((Guid)convertedResult.GetPropertyValue(EngineConstants.ExecutionIdProperty)!).Should().Be(executionId); + ((Guid)convertedResult.GetPropertyValue(EngineConstants.ParentExecIdProperty)!).Should().Be(parentExecId); + ((int)convertedResult.GetPropertyValue(EngineConstants.InnerResultsCountProperty)!).Should().Be(innerResultsCount); } public void ToUnitTestResultsShouldHaveResultsFileProvidedToTestResult() @@ -180,6 +182,6 @@ public void ToUnitTestResultsShouldHaveResultsFileProvidedToTestResult() var result = new TestResult { ResultFiles = [resultFile] }; var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); - Verify(convertedResult.Attachments[0].Attachments[0].Description == resultFile); + convertedResult.Attachments[0].Attachments[0].Description.Should().Be(resultFile); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs index 86bc0fb6cb..4f551bad5a 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Extensions/UnitTestOutcomeExtensionsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions; using TestFramework.ForTestingMSTest; @@ -17,7 +19,7 @@ public void ToUnitTestOutComeForPassedTestResultsConvertsToPassedUnitTestOutCome UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Passed; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); - Verify(convertedOutcome == AdapterTestOutcome.Passed); + convertedOutcome.Should().Be(AdapterTestOutcome.Passed); } public void ToUnitTestResultsForFailedTestResultsConvertsToFailedUnitTestResults() @@ -25,7 +27,7 @@ public void ToUnitTestResultsForFailedTestResultsConvertsToFailedUnitTestResults UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Failed; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); - Verify(convertedOutcome == AdapterTestOutcome.Failed); + convertedOutcome.Should().Be(AdapterTestOutcome.Failed); } public void ToUnitTestResultsForInProgressTestResultsConvertsToInProgressUnitTestResults() @@ -33,7 +35,7 @@ public void ToUnitTestResultsForInProgressTestResultsConvertsToInProgressUnitTes UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.InProgress; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); - Verify(convertedOutcome == AdapterTestOutcome.InProgress); + convertedOutcome.Should().Be(AdapterTestOutcome.InProgress); } public void ToUnitTestResultsForInconclusiveTestResultsConvertsToInconclusiveUnitTestResults() @@ -41,7 +43,7 @@ public void ToUnitTestResultsForInconclusiveTestResultsConvertsToInconclusiveUni UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Inconclusive; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); - Verify(convertedOutcome == AdapterTestOutcome.Inconclusive); + convertedOutcome.Should().Be(AdapterTestOutcome.Inconclusive); } public void ToUnitTestResultsForTimeoutTestResultsConvertsToTimeoutUnitTestResults() @@ -49,7 +51,7 @@ public void ToUnitTestResultsForTimeoutTestResultsConvertsToTimeoutUnitTestResul UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Timeout; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); - Verify(convertedOutcome == AdapterTestOutcome.Timeout); + convertedOutcome.Should().Be(AdapterTestOutcome.Timeout); } public void ToUnitTestResultsForUnknownTestResultsConvertsToErrorUnitTestResults() @@ -57,30 +59,30 @@ public void ToUnitTestResultsForUnknownTestResultsConvertsToErrorUnitTestResults UnitTestOutcome frameworkOutcome = UTF.UnitTestOutcome.Unknown; var convertedOutcome = frameworkOutcome.ToUnitTestOutcome(); - Verify(convertedOutcome == AdapterTestOutcome.Error); + convertedOutcome.Should().Be(AdapterTestOutcome.Error); } public void GetMoreImportantOutcomeShouldReturnFailIfTwoOutcomesAreFailedAndInconclusive() { UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Failed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Inconclusive); - Verify(resultOutcome == UTF.UnitTestOutcome.Failed); + resultOutcome.Should().Be(UTF.UnitTestOutcome.Failed); } public void GetMoreImportantOutcomeShouldReturnInconclusiveIfTwoOutcomesArePassedAndInconclusive() { UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Passed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Inconclusive); - Verify(resultOutcome == UTF.UnitTestOutcome.Inconclusive); + resultOutcome.Should().Be(UTF.UnitTestOutcome.Inconclusive); } public void GetMoreImportantOutcomeShouldReturnFailedIfTwoOutcomesArePassedAndFailed() { UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Passed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Failed); - Verify(resultOutcome == UTF.UnitTestOutcome.Failed); + resultOutcome.Should().Be(UTF.UnitTestOutcome.Failed); } public void GetMoreImportantOutcomeShouldReturnFailedIfBothOutcomesAreFailed() { UnitTestOutcome resultOutcome = UTF.UnitTestOutcome.Failed.GetMoreImportantOutcome(UTF.UnitTestOutcome.Failed); - Verify(resultOutcome == UTF.UnitTestOutcome.Failed); + resultOutcome.Should().Be(UTF.UnitTestOutcome.Failed); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DataSerializationHelperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DataSerializationHelperTests.cs index 1b7e4aa18e..b4753e5538 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DataSerializationHelperTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DataSerializationHelperTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using TestFramework.ForTestingMSTest; @@ -15,9 +17,9 @@ public void DataSerializerShouldRoundTripDateTimeOffset() object?[]? actual = DataSerializationHelper.Deserialize(DataSerializationHelper.Serialize([source])); - Verify(actual!.Length == 1); - Verify(actual[0]!.GetType() == typeof(DateTimeOffset)); - Verify(actual[0]!.Equals(source)); + actual!.Length.Should().Be(1); + actual[0].Should().BeOfType(); + actual[0]!.Equals(source).Should().BeTrue(); } public void DataSerializerShouldRoundTripDateTime() @@ -26,10 +28,10 @@ public void DataSerializerShouldRoundTripDateTime() object?[]? actual = DataSerializationHelper.Deserialize(DataSerializationHelper.Serialize([source])); - Verify(actual!.Length == 1); - Verify(actual[0]!.GetType() == typeof(DateTime)); - Verify(actual[0]!.Equals(source)); - Verify(((DateTime)actual[0]!).Kind.Equals(source.Kind)); + actual!.Length.Should().Be(1); + actual[0].Should().BeOfType(); + actual[0]!.Equals(source).Should().BeTrue(); + ((DateTime)actual[0]!).Kind.Equals(source.Kind).Should().BeTrue(); } public void DataSerializerShouldRoundTripDateTimeOfKindLocal() @@ -38,10 +40,10 @@ public void DataSerializerShouldRoundTripDateTimeOfKindLocal() object?[]? actual = DataSerializationHelper.Deserialize(DataSerializationHelper.Serialize([source])); - Verify(actual!.Length == 1); - Verify(actual[0]!.GetType() == typeof(DateTime)); - Verify(actual[0]!.Equals(source)); - Verify(((DateTime)actual[0]!).Kind.Equals(source.Kind)); + actual!.Length.Should().Be(1); + actual[0].Should().BeOfType(); + actual[0]!.Equals(source).Should().BeTrue(); + ((DateTime)actual[0]!).Kind.Equals(source.Kind).Should().BeTrue(); } public void DataSerializerShouldRoundTripDateTimeOfKindUtc() @@ -50,10 +52,10 @@ public void DataSerializerShouldRoundTripDateTimeOfKindUtc() object?[]? actual = DataSerializationHelper.Deserialize(DataSerializationHelper.Serialize([source])); - Verify(actual!.Length == 1); - Verify(actual[0]!.GetType() == typeof(DateTime)); - Verify(actual[0]!.Equals(source)); - Verify(((DateTime)actual[0]!).Kind.Equals(source.Kind)); + actual!.Length.Should().Be(1); + actual[0].Should().BeOfType(); + actual[0]!.Equals(source).Should().BeTrue(); + ((DateTime)actual[0]!).Kind.Equals(source.Kind).Should().BeTrue(); } #if NET7_0_OR_GREATER @@ -63,9 +65,9 @@ public void DataSerializerShouldRoundTripDateOnly() object?[]? actual = DataSerializationHelper.Deserialize(DataSerializationHelper.Serialize([source])); - Verify(actual!.Length == 1); - Verify(actual[0]!.GetType() == typeof(DateOnly)); - Verify(actual[0]!.Equals(source)); + actual!.Length.Should().Be(1); + actual[0].Should().BeOfType(); + actual[0]!.Equals(source).Should().BeTrue(); } public void DataSerializerShouldRoundTripTimeOnly() @@ -74,9 +76,9 @@ public void DataSerializerShouldRoundTripTimeOnly() object?[]? actual = DataSerializationHelper.Deserialize(DataSerializationHelper.Serialize([source])); - Verify(actual!.Length == 1); - Verify(actual[0]!.GetType() == typeof(TimeOnly)); - Verify(actual[0]!.Equals(source)); + actual!.Length.Should().Be(1); + actual[0].Should().BeOfType(); + actual[0]!.Equals(source).Should().BeTrue(); } #endif } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DictionaryHelperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DictionaryHelperTests.cs index b358cf4fc6..f90eb502a5 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DictionaryHelperTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/DictionaryHelperTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using TestFramework.ForTestingMSTest; @@ -20,7 +22,7 @@ public void ConcatenatingDictionariesReturnsEmptyDictionaryWhenBothSidesAreNullO actual.ToList().Sort(); expected.ToList().Sort(); - Verify(actual.SequenceEqual(expected)); + actual.SequenceEqual(expected).Should().BeTrue(); } public void ConcatenatingDictionariesReturnsSourceSideWhenOverwriteIsNullOrEmpty() @@ -37,7 +39,7 @@ public void ConcatenatingDictionariesReturnsSourceSideWhenOverwriteIsNullOrEmpty IOrderedEnumerable> sortedActual = from entry in actual orderby entry.Key select entry; IOrderedEnumerable> sortedSource = from entry in source orderby entry.Key select entry; - Verify(sortedActual.SequenceEqual(sortedSource)); + sortedActual.SequenceEqual(sortedSource).Should().BeTrue(); } public void ConcatenatingDictionariesReturnsOverwriteSideWhenSourceIsNullOrEmpty() @@ -54,7 +56,7 @@ public void ConcatenatingDictionariesReturnsOverwriteSideWhenSourceIsNullOrEmpty IOrderedEnumerable> sortedActual = from entry in actual orderby entry.Key select entry; IOrderedEnumerable> sortedOverwrite = from entry in overwrite orderby entry.Key select entry; - Verify(sortedActual.SequenceEqual(sortedOverwrite)); + sortedActual.SequenceEqual(sortedOverwrite).Should().BeTrue(); } public void ConcatenatingDictionariesShouldMergeThemAndTakeDuplicateKeysFromOverwrite() @@ -86,6 +88,6 @@ public void ConcatenatingDictionariesShouldMergeThemAndTakeDuplicateKeysFromOver IOrderedEnumerable> sortedActual = from entry in actual orderby entry.Key select entry; IOrderedEnumerable> sortedExpected = from entry in expected orderby entry.Key select entry; - Verify(sortedActual.SequenceEqual(sortedExpected)); + sortedActual.SequenceEqual(sortedExpected).Should().BeTrue(); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/ReflectHelperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/ReflectHelperTests.cs index f47ee26f08..f77e4c6301 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/ReflectHelperTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/ReflectHelperTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; @@ -51,7 +53,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtClassLevel() string[] expected = ["ClassLevel"]; string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; - Verify(expected.SequenceEqual(actual)); + expected.SequenceEqual(actual).Should().BeTrue(); } /// @@ -67,7 +69,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtAllLevels() string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; string[] expected = ["MethodLevel", "ClassLevel", "AsmLevel1", "AsmLevel2", "AsmLevel3"]; - Verify(expected.SequenceEqual(actual)); + expected.SequenceEqual(actual).Should().BeTrue(); } /// @@ -85,7 +87,7 @@ public void GetTestCategoryAttributeShouldConcatCustomAttributeOfSameType() string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; string[] expected = ["MethodLevel1", "MethodLevel2", "ClassLevel1", "ClassLevel2", "AsmLevel1", "AsmLevel2"]; - Verify(expected.SequenceEqual(actual)); + expected.SequenceEqual(actual).Should().BeTrue(); } /// @@ -99,7 +101,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtAssemblyLevel() string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; - Verify(expected.SequenceEqual(actual)); + expected.SequenceEqual(actual).Should().BeTrue(); } /// @@ -112,7 +114,7 @@ public void GetTestCategoryAttributeShouldIncludeMultipleTestCategoriesAtClassLe string[] expected = ["ClassLevel", "ClassLevel1"]; string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; - Verify(expected.SequenceEqual(actual)); + expected.SequenceEqual(actual).Should().BeTrue(); } /// @@ -124,7 +126,7 @@ public void GetTestCategoryAttributeShouldIncludeMultipleTestCategoriesAtAssembl string[] expected = ["AsmLevel", "AsmLevel1"]; string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; - Verify(expected.SequenceEqual(actual)); + expected.SequenceEqual(actual).Should().BeTrue(); } /// @@ -137,7 +139,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtMethodLevel() string[] expected = ["MethodLevel"]; string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; - Verify(expected.SequenceEqual(actual)); + expected.SequenceEqual(actual).Should().BeTrue(); } public void IsAttributeDefinedShouldReturnTrueIfSpecifiedAttributeIsDefinedOnAMember() @@ -150,7 +152,7 @@ public void IsAttributeDefinedShouldReturnTrueIfSpecifiedAttributeIsDefinedOnAMe Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object)). Returns(attributes); - Verify(rh.IsAttributeDefined(mockMemberInfo.Object)); + rh.IsAttributeDefined(mockMemberInfo.Object).Should().BeTrue(); } public void IsAttributeDefinedShouldReturnFalseIfSpecifiedAttributeIsNotDefinedOnAMember() @@ -163,7 +165,7 @@ public void IsAttributeDefinedShouldReturnFalseIfSpecifiedAttributeIsNotDefinedO Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object)). Returns(attributes); - Verify(!rh.IsAttributeDefined(mockMemberInfo.Object)); + rh.IsAttributeDefined(mockMemberInfo.Object).Should().BeFalse(); } public void IsAttributeDefinedShouldReturnFromCache() @@ -180,10 +182,10 @@ public void IsAttributeDefinedShouldReturnFromCache() Setup(ro => ro.GetCustomAttributes(memberInfo)). Returns(attributes); - Verify(rh.IsAttributeDefined(memberInfo)); + rh.IsAttributeDefined(memberInfo).Should().BeTrue(); // Validate that reflection APIs are not called again. - Verify(rh.IsAttributeDefined(memberInfo)); + rh.IsAttributeDefined(memberInfo).Should().BeTrue(); _testablePlatformServiceProvider.MockReflectionOperations.Verify(ro => ro.GetCustomAttributes(memberInfo), Times.Once); // Also validate that reflection APIs for an individual type is not called since the cache gives us what we need already. @@ -200,7 +202,7 @@ public void HasAttributeDerivedFromShouldReturnTrueIfSpecifiedAttributeIsDefined Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object)). Returns(attributes); - Verify(rh.IsAttributeDefined(mockMemberInfo.Object)); + rh.IsAttributeDefined(mockMemberInfo.Object).Should().BeTrue(); } public void HasAttributeDerivedFromShouldReturnFalseIfSpecifiedAttributeIsNotDefinedOnAMember() @@ -213,7 +215,7 @@ public void HasAttributeDerivedFromShouldReturnFalseIfSpecifiedAttributeIsNotDef Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object)). Returns(attributes); - Verify(!rh.IsAttributeDefined(mockMemberInfo.Object)); + rh.IsAttributeDefined(mockMemberInfo.Object).Should().BeFalse(); } public void HasAttributeDerivedFromShouldReturnFromCache() @@ -230,10 +232,10 @@ public void HasAttributeDerivedFromShouldReturnFromCache() Setup(ro => ro.GetCustomAttributes(memberInfo)). Returns(attributes); - Verify(rh.IsAttributeDefined(memberInfo)); + rh.IsAttributeDefined(memberInfo).Should().BeTrue(); // Validate that reflection APIs are not called again. - Verify(rh.IsAttributeDefined(memberInfo)); + rh.IsAttributeDefined(memberInfo).Should().BeTrue(); _testablePlatformServiceProvider.MockReflectionOperations.Verify(ro => ro.GetCustomAttributes(memberInfo), Times.Once); // Also validate that reflection APIs for an individual type is not called since the cache gives us what we need already. @@ -254,7 +256,7 @@ public void HasAttributeDerivedFromShouldReturnFalseQueryingProvidedAttributesEx Setup(ro => ro.GetCustomAttributes(mockMemberInfo.Object, typeof(TestMethodAttribute))). Returns(attributes); - Verify(!rh.IsAttributeDefined(mockMemberInfo.Object)); + rh.IsAttributeDefined(mockMemberInfo.Object).Should().BeFalse(); } internal class AttributeMockingHelper diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/RunSettingsUtilitiesTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/RunSettingsUtilitiesTests.cs index 3507db1027..e2301915a4 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/RunSettingsUtilitiesTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/RunSettingsUtilitiesTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -13,7 +15,7 @@ public class RunSettingsUtilitiesTests : TestContainer public void GetTestRunParametersReturnsNullOnNullRunSettings() { Dictionary? trp = RunSettingsUtilities.GetTestRunParameters(null); - Verify(trp is null); + trp.Should().BeNull(); } public void GetTestRunParametersReturnsNullWhenNoTestRunParameters() @@ -31,7 +33,7 @@ public void GetTestRunParametersReturnsNullWhenNoTestRunParameters() """; Dictionary? trp = RunSettingsUtilities.GetTestRunParameters(settingsXml); - Verify(trp is null); + trp.Should().BeNull(); } public void GetTestRunParametersReturnsEmptyDictionaryForEmptyTestRunParametersNode() @@ -51,8 +53,7 @@ public void GetTestRunParametersReturnsEmptyDictionaryForEmptyTestRunParametersN """; Dictionary? trp = RunSettingsUtilities.GetTestRunParameters(settingsXml); - Verify(trp is not null); - Verify(trp.Count == 0); + trp.Should().BeEmpty(); } public void GetTestRunParametersReturns1EntryOn1TestRunParameter() @@ -73,12 +74,12 @@ public void GetTestRunParametersReturns1EntryOn1TestRunParameter() """; Dictionary? trp = RunSettingsUtilities.GetTestRunParameters(settingsXml); - Verify(trp is not null); - Verify(trp.Count == 1); + trp.Should().NotBeNull(); + trp.Count.Should().Be(1); // Verify Parameter Values. - Verify(trp.ContainsKey("webAppUrl")); - Verify("http://localhost".Equals(trp["webAppUrl"])); + trp.Should().ContainKey("webAppUrl"); + trp["webAppUrl"].Should().Be("http://localhost"); } public void GetTestRunParametersReturns3EntryOn3TestRunParameter() @@ -101,16 +102,16 @@ public void GetTestRunParametersReturns3EntryOn3TestRunParameter() """; Dictionary? trp = RunSettingsUtilities.GetTestRunParameters(settingsXml); - Verify(trp is not null); - Verify(trp.Count == 3); + trp.Should().NotBeNull(); + trp.Count.Should().Be(3); // Verify Parameter Values. - Verify(trp.ContainsKey("webAppUrl")); - Verify("http://localhost".Equals(trp["webAppUrl"])); - Verify(trp.ContainsKey("webAppUserName")); - Verify("Admin".Equals(trp["webAppUserName"])); - Verify(trp.ContainsKey("webAppPassword")); - Verify("Password".Equals(trp["webAppPassword"])); + trp.Should().ContainKey("webAppUrl"); + trp["webAppUrl"].Should().Be("http://localhost"); + trp.Should().ContainKey("webAppUserName"); + trp["webAppUserName"].Should().Be("Admin"); + trp.Should().ContainKey("webAppPassword"); + trp["webAppPassword"].Should().Be("Password"); } public void GetTestRunParametersThrowsWhenTRPNodeHasAttributes() @@ -130,7 +131,7 @@ public void GetTestRunParametersThrowsWhenTRPNodeHasAttributes() """; - VerifyThrows(() => RunSettingsUtilities.GetTestRunParameters(settingsXml)); + new Action(() => RunSettingsUtilities.GetTestRunParameters(settingsXml)).Should().Throw(); } public void GetTestRunParametersThrowsWhenTRPNodeHasNonParameterTypeChildNodes() @@ -151,7 +152,7 @@ public void GetTestRunParametersThrowsWhenTRPNodeHasNonParameterTypeChildNodes() """; - VerifyThrows(() => RunSettingsUtilities.GetTestRunParameters(settingsXml)); + new Action(() => RunSettingsUtilities.GetTestRunParameters(settingsXml)).Should().Throw(); } public void GetTestRunParametersIgnoresMalformedKeyValues() @@ -172,7 +173,6 @@ public void GetTestRunParametersIgnoresMalformedKeyValues() """; Dictionary? trp = RunSettingsUtilities.GetTestRunParameters(settingsXml); - Verify(trp is not null); - Verify(trp.Count == 0); + trp.Should().BeEmpty(); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/TestDataSourceHelpersTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/TestDataSourceHelpersTests.cs index c470744a70..4bb0f4becb 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/TestDataSourceHelpersTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/TestDataSourceHelpersTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using TestFramework.ForTestingMSTest; @@ -31,16 +33,16 @@ public void TryHandleITestDataRow_WithTestDataRow_ShouldExtractTestCategories() out IList? testCategories); // Assert - Verify(result); - Verify(extractedData != null); - Verify(extractedData.Length == 1); - Verify((string?)extractedData[0] == "test_value"); - Verify(ignoreMessage == "ignore_message"); - Verify(displayName == "display_name"); - Verify(testCategories != null); - Verify(testCategories.Count == 2); - Verify(testCategories.Contains("Category1")); - Verify(testCategories.Contains("Category2")); + result.Should().BeTrue(); + extractedData.Should().NotBeNull(); + extractedData.Length.Should().Be(1); + ((string?)extractedData[0]).Should().Be("test_value"); + ignoreMessage.Should().Be("ignore_message"); + displayName.Should().Be("display_name"); + testCategories.Should().NotBeNull(); + testCategories.Count.Should().Be(2); + testCategories.Should().Contain("Category1"); + testCategories.Should().Contain("Category2"); } public void TryHandleITestDataRow_WithTestDataRowNullCategories_ShouldReturnNullCategories() @@ -60,8 +62,8 @@ public void TryHandleITestDataRow_WithTestDataRowNullCategories_ShouldReturnNull out IList? testCategories); // Assert - Verify(result); - Verify(testCategories == null); + result.Should().BeTrue(); + testCategories.Should().BeNull(); } public void TryHandleITestDataRow_WithNonTestDataRow_ShouldReturnFalseAndNullCategories() @@ -80,11 +82,11 @@ public void TryHandleITestDataRow_WithNonTestDataRow_ShouldReturnFalseAndNullCat out IList? testCategories); // Assert - Verify(!result); - Verify(extractedData == dataArray); - Verify(ignoreMessage == null); - Verify(displayName == null); - Verify(testCategories == null); + result.Should().BeFalse(); + extractedData.Should().BeEquivalentTo(dataArray); + ignoreMessage.Should().BeNull(); + displayName.Should().BeNull(); + testCategories.Should().BeNull(); } public void TryHandleITestDataRow_BackwardCompatibilityOverload_ShouldWork() @@ -108,11 +110,11 @@ public void TryHandleITestDataRow_BackwardCompatibilityOverload_ShouldWork() out string? displayName); // Assert - should work without TestCategories parameter - Verify(result); - Verify(extractedData != null); - Verify(extractedData.Length == 1); - Verify((string?)extractedData[0] == "test_value"); - Verify(ignoreMessage == "ignore_message"); - Verify(displayName == "display_name"); + result.Should().BeTrue(); + extractedData.Should().NotBeNull(); + extractedData.Length.Should().Be(1); + ((string?)extractedData[0]).Should().Be("test_value"); + ignoreMessage.Should().Be("ignore_message"); + displayName.Should().Be("display_name"); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/UnitTestOutcomeHelperTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/UnitTestOutcomeHelperTests.cs index a4600fe44a..e256a8db07 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/UnitTestOutcomeHelperTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Helpers/UnitTestOutcomeHelperTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -32,54 +34,54 @@ public UnitTestOutcomeHelperTests() public void UniTestHelperToTestOutcomeForUnitTestOutcomePassedShouldReturnTestOutcomePassed() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.Passed, _adapterSettings); - Verify(resultOutcome == TestOutcome.Passed); + resultOutcome.Should().Be(TestOutcome.Passed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeFailedShouldReturnTestOutcomeFailed() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.Failed, _adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeErrorShouldReturnTestOutcomeFailed() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.Error, _adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeNotRunnableShouldReturnTestOutcomeFailed() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.NotRunnable, _adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeTimeoutShouldReturnTestOutcomeFailed() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.Timeout, _adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeIgnoredShouldReturnTestOutcomeSkipped() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.Ignored, _adapterSettings); - Verify(resultOutcome == TestOutcome.Skipped); + resultOutcome.Should().Be(TestOutcome.Skipped); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeInconclusiveShouldReturnTestOutcomeSkipped() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.Inconclusive, _adapterSettings); - Verify(resultOutcome == TestOutcome.Skipped); + resultOutcome.Should().Be(TestOutcome.Skipped); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeNotFoundShouldReturnTestOutcomeNotFound() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.NotFound, _adapterSettings); - Verify(resultOutcome == TestOutcome.NotFound); + resultOutcome.Should().Be(TestOutcome.NotFound); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeInProgressShouldReturnTestOutcomeNone() { var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UnitTestOutcome.InProgress, _adapterSettings); - Verify(resultOutcome == TestOutcome.None); + resultOutcome.Should().Be(TestOutcome.None); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs index 85a908d95d..1f54565e18 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestSettingsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; @@ -57,7 +59,7 @@ public void MapInconclusiveToFailedIsByDefaultFalseWhenNotSpecified() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(!adapterSettings.MapInconclusiveToFailed); + adapterSettings.MapInconclusiveToFailed.Should().BeFalse(); } public void MapNotRunnableToFailedIsByDefaultTrueWhenNotSpecified() @@ -72,7 +74,7 @@ public void MapNotRunnableToFailedIsByDefaultTrueWhenNotSpecified() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.MapNotRunnableToFailed); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); } public void MapInconclusiveToFailedShouldBeConsumedFromRunSettingsWhenSpecified() @@ -88,7 +90,7 @@ public void MapInconclusiveToFailedShouldBeConsumedFromRunSettingsWhenSpecified( MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.MapInconclusiveToFailed); + adapterSettings.MapInconclusiveToFailed.Should().BeTrue(); } public void RunSettings_WithInvalidValues_GettingAWarningForEachInvalidSetting() @@ -151,7 +153,7 @@ public void MapNotRunnableToFailedShouldBeConsumedFromRunSettingsWhenSpecified() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.MapNotRunnableToFailed); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); } public void TestSettingsFileIsByDefaultNullWhenNotSpecified() @@ -166,7 +168,7 @@ public void TestSettingsFileIsByDefaultNullWhenNotSpecified() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object)!; - Verify(adapterSettings.TestSettingsFile is null); + adapterSettings.TestSettingsFile.Should().BeNull(); } public void TestSettingsFileShouldNotBeNullWhenSpecifiedInRunSettings() @@ -182,7 +184,7 @@ public void TestSettingsFileShouldNotBeNullWhenSpecifiedInRunSettings() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object)!; - Verify(adapterSettings.TestSettingsFile is not null); + adapterSettings.TestSettingsFile.Should().NotBeNull(); } public void EnableBaseClassTestMethodsFromOtherAssembliesIsByDefaulTrueWhenNotSpecified() @@ -197,7 +199,7 @@ public void EnableBaseClassTestMethodsFromOtherAssembliesIsByDefaulTrueWhenNotSp MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); } public void EnableBaseClassTestMethodsFromOtherAssembliesShouldBeConsumedFromRunSettingsWhenSpecified() @@ -213,7 +215,7 @@ public void EnableBaseClassTestMethodsFromOtherAssembliesShouldBeConsumedFromRun MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); } public void CaptureDebugTracesShouldBeTrueByDefault() @@ -228,7 +230,7 @@ public void CaptureDebugTracesShouldBeTrueByDefault() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.CaptureDebugTraces); + adapterSettings.CaptureDebugTraces.Should().BeTrue(); } public void CaptureDebugTracesShouldBeConsumedFromRunSettingsWhenSpecified() @@ -244,7 +246,7 @@ public void CaptureDebugTracesShouldBeConsumedFromRunSettingsWhenSpecified() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(!adapterSettings.CaptureDebugTraces); + adapterSettings.CaptureDebugTraces.Should().BeFalse(); } public void TestTimeoutShouldBeConsumedFromRunSettingsWhenSpecified() @@ -260,7 +262,7 @@ public void TestTimeoutShouldBeConsumedFromRunSettingsWhenSpecified() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.TestTimeout == 4000); + adapterSettings.TestTimeout.Should().Be(4000); } public void TestTimeoutShouldBeSetToZeroIfNotSpecifiedInRunSettings() @@ -275,7 +277,7 @@ public void TestTimeoutShouldBeSetToZeroIfNotSpecifiedInRunSettings() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.TestTimeout == 0); + adapterSettings.TestTimeout.Should().Be(0); } public void TreatDiscoveryWarningsAsErrorsShouldBeTrueByDefault() @@ -290,7 +292,7 @@ public void TreatDiscoveryWarningsAsErrorsShouldBeTrueByDefault() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.TreatDiscoveryWarningsAsErrors); + adapterSettings.TreatDiscoveryWarningsAsErrors.Should().BeTrue(); } public void TreatDiscoveryWarningsAsErrorsShouldBeConsumedFromRunSettingsWhenSpecified() @@ -306,7 +308,7 @@ public void TreatDiscoveryWarningsAsErrorsShouldBeConsumedFromRunSettingsWhenSpe MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.TreatDiscoveryWarningsAsErrors); + adapterSettings.TreatDiscoveryWarningsAsErrors.Should().BeTrue(); } public void ParallelizationSettingsShouldNotBeSetByDefault() @@ -321,8 +323,8 @@ public void ParallelizationSettingsShouldNotBeSetByDefault() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(!adapterSettings.ParallelizationWorkers.HasValue); - Verify(!adapterSettings.ParallelizationScope.HasValue); + adapterSettings.ParallelizationWorkers.HasValue.Should().BeFalse(); + adapterSettings.ParallelizationScope.HasValue.Should().BeFalse(); } public void GetSettingsShouldThrowIfParallelizationWorkersIsNotInt() @@ -338,9 +340,10 @@ public void GetSettingsShouldThrowIfParallelizationWorkersIsNotInt() """; - AdapterSettingsException exception = VerifyThrows(() => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)); + Action act = () => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object); + AdapterSettingsException exception = act.Should().Throw().Which; - Verify(exception.Message.Contains("Invalid value 'GoneFishing' specified for 'Workers'. The value should be a non-negative integer.")); + exception.Message.Should().Contain("Invalid value 'GoneFishing' specified for 'Workers'. The value should be a non-negative integer."); } public void GetSettingsShouldThrowIfParallelizationWorkersIsNegative() @@ -356,8 +359,9 @@ public void GetSettingsShouldThrowIfParallelizationWorkersIsNegative() """; - AdapterSettingsException exception = VerifyThrows(() => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)); - Verify(exception.Message.Contains("Invalid value '-1' specified for 'Workers'. The value should be a non-negative integer.")); + Action act = () => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object); + AdapterSettingsException exception = act.Should().Throw().Which; + exception.Message.Should().Contain("Invalid value '-1' specified for 'Workers'. The value should be a non-negative integer."); } public void ParallelizationWorkersShouldBeConsumedFromRunSettingsWhenSpecified() @@ -375,7 +379,7 @@ public void ParallelizationWorkersShouldBeConsumedFromRunSettingsWhenSpecified() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.ParallelizationWorkers == 2); + adapterSettings.ParallelizationWorkers.Should().Be(2); } public void ParallelizationWorkersShouldBeSetToProcessorCountWhenSetToZero() @@ -393,7 +397,7 @@ public void ParallelizationWorkersShouldBeSetToProcessorCountWhenSetToZero() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(Environment.ProcessorCount == adapterSettings.ParallelizationWorkers); + adapterSettings.ParallelizationWorkers.Should().Be(Environment.ProcessorCount); } public void ParallelizationSettingsShouldBeSetToDefaultsWhenNotSet() @@ -410,8 +414,8 @@ public void ParallelizationSettingsShouldBeSetToDefaultsWhenNotSet() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(Environment.ProcessorCount == adapterSettings.ParallelizationWorkers); - Verify(adapterSettings.ParallelizationScope == ExecutionScope.ClassLevel); + adapterSettings.ParallelizationWorkers.Should().Be(Environment.ProcessorCount); + adapterSettings.ParallelizationScope.Should().Be(ExecutionScope.ClassLevel); } public void ParallelizationSettingsShouldBeSetToDefaultsOnAnEmptyParalleizeSetting() @@ -427,8 +431,8 @@ public void ParallelizationSettingsShouldBeSetToDefaultsOnAnEmptyParalleizeSetti MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(Environment.ProcessorCount == adapterSettings.ParallelizationWorkers); - Verify(adapterSettings.ParallelizationScope == ExecutionScope.ClassLevel); + adapterSettings.ParallelizationWorkers.Should().Be(Environment.ProcessorCount); + adapterSettings.ParallelizationScope.Should().Be(ExecutionScope.ClassLevel); } public void ParallelizationSettingsShouldBeConsumedFromRunSettingsWhenSpecified() @@ -447,8 +451,8 @@ public void ParallelizationSettingsShouldBeConsumedFromRunSettingsWhenSpecified( MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.ParallelizationWorkers == 127); - Verify(adapterSettings.ParallelizationScope == ExecutionScope.MethodLevel); + adapterSettings.ParallelizationWorkers.Should().Be(127); + adapterSettings.ParallelizationScope.Should().Be(ExecutionScope.MethodLevel); } public void GetSettingsShouldThrowIfParallelizationScopeIsNotValid() @@ -464,8 +468,9 @@ public void GetSettingsShouldThrowIfParallelizationScopeIsNotValid() """; - AdapterSettingsException exception = VerifyThrows(() => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)); - Verify(exception.Message.Contains("Invalid value 'JustParallelizeWillYou' specified for 'Scope'. Supported scopes are ClassLevel, MethodLevel.")); + Action act = () => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object); + AdapterSettingsException exception = act.Should().Throw().Which; + exception.Message.Should().Contain("Invalid value 'JustParallelizeWillYou' specified for 'Scope'. Supported scopes are ClassLevel, MethodLevel."); } public void ParallelizationScopeShouldBeConsumedFromRunSettingsWhenSpecified() @@ -483,7 +488,7 @@ public void ParallelizationScopeShouldBeConsumedFromRunSettingsWhenSpecified() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.ParallelizationScope == ExecutionScope.MethodLevel); + adapterSettings.ParallelizationScope.Should().Be(ExecutionScope.MethodLevel); } public void GetSettingsShouldThrowWhenParallelizeHasInvalidElements() @@ -499,8 +504,9 @@ public void GetSettingsShouldThrowWhenParallelizeHasInvalidElements() """; - AdapterSettingsException exception = VerifyThrows(() => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)); - Verify(exception.Message.Contains("MSTestAdapter encountered an unexpected element 'Hola' in its settings 'Parallelize'. Remove this element and try again.")); + Action act = () => MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object); + AdapterSettingsException exception = act.Should().Throw().Which; + exception.Message.Should().Contain("MSTestAdapter encountered an unexpected element 'Hola' in its settings 'Parallelize'. Remove this element and try again."); } public void GetSettingsShouldBeAbleToReadAfterParallelizationSettings() @@ -518,7 +524,7 @@ public void GetSettingsShouldBeAbleToReadAfterParallelizationSettings() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.TestSettingsFile is not null); + adapterSettings.TestSettingsFile.Should().NotBeNull(); } public void GetSettingsShouldBeAbleToReadAfterParallelizationSettingsWithData() @@ -538,9 +544,9 @@ public void GetSettingsShouldBeAbleToReadAfterParallelizationSettingsWithData() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.TestSettingsFile is not null); - Verify(adapterSettings.ParallelizationWorkers == 127); - Verify(adapterSettings.ParallelizationScope == ExecutionScope.MethodLevel); + adapterSettings.TestSettingsFile.Should().NotBeNull(); + adapterSettings.ParallelizationWorkers.Should().Be(127); + adapterSettings.ParallelizationScope.Should().Be(ExecutionScope.MethodLevel); } public void GetSettingsShouldBeAbleToReadAfterParallelizationSettingsOnEmptyParallelizationNode() @@ -557,7 +563,7 @@ public void GetSettingsShouldBeAbleToReadAfterParallelizationSettingsOnEmptyPara MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; - Verify(adapterSettings.TestSettingsFile is not null); + adapterSettings.TestSettingsFile.Should().NotBeNull(); } public void DisableParallelizationShouldBeFalseByDefault() @@ -572,7 +578,7 @@ public void DisableParallelizationShouldBeFalseByDefault() _mockRunSettings.Setup(rs => rs.SettingsXml).Returns(runSettingsXml); MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); - Verify(!MSTestSettings.CurrentSettings.DisableParallelization); + MSTestSettings.CurrentSettings.DisableParallelization.Should().BeFalse(); _mockMessageLogger.Verify(lm => lm.SendMessage(TestMessageLevel.Warning, It.IsAny()), Times.Never); } @@ -591,7 +597,7 @@ public void DisableParallelizationShouldBeConsumedFromRunSettingsWhenSpecified() _mockRunSettings.Setup(rs => rs.SettingsXml).Returns(runSettingsXml); MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); - Verify(MSTestSettings.CurrentSettings.DisableParallelization); + MSTestSettings.CurrentSettings.DisableParallelization.Should().BeTrue(); } public void DisableParallelization_WithInvalidValue_GettingAWarning() @@ -660,7 +666,7 @@ public void GetSettingsShouldOnlyPassTheElementSubTreeToPlatformService() }); MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object); - Verify(expectedRunSettingXml == observedXml); + (expectedRunSettingXml == observedXml).Should().BeTrue(); } public void GetSettingsShouldBeAbleToReadSettingsAfterThePlatformServiceReadsItsSettings() @@ -709,10 +715,10 @@ public void GetSettingsShouldBeAbleToReadSettingsAfterThePlatformServiceReadsIts MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object)!; // Assert. - Verify(dummyPlatformSpecificSetting); - Verify(adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.TestSettingsFile == "DummyPath\\\\TestSettings1.testsettings"); + dummyPlatformSpecificSetting.Should().BeTrue(); + adapterSettings.MapInconclusiveToFailed.Should().BeTrue(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.TestSettingsFile.Should().Be("DummyPath\\\\TestSettings1.testsettings"); } public void GetSettingsShouldBeAbleToReadSettingsIfThePlatformServiceDoesNotUnderstandASetting() @@ -763,11 +769,11 @@ public void GetSettingsShouldBeAbleToReadSettingsIfThePlatformServiceDoesNotUnde MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object)!; // Assert. - Verify(dummyPlatformSpecificSetting); - Verify(adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(adapterSettings.TestSettingsFile == "DummyPath\\\\TestSettings1.testsettings"); + dummyPlatformSpecificSetting.Should().BeTrue(); + adapterSettings.MapInconclusiveToFailed.Should().BeTrue(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + adapterSettings.TestSettingsFile.Should().Be("DummyPath\\\\TestSettings1.testsettings"); } public void GetSettingsShouldOnlyReadTheAdapterSection() @@ -813,7 +819,7 @@ public void GetSettingsShouldOnlyReadTheAdapterSection() MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object); // Assert. - Verify(!outOfScopeCall); + outOfScopeCall.Should().BeFalse(); } public void GetSettingsShouldWorkIfThereAreCommentsInTheXML() @@ -866,10 +872,10 @@ public void GetSettingsShouldWorkIfThereAreCommentsInTheXML() MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object)!; // Assert. - Verify(dummyPlatformSpecificSetting); - Verify(adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); + dummyPlatformSpecificSetting.Should().BeTrue(); + adapterSettings.MapInconclusiveToFailed.Should().BeTrue(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); } #endregion @@ -881,10 +887,10 @@ public void CurrentSettingShouldReturnDefaultSettingsIfNotSet() MSTestSettings.Reset(); MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; - Verify(adapterSettings is not null); + adapterSettings.Should().NotBeNull(); // Validating the default value of a random setting. - Verify(!adapterSettings.MapInconclusiveToFailed); + adapterSettings.MapInconclusiveToFailed.Should().BeFalse(); } public void CurrentSettingShouldReturnCachedLoadedSettings() @@ -905,10 +911,10 @@ public void CurrentSettingShouldReturnCachedLoadedSettings() MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; MSTestSettings adapterSettings2 = MSTestSettings.CurrentSettings; - Verify(adapterSettings is not null); - Verify(!string.IsNullOrEmpty(adapterSettings.TestSettingsFile)); + adapterSettings.Should().NotBeNull(); + adapterSettings.TestSettingsFile.Should().NotBeNullOrEmpty(); - Verify(adapterSettings == adapterSettings2); + (adapterSettings == adapterSettings2).Should().BeTrue(); } #endregion @@ -934,11 +940,11 @@ public void PopulateSettingsShouldFillInSettingsFromSettingsObject() MSTestSettings.PopulateSettings(settings); - Verify(!MSTestSettings.CurrentSettings.CaptureDebugTraces); - Verify(MSTestSettings.CurrentSettings.MapInconclusiveToFailed); - Verify(MSTestSettings.CurrentSettings.MapNotRunnableToFailed); - Verify(MSTestSettings.CurrentSettings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(!string.IsNullOrEmpty(MSTestSettings.CurrentSettings.TestSettingsFile)); + MSTestSettings.CurrentSettings.CaptureDebugTraces.Should().BeFalse(); + MSTestSettings.CurrentSettings.MapInconclusiveToFailed.Should().BeTrue(); + MSTestSettings.CurrentSettings.MapNotRunnableToFailed.Should().BeTrue(); + MSTestSettings.CurrentSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + MSTestSettings.CurrentSettings.TestSettingsFile.Should().NotBeNullOrEmpty(); } public void PopulateSettingsShouldInitializeDefaultAdapterSettingsWhenDiscoveryContextIsNull() @@ -946,11 +952,11 @@ public void PopulateSettingsShouldInitializeDefaultAdapterSettingsWhenDiscoveryC MSTestSettings.PopulateSettings(null, _mockMessageLogger.Object, null); MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; - Verify(adapterSettings.CaptureDebugTraces); - Verify(!adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(adapterSettings.TreatDiscoveryWarningsAsErrors); + adapterSettings.CaptureDebugTraces.Should().BeTrue(); + adapterSettings.MapInconclusiveToFailed.Should().BeFalse(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + adapterSettings.TreatDiscoveryWarningsAsErrors.Should().BeTrue(); } public void PopulateSettingsShouldInitializeDefaultSettingsWhenRunSettingsIsNull() @@ -958,11 +964,11 @@ public void PopulateSettingsShouldInitializeDefaultSettingsWhenRunSettingsIsNull MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; - Verify(adapterSettings.CaptureDebugTraces); - Verify(!adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(adapterSettings.TreatDiscoveryWarningsAsErrors); + adapterSettings.CaptureDebugTraces.Should().BeTrue(); + adapterSettings.MapInconclusiveToFailed.Should().BeFalse(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + adapterSettings.TreatDiscoveryWarningsAsErrors.Should().BeTrue(); } public void PopulateSettingsShouldInitializeDefaultSettingsWhenRunSettingsXmlIsEmpty() @@ -971,11 +977,11 @@ public void PopulateSettingsShouldInitializeDefaultSettingsWhenRunSettingsXmlIsE MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; - Verify(adapterSettings.CaptureDebugTraces); - Verify(!adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(adapterSettings.TreatDiscoveryWarningsAsErrors); + adapterSettings.CaptureDebugTraces.Should().BeTrue(); + adapterSettings.MapInconclusiveToFailed.Should().BeFalse(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + adapterSettings.TreatDiscoveryWarningsAsErrors.Should().BeTrue(); } public void PopulateSettingsShouldInitializeSettingsToDefaultIfNotSpecified() @@ -995,10 +1001,10 @@ public void PopulateSettingsShouldInitializeSettingsToDefaultIfNotSpecified() MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; - Verify(adapterSettings is not null); + adapterSettings.Should().NotBeNull(); // Validating the default value of a random setting. - Verify(!adapterSettings.MapInconclusiveToFailed); + adapterSettings.MapInconclusiveToFailed.Should().BeFalse(); } public void PopulateSettingsShouldInitializeSettingsFromMSTestSection() @@ -1021,12 +1027,12 @@ public void PopulateSettingsShouldInitializeSettingsFromMSTestSection() MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; - Verify(adapterSettings is not null); + adapterSettings.Should().NotBeNull(); - Verify(adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(!string.IsNullOrEmpty(adapterSettings.TestSettingsFile)); + adapterSettings.MapInconclusiveToFailed.Should().BeTrue(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + adapterSettings.TestSettingsFile.Should().NotBeNullOrEmpty(); } public void PopulateSettingsShouldInitializeSettingsFromMSTestV2Section() @@ -1049,12 +1055,12 @@ public void PopulateSettingsShouldInitializeSettingsFromMSTestV2Section() MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; - Verify(adapterSettings is not null); + adapterSettings.Should().NotBeNull(); - Verify(adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(!string.IsNullOrEmpty(adapterSettings.TestSettingsFile)); + adapterSettings.MapInconclusiveToFailed.Should().BeTrue(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + adapterSettings.TestSettingsFile.Should().NotBeNullOrEmpty(); } public void PopulateSettingsShouldInitializeSettingsFromMSTestV2OverMSTestV1Section() @@ -1080,13 +1086,13 @@ public void PopulateSettingsShouldInitializeSettingsFromMSTestV2OverMSTestV1Sect MSTestSettings adapterSettings = MSTestSettings.CurrentSettings; - Verify(adapterSettings is not null); + adapterSettings.Should().NotBeNull(); - Verify(adapterSettings.MapInconclusiveToFailed); - Verify(adapterSettings.MapNotRunnableToFailed); - Verify(adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(adapterSettings.CaptureDebugTraces); - Verify(string.IsNullOrEmpty(adapterSettings.TestSettingsFile)); + adapterSettings.MapInconclusiveToFailed.Should().BeTrue(); + adapterSettings.MapNotRunnableToFailed.Should().BeTrue(); + adapterSettings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + adapterSettings.CaptureDebugTraces.Should().BeTrue(); + adapterSettings.TestSettingsFile.Should().BeNullOrEmpty(); } #endregion @@ -1096,7 +1102,7 @@ public void PopulateSettingsShouldInitializeSettingsFromMSTestV2OverMSTestV1Sect public void IsLegacyScenarioReturnsFalseWhenDiscoveryContextIsNull() { MSTestSettings.PopulateSettings(null, _mockMessageLogger.Object, null); - Verify(!MSTestSettings.IsLegacyScenario(null!)); + MSTestSettings.IsLegacyScenario(null!).Should().BeFalse(); } public void IsLegacyScenarioReturnsFalseWhenTestSettingsFileIsNotGiven() @@ -1112,7 +1118,7 @@ public void IsLegacyScenarioReturnsFalseWhenTestSettingsFileIsNotGiven() _mockDiscoveryContext.Setup(dc => dc.RunSettings).Returns(_mockRunSettings.Object); _mockRunSettings.Setup(rs => rs.SettingsXml).Returns(runSettingsXml); MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); - Verify(!MSTestSettings.IsLegacyScenario(_mockMessageLogger.Object)); + MSTestSettings.IsLegacyScenario(_mockMessageLogger.Object).Should().BeFalse(); } public void IsLegacyScenarioReturnsTrueWhenTestSettingsFileIsGiven() @@ -1128,7 +1134,7 @@ public void IsLegacyScenarioReturnsTrueWhenTestSettingsFileIsGiven() _mockDiscoveryContext.Setup(dc => dc.RunSettings).Returns(_mockRunSettings.Object); _mockRunSettings.Setup(rs => rs.SettingsXml).Returns(runSettingsXml); MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); - Verify(MSTestSettings.IsLegacyScenario(_mockMessageLogger.Object)); + MSTestSettings.IsLegacyScenario(_mockMessageLogger.Object).Should().BeTrue(); } public void LegacyScenariosNotSupportedWarningIsPrintedWhenVsmdiFileIsGiven() @@ -1144,7 +1150,7 @@ public void LegacyScenariosNotSupportedWarningIsPrintedWhenVsmdiFileIsGiven() _mockDiscoveryContext.Setup(dc => dc.RunSettings).Returns(_mockRunSettings.Object); _mockRunSettings.Setup(rs => rs.SettingsXml).Returns(runSettingsXml); MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); - Verify(MSTestSettings.IsLegacyScenario(_mockMessageLogger.Object)); + MSTestSettings.IsLegacyScenario(_mockMessageLogger.Object).Should().BeTrue(); _mockMessageLogger.Verify(logger => logger.SendMessage(TestMessageLevel.Warning, Resource.LegacyScenariosNotSupportedWarning), Times.Once); } @@ -1153,6 +1159,7 @@ public void LegacyScenariosNotSupportedWarningIsPrintedWhenVsmdiFileIsGiven() #region ConfigJson public void ConfigJson_WithInvalidValues_GettingAWarningForEachInvalidSetting() { + // Arrange - setting up invalid configuration values var configDictionary = new Dictionary { { "mstest:timeout:assemblyInitialize", "timeout" }, @@ -1231,27 +1238,27 @@ public void ConfigJson_WithValidValues_ValuesAreSetCorrectly() MSTestSettings.SetSettingsFromConfig(mockConfig.Object, _mockMessageLogger.Object, settings); // Assert - Verify(settings.EnableBaseClassTestMethodsFromOtherAssemblies); - Verify(settings.OrderTestsByNameInClass); - Verify(settings.CaptureDebugTraces); - Verify(settings.CooperativeCancellationTimeout); - Verify(settings.MapInconclusiveToFailed); - Verify(settings.MapNotRunnableToFailed); - Verify(settings.TreatDiscoveryWarningsAsErrors); - Verify(settings.ConsiderEmptyDataSourceAsInconclusive); - Verify(settings.ConsiderFixturesAsSpecialTests); - - Verify(settings.TestTimeout == 60); - Verify(settings.AssemblyInitializeTimeout == 300); - Verify(settings.AssemblyCleanupTimeout == 300); - Verify(settings.ClassInitializeTimeout == 200); - Verify(settings.ClassCleanupTimeout == 200); - Verify(settings.TestInitializeTimeout == 100); - Verify(settings.TestCleanupTimeout == 100); - - Verify(!settings.DisableParallelization); - Verify(settings.ParallelizationWorkers == 4); - Verify(settings.ParallelizationScope == ExecutionScope.ClassLevel); + settings.EnableBaseClassTestMethodsFromOtherAssemblies.Should().BeTrue(); + settings.OrderTestsByNameInClass.Should().BeTrue(); + settings.CaptureDebugTraces.Should().BeTrue(); + settings.CooperativeCancellationTimeout.Should().BeTrue(); + settings.MapInconclusiveToFailed.Should().BeTrue(); + settings.MapNotRunnableToFailed.Should().BeTrue(); + settings.TreatDiscoveryWarningsAsErrors.Should().BeTrue(); + settings.ConsiderEmptyDataSourceAsInconclusive.Should().BeTrue(); + settings.ConsiderFixturesAsSpecialTests.Should().BeTrue(); + + settings.TestTimeout.Should().Be(60); + settings.AssemblyInitializeTimeout.Should().Be(300); + settings.AssemblyCleanupTimeout.Should().Be(300); + settings.ClassInitializeTimeout.Should().Be(200); + settings.ClassCleanupTimeout.Should().Be(200); + settings.TestInitializeTimeout.Should().Be(100); + settings.TestCleanupTimeout.Should().Be(100); + + settings.DisableParallelization.Should().BeFalse(); + settings.ParallelizationWorkers.Should().Be(4); + settings.ParallelizationScope.Should().Be(ExecutionScope.ClassLevel); } public void ConfigJson_Parllelism_Enabled_True() => ConfigJson_Parllelism_Enabled_Core(true); @@ -1278,9 +1285,9 @@ private void ConfigJson_Parllelism_Enabled_Core(bool parallelismEnabled) MSTestSettings.SetSettingsFromConfig(mockConfig.Object, _mockMessageLogger.Object, settings); // Assert - Verify(settings.DisableParallelization == !parallelismEnabled); - Verify(settings.ParallelizationWorkers == 4); - Verify(settings.ParallelizationScope == ExecutionScope.ClassLevel); + settings.DisableParallelization.Should().Be(!parallelismEnabled); + settings.ParallelizationWorkers.Should().Be(4); + settings.ParallelizationScope.Should().Be(ExecutionScope.ClassLevel); } public void ConfigJson_WithValidValues_MethodScope() @@ -1298,7 +1305,7 @@ public void ConfigJson_WithValidValues_MethodScope() MSTestSettings.SetSettingsFromConfig(mockConfig.Object, _mockMessageLogger.Object, settings); // Assert - Verify(settings.ParallelizationScope == ExecutionScope.MethodLevel); + settings.ParallelizationScope.Should().Be(ExecutionScope.MethodLevel); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs index 3d722b0347..f3783e33e5 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestElementTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -24,8 +26,11 @@ public UnitTestElementTests() #region Ctor tests - public void UnitTestElementConstructorShouldThrowIfTestMethodIsNull() => - VerifyThrows(() => _ = new UnitTestElement(null!)); + public void UnitTestElementConstructorShouldThrowIfTestMethodIsNull() + { + Action action = () => _ = new UnitTestElement(null!); + action.Should().Throw(); + } #endregion @@ -35,28 +40,28 @@ public void ToTestCaseShouldSetFullyQualifiedName() { var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.FullyQualifiedName == "C.M"); + testCase.FullyQualifiedName.Should().Be("C.M"); } public void ToTestCaseShouldSetExecutorUri() { var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.ExecutorUri == EngineConstants.ExecutorUri); + testCase.ExecutorUri.Should().Be(EngineConstants.ExecutorUri); } public void ToTestCaseShouldSetAssemblyName() { var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.Source == "A"); + testCase.Source.Should().Be("A"); } public void ToTestCaseShouldSetDisplayName() { var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.DisplayName == "M"); + testCase.DisplayName.Should().Be("M"); } public void ToTestCaseShouldSetDisplayNameIfPresent() @@ -64,14 +69,14 @@ public void ToTestCaseShouldSetDisplayNameIfPresent() _unitTestElement.TestMethod.DisplayName = "Display Name"; var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.DisplayName == "Display Name"); + testCase.DisplayName.Should().Be("Display Name"); } public void ToTestCaseShouldSetTestClassNameProperty() { var testCase = _unitTestElement.ToTestCase(); - Verify((testCase.GetPropertyValue(EngineConstants.TestClassNameProperty) as string) == "C"); + (testCase.GetPropertyValue(EngineConstants.TestClassNameProperty) as string).Should().Be("C"); } public void ToTestCaseShouldSetDeclaringClassNameIfPresent() @@ -79,12 +84,12 @@ public void ToTestCaseShouldSetDeclaringClassNameIfPresent() _testMethod.DeclaringClassFullName = null; var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(EngineConstants.DeclaringClassNameProperty) is null); + testCase.GetPropertyValue(EngineConstants.DeclaringClassNameProperty).Should().BeNull(); _testMethod.DeclaringClassFullName = "DC"; testCase = _unitTestElement.ToTestCase(); - Verify((testCase.GetPropertyValue(EngineConstants.DeclaringClassNameProperty) as string) == "DC"); + (testCase.GetPropertyValue(EngineConstants.DeclaringClassNameProperty) as string).Should().Be("DC"); } public void ToTestCaseShouldSetTestCategoryIfPresent() @@ -92,17 +97,17 @@ public void ToTestCaseShouldSetTestCategoryIfPresent() _unitTestElement.TestCategory = null; var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(EngineConstants.TestCategoryProperty) is null); + testCase.GetPropertyValue(EngineConstants.TestCategoryProperty).Should().BeNull(); _unitTestElement.TestCategory = []; testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(EngineConstants.TestCategoryProperty) is null); + testCase.GetPropertyValue(EngineConstants.TestCategoryProperty).Should().BeNull(); _unitTestElement.TestCategory = ["TC"]; testCase = _unitTestElement.ToTestCase(); - Verify(new string[] { "TC" }.SequenceEqual((string[])testCase.GetPropertyValue(EngineConstants.TestCategoryProperty)!)); + new string[] { "TC" }.SequenceEqual((string[])testCase.GetPropertyValue(EngineConstants.TestCategoryProperty)!).Should().BeTrue(); } public void ToTestCaseShouldSetPriorityIfPresent() @@ -110,12 +115,12 @@ public void ToTestCaseShouldSetPriorityIfPresent() _unitTestElement.Priority = null; var testCase = _unitTestElement.ToTestCase(); - Verify((int)testCase.GetPropertyValue(EngineConstants.PriorityProperty)! == 0); + ((int)testCase.GetPropertyValue(EngineConstants.PriorityProperty)!).Should().Be(0); _unitTestElement.Priority = 1; testCase = _unitTestElement.ToTestCase(); - Verify((int)testCase.GetPropertyValue(EngineConstants.PriorityProperty)! == 1); + ((int)testCase.GetPropertyValue(EngineConstants.PriorityProperty)!).Should().Be(1); } public void ToTestCaseShouldSetTraitsIfPresent() @@ -124,16 +129,16 @@ public void ToTestCaseShouldSetTraitsIfPresent() var testCase = _unitTestElement.ToTestCase(); #pragma warning disable CA1827 // Do not use Count() or LongCount() when Any() can be used - Verify(testCase.Traits.Count() == 0); + testCase.Traits.Count().Should().Be(0); #pragma warning restore CA1827 // Do not use Count() or LongCount() when Any() can be used var trait = new Trait("trait", "value"); _unitTestElement.Traits = [trait]; testCase = _unitTestElement.ToTestCase(); - Verify(testCase.Traits.Count() == 1); - Verify(testCase.Traits.ToArray()[0].Name == "trait"); - Verify(testCase.Traits.ToArray()[0].Value == "value"); + testCase.Traits.Count().Should().Be(1); + testCase.Traits.ToArray()[0].Name.Should().Be("trait"); + testCase.Traits.ToArray()[0].Value.Should().Be("value"); } public void ToTestCaseShouldSetPropertiesIfPresent() @@ -142,7 +147,7 @@ public void ToTestCaseShouldSetPropertiesIfPresent() var testCase = _unitTestElement.ToTestCase(); - Verify(new string[] { "2312", "22332" }.SequenceEqual((string[])testCase.GetPropertyValue(EngineConstants.WorkItemIdsProperty)!)); + ((string[])testCase.GetPropertyValue(EngineConstants.WorkItemIdsProperty)!).Should().Equal(["2312", "22332"]); } public void ToTestCaseShouldSetDeploymentItemPropertyIfPresent() @@ -150,17 +155,17 @@ public void ToTestCaseShouldSetDeploymentItemPropertyIfPresent() _unitTestElement.DeploymentItems = null; var testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty) is null); + testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty).Should().BeNull(); _unitTestElement.DeploymentItems = []; testCase = _unitTestElement.ToTestCase(); - Verify(testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty) is null); + testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty).Should().BeNull(); _unitTestElement.DeploymentItems = [new("s", "d")]; testCase = _unitTestElement.ToTestCase(); - Verify(_unitTestElement.DeploymentItems.SequenceEqual(testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty) as KeyValuePair[])); + _unitTestElement.DeploymentItems.SequenceEqual(testCase.GetPropertyValue(EngineConstants.DeploymentItemsProperty) as KeyValuePair[]).Should().BeTrue(); } public void ToTestCase_WhenStrategyIsData_DoesNotUseDefaultTestCaseId() @@ -175,10 +180,10 @@ public void ToTestCase_WhenStrategyIsData_DoesNotUseDefaultTestCaseId() }).ToTestCase(); var expectedTestCase = new TestCase(testCase.FullyQualifiedName, testCase.ExecutorUri, testCase.Source); Guid expectedId = GuidFromString("MyAssemblyMyProduct.MyNamespace.MyClass.MyMethod" + (dataType == DynamicDataType.None ? string.Empty : "[0]")); - Verify(expectedTestCase.Id != testCase.Id); - Verify(expectedId == testCase.Id); - Verify(Guid.TryParse(dataType == DynamicDataType.None ? "157ad7ac-90d2-8e05-a240-056ef4253f19" : "1834fb10-d2d5-8106-8620-918822cdc63a", out Guid expectedId2)); - Verify(expectedId == expectedId2); + expectedTestCase.Id.Should().NotBe(testCase.Id); + testCase.Id.Should().Be(expectedId); + Guid.TryParse(dataType == DynamicDataType.None ? "157ad7ac-90d2-8e05-a240-056ef4253f19" : "1834fb10-d2d5-8106-8620-918822cdc63a", out Guid expectedId2).Should().BeTrue(); + expectedId.Should().Be(expectedId2); } #pragma warning restore CA2263 // Prefer generic overload when type is known @@ -228,7 +233,7 @@ public void ToTestCase_WhenStrategyIsFullyQualifiedTest_ExamplesOfTestCaseIdUniq .ToTestCase() ]; - Verify(testCases.Select(tc => tc.Id.ToString()).Distinct().Count() == testCases.Length); + testCases.Select(tc => tc.Id.ToString()).Distinct().Count().Should().Be(testCases.Length); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestResultTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestResultTests.cs index 5087c66a1b..fc9b212857 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestResultTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ObjectModel/UnitTestResultTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel; @@ -24,8 +26,8 @@ public void UnitTestResultConstructorWithOutcomeAndErrorMessageShouldSetRequired { UnitTestResult result = new(UnitTestOutcome.Error, "DummyMessage"); - Verify(result.Outcome == UnitTestOutcome.Error); - Verify(result.ErrorMessage == "DummyMessage"); + result.Outcome.Should().Be(UnitTestOutcome.Error); + result.ErrorMessage.Should().Be("DummyMessage"); } public void UnitTestResultConstructorWithTestFailedExceptionShouldSetRequiredFields() @@ -35,12 +37,12 @@ public void UnitTestResultConstructorWithTestFailedExceptionShouldSetRequiredFie UnitTestResult result = new(ex); - Verify(result.Outcome == UnitTestOutcome.Error); - Verify(result.ErrorMessage == "DummyMessage"); - Verify(result.ErrorStackTrace == "trace"); - Verify(result.ErrorFilePath == "filePath"); - Verify(result.ErrorLineNumber == 2); - Verify(result.ErrorColumnNumber == 3); + result.Outcome.Should().Be(UnitTestOutcome.Error); + result.ErrorMessage.Should().Be("DummyMessage"); + result.ErrorStackTrace.Should().Be("trace"); + result.ErrorFilePath.Should().Be("filePath"); + result.ErrorLineNumber.Should().Be(2); + result.ErrorColumnNumber.Should().Be(3); } public void UniTestHelperToTestOutcomeForUnitTestOutcomePassedShouldReturnTestOutcomePassed() @@ -56,7 +58,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomePassedShouldReturnTestOu MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.Passed, adapterSettings); - Verify(resultOutcome == TestOutcome.Passed); + resultOutcome.Should().Be(TestOutcome.Passed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeFailedShouldReturnTestOutcomeFailed() @@ -72,7 +74,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeFailedShouldReturnTestOu MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.Failed, adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeErrorShouldReturnTestOutcomeFailed() @@ -88,7 +90,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeErrorShouldReturnTestOut MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.Error, adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UnitTestHelperToTestOutcomeForUnitTestOutcomeNotRunnableShouldReturnTestOutComeNoneWhenSpecifiedInAdapterSettings() @@ -105,7 +107,7 @@ public void UnitTestHelperToTestOutcomeForUnitTestOutcomeNotRunnableShouldReturn MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.NotRunnable, adapterSettings); - Verify(resultOutcome == TestOutcome.None); + resultOutcome.Should().Be(TestOutcome.None); } public void UnitTestHelperToTestOutcomeForUnitTestOutcomeNotRunnableShouldReturnTestOutcomeFailedByDefault() @@ -121,7 +123,7 @@ public void UnitTestHelperToTestOutcomeForUnitTestOutcomeNotRunnableShouldReturn MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.NotRunnable, adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeTimeoutShouldReturnTestOutcomeFailed() @@ -137,7 +139,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeTimeoutShouldReturnTestO MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.Timeout, adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeIgnoredShouldReturnTestOutcomeSkipped() @@ -153,7 +155,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeIgnoredShouldReturnTestO MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.Ignored, adapterSettings); - Verify(resultOutcome == TestOutcome.Skipped); + resultOutcome.Should().Be(TestOutcome.Skipped); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeInconclusiveShouldReturnTestOutcomeSkipped() @@ -169,7 +171,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeInconclusiveShouldReturn MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.Inconclusive, adapterSettings); - Verify(resultOutcome == TestOutcome.Skipped); + resultOutcome.Should().Be(TestOutcome.Skipped); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeInconclusiveShouldReturnTestOutcomeFailedWhenSpecifiedSo() @@ -186,7 +188,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeInconclusiveShouldReturn MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.Inconclusive, adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeNotFoundShouldReturnTestOutcomeNotFound() @@ -202,7 +204,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeNotFoundShouldReturnTest MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.NotFound, adapterSettings); - Verify(resultOutcome == TestOutcome.NotFound); + resultOutcome.Should().Be(TestOutcome.NotFound); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeInProgressShouldReturnTestOutcomeNone() @@ -218,7 +220,7 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeInProgressShouldReturnTe MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.InProgress, adapterSettings); - Verify(resultOutcome == TestOutcome.None); + resultOutcome.Should().Be(TestOutcome.None); } public void UniTestHelperToTestOutcomeForUnitTestOutcomeNotRunnableShouldReturnTestOutcomeFailedWhenSpecifiedSo() @@ -234,6 +236,6 @@ public void UniTestHelperToTestOutcomeForUnitTestOutcomeNotRunnableShouldReturnT MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsNameAlias, _mockMessageLogger.Object)!; var resultOutcome = UnitTestOutcomeHelper.ToTestOutcome(UTF.UnitTestOutcome.NotRunnable, adapterSettings); - Verify(resultOutcome == TestOutcome.Failed); + resultOutcome.Should().Be(TestOutcome.Failed); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs index 1cc5b9b66b..d3deafcd7f 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/PlatformServiceProviderTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; @@ -22,26 +24,29 @@ protected override void Dispose(bool disposing) } } - public void ProviderServiceInstanceShouldReturnAnObjectOfItselfByDefault() => Verify(PlatformServiceProvider.Instance.GetType() == typeof(PlatformServiceProvider)); + public void ProviderServiceInstanceShouldReturnAnObjectOfItselfByDefault() + => PlatformServiceProvider.Instance.Should().BeOfType(); public void ProviderServiceInstanceShouldReturnTheInstanceSet() { // If this test fails most other tests would too since this // defines our mocking for the Service provider. PlatformServiceProvider.Instance = new TestablePlatformServiceProvider(); - Verify(PlatformServiceProvider.Instance.GetType() == typeof(TestablePlatformServiceProvider)); + PlatformServiceProvider.Instance.Should().BeOfType(); } - public void TestSourceShouldReturnANonNullInstance() => Verify(PlatformServiceProvider.Instance is not null); + public void TestSourceShouldReturnANonNullInstance() + => PlatformServiceProvider.Instance.Should().NotBeNull(); - public void ReflectionOperationsShouldReturnAValidInstance() => Verify(PlatformServiceProvider.Instance.ReflectionOperations.GetType() == typeof(ReflectionOperations)); + public void ReflectionOperationsShouldReturnAValidInstance() + => PlatformServiceProvider.Instance.ReflectionOperations.Should().BeOfType(); public void ReflectionOperationsShouldBeCached() { PlatformServices.Interface.IReflectionOperations reflectionOperationsInstance = PlatformServiceProvider.Instance.ReflectionOperations; - Verify(reflectionOperationsInstance is not null); - Verify(reflectionOperationsInstance == PlatformServiceProvider.Instance.ReflectionOperations); + reflectionOperationsInstance.Should().NotBeNull(); + reflectionOperationsInstance.Should().Be(PlatformServiceProvider.Instance.ReflectionOperations); } public void GetTestContextShouldReturnAValidTestContext() @@ -56,10 +61,9 @@ public void GetTestContextShouldReturnAValidTestContext() PlatformServices.Interface.ITestContext testContext = PlatformServiceProvider.Instance.GetTestContext(testMethod.Object, null, properties, null!, default); // Assert. - Verify(testContext.Context.FullyQualifiedTestClassName == "A.C.M"); - Verify(testContext.Context.TestName == "M"); - Verify(testContext.Context.Properties.ContainsKey(properties.Single().Key)); - - Verify(testContext.Context.Properties.Contains(properties.Single())); + testContext.Context.FullyQualifiedTestClassName.Should().Be("A.C.M"); + testContext.Context.TestName.Should().Be("M"); + testContext.Context.Properties.Should().ContainKey(properties.Single().Key); + testContext.Context.Properties.Should().Contain(properties.Single()); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/RunConfigurationSettingsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/RunConfigurationSettingsTests.cs index c8b8aa60a2..96ad8939f5 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/RunConfigurationSettingsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/RunConfigurationSettingsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.TestableImplementations; @@ -46,10 +48,10 @@ public void ConfigurationSettingsShouldReturnDefaultSettingsIfNotSet() MSTestSettings.Reset(); RunConfigurationSettings settings = MSTestSettings.RunConfigurationSettings; - Verify(settings is not null); + settings.Should().NotBeNull(); // Validating the default value of a random setting. - Verify(settings.ExecutionApartmentState is null); + settings.ExecutionApartmentState.Should().BeNull(); } #endregion @@ -61,7 +63,7 @@ public void PopulateSettingsShouldInitializeDefaultConfigurationSettingsWhenDisc MSTestSettings.PopulateSettings(null, _mockMessageLogger.Object, null); RunConfigurationSettings settings = MSTestSettings.RunConfigurationSettings; - Verify(settings.ExecutionApartmentState is null); + settings.ExecutionApartmentState.Should().BeNull(); } public void PopulateSettingsShouldInitializeDefaultSettingsWhenRunSettingsIsNull() @@ -69,7 +71,7 @@ public void PopulateSettingsShouldInitializeDefaultSettingsWhenRunSettingsIsNull MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); RunConfigurationSettings settings = MSTestSettings.RunConfigurationSettings; - Verify(settings.ExecutionApartmentState is null); + settings.ExecutionApartmentState.Should().BeNull(); } public void PopulateSettingsShouldInitializeDefaultSettingsWhenRunSettingsXmlIsEmpty() @@ -78,7 +80,7 @@ public void PopulateSettingsShouldInitializeDefaultSettingsWhenRunSettingsXmlIsE MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); RunConfigurationSettings settings = MSTestSettings.RunConfigurationSettings; - Verify(settings.ExecutionApartmentState is null); + settings.ExecutionApartmentState.Should().BeNull(); } public void PopulateSettingsShouldInitializeSettingsToDefaultIfNotSpecified() @@ -97,10 +99,10 @@ public void PopulateSettingsShouldInitializeSettingsToDefaultIfNotSpecified() MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); RunConfigurationSettings settings = MSTestSettings.RunConfigurationSettings; - Verify(settings is not null); + settings.Should().NotBeNull(); // Validating the default value of a random setting. - Verify(settings.ExecutionApartmentState is null); + settings.ExecutionApartmentState.Should().BeNull(); } public void PopulateSettingsShouldInitializeSettingsFromRunConfigurationSection() @@ -120,10 +122,10 @@ public void PopulateSettingsShouldInitializeSettingsFromRunConfigurationSection( MSTestSettings.PopulateSettings(_mockDiscoveryContext.Object, _mockMessageLogger.Object, null); RunConfigurationSettings settings = MSTestSettings.RunConfigurationSettings; - Verify(settings is not null); + settings.Should().NotBeNull(); // Validating the default value of a random setting. - Verify(settings.ExecutionApartmentState == ApartmentState.STA); + settings.ExecutionApartmentState.Should().Be(ApartmentState.STA); } #endregion @@ -147,8 +149,8 @@ public void PopulateRunConfigurationSettingsFromJson_ShouldInitializeSettingsCor RunConfigurationSettings.SetRunConfigurationSettingsFromConfig(mockConfig.Object, settings); // Assert - Verify(settings is not null); - Verify(settings.ExecutionApartmentState == ApartmentState.STA); + settings.Should().NotBeNull(); + settings.ExecutionApartmentState.Should().Be(ApartmentState.STA); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopReflectionOperationsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopReflectionOperationsTests.cs index 0b867956a9..b92337a744 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopReflectionOperationsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopReflectionOperationsTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using MSTestAdapter.PlatformServices.UnitTests.Utilities; @@ -22,11 +24,11 @@ public void GetCustomAttributesShouldReturnAllAttributes() object[] attributes = _reflectionOperations.GetCustomAttributes(methodInfo); - Verify(attributes is not null); - Verify(attributes.Length == 2); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(2); string[] expectedAttributes = ["DummyA : base", "DummySingleA : base"]; - Verify(expectedAttributes.SequenceEqual(ReflectionUtilityTests.GetAttributeValuePairs(attributes))); + expectedAttributes.SequenceEqual(ReflectionUtilityTests.GetAttributeValuePairs(attributes)).Should().BeTrue(); } public void GetCustomAttributesOnTypeShouldReturnAllAttributes() @@ -35,11 +37,11 @@ public void GetCustomAttributesOnTypeShouldReturnAllAttributes() object[] attributes = _reflectionOperations.GetCustomAttributes(type); - Verify(attributes is not null); - Verify(attributes.Length == 1); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(1); string[] expectedAttributes = ["DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(ReflectionUtilityTests.GetAttributeValuePairs(attributes))); + expectedAttributes.SequenceEqual(ReflectionUtilityTests.GetAttributeValuePairs(attributes)).Should().BeTrue(); } public void GetSpecificCustomAttributesOnAssemblyShouldReturnAllAttributes() @@ -48,11 +50,11 @@ public void GetSpecificCustomAttributesOnAssemblyShouldReturnAllAttributes() object[] attributes = _reflectionOperations.GetCustomAttributes(asm, typeof(ReflectionUtilityTests.DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Length == 2); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(2); string[] expectedAttributes = ["DummyA : a1", "DummyA : a2"]; - Verify(expectedAttributes.SequenceEqual(ReflectionUtilityTests.GetAttributeValuePairs(attributes))); + expectedAttributes.SequenceEqual(ReflectionUtilityTests.GetAttributeValuePairs(attributes)).Should().BeTrue(); } } #endif diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDataSourceTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDataSourceTests.cs index 4b7ebe5ae1..a4223eef55 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDataSourceTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDataSourceTests.cs @@ -4,6 +4,8 @@ #if NETFRAMEWORK using System.Data; +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; @@ -41,7 +43,7 @@ public void GetDataShouldReadDataFromGivenDataSource() foreach (DataRow dataRow in dataRows.Cast()) { - Verify("v1".Equals(dataRow[3])); + dataRow[3].Should().Be("v1"); } } @@ -70,13 +72,14 @@ public class DummyTestClass [TestMethod] public void PassingTest() { - Verify(TestContext.DataRow!["adapter"].ToString() == "v1"); - Verify(TestContext.DataRow["targetPlatform"].ToString() == "x86"); + TestContext.DataRow!["adapter"].ToString().Should().Be("v1"); + TestContext.DataRow["targetPlatform"].ToString().Should().Be("x86"); TestContext.AddResultFile("C:\\temp.txt"); } [TestMethod] - public void FailingTest() => Verify(TestContext.DataRow!["configuration"].ToString() == "Release"); + public void FailingTest() + => TestContext.DataRow!["configuration"].ToString().Should().Be("Release"); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs index 41262e4193..44c211f7d2 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; @@ -50,7 +52,7 @@ public void DeployShouldDeployFilesInASourceAndReturnTrue() var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); - Verify(testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object)); + testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object).Should().BeTrue(); string? warning; string sourceFile = Assembly.GetExecutingAssembly().GetName().Name + ".exe"; @@ -75,7 +77,7 @@ public void DeployShouldDeployFilesInMultipleSourcesAndReturnTrue() var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); - Verify(testDeployment.Deploy(new List { testCase1, testCase2 }, mockRunContext.Object, new Mock().Object)); + testDeployment.Deploy(new List { testCase1, testCase2 }, mockRunContext.Object, new Mock().Object).Should().BeTrue(); string? warning; string sourceFile1 = Assembly.GetExecutingAssembly().GetName().Name + ".exe"; @@ -105,7 +107,7 @@ public void DeployShouldCreateDeploymentDirectories() var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); - Verify(testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object)); + testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object).Should().BeTrue(); // matched twice because root deployment and out directory are same in net core _mockFileUtility.Verify(fu => fu.CreateDirectoryIfNotExists(testRunDirectories.RootDeploymentDirectory), Times.Once); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestSourceHostTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestSourceHostTests.cs index a80aefe8f9..fb0a5fb296 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestSourceHostTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestSourceHostTests.cs @@ -4,6 +4,8 @@ #if NETFRAMEWORK using System.Security.Policy; +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; @@ -29,12 +31,12 @@ public void GetResolutionPathsShouldAddPublicAndPrivateAssemblyPath() // Assert if (!string.IsNullOrWhiteSpace(VSInstallationUtilities.PathToPublicAssemblies)) { - Verify(result.Contains(VSInstallationUtilities.PathToPublicAssemblies!)); + result.Should().Contain(VSInstallationUtilities.PathToPublicAssemblies!); } if (!string.IsNullOrWhiteSpace(VSInstallationUtilities.PathToPrivateAssemblies)) { - Verify(result.Contains(VSInstallationUtilities.PathToPrivateAssemblies!)); + result.Should().Contain(VSInstallationUtilities.PathToPrivateAssemblies!); } } @@ -48,8 +50,8 @@ public void GetResolutionPathsShouldNotAddPublicAndPrivateAssemblyPathInPortable List result = sut.GetResolutionPaths("DummyAssembly.dll", isPortableMode: true); // Assert - Verify(!result.Contains(VSInstallationUtilities.PathToPublicAssemblies!)); - Verify(!result.Contains(VSInstallationUtilities.PathToPrivateAssemblies!)); + result.Should().NotContain(VSInstallationUtilities.PathToPublicAssemblies!); + result.Should().NotContain(VSInstallationUtilities.PathToPrivateAssemblies!); } public void GetResolutionPathsShouldAddAdapterFolderPath() @@ -61,7 +63,7 @@ public void GetResolutionPathsShouldAddAdapterFolderPath() List result = sut.GetResolutionPaths("DummyAssembly.dll", isPortableMode: false); // Assert - Verify(!result.Contains(typeof(TestSourceHost).Assembly.Location)); + result.Should().NotContain(typeof(TestSourceHost).Assembly.Location); } public void GetResolutionPathsShouldAddTestPlatformFolderPath() @@ -73,7 +75,7 @@ public void GetResolutionPathsShouldAddTestPlatformFolderPath() List result = sut.GetResolutionPaths("DummyAssembly.dll", isPortableMode: false); // Assert - Verify(!result.Contains(typeof(AssemblyHelper).Assembly.Location)); + result.Should().NotContain(typeof(AssemblyHelper).Assembly.Location); } public void CreateInstanceForTypeShouldCreateTheTypeInANewAppDomain() @@ -93,7 +95,7 @@ public void CreateInstanceForTypeShouldCreateTheTypeInANewAppDomain() } // Assert - Verify(currentAppDomainId != newAppDomainId); + currentAppDomainId.Should().NotBe(newAppDomainId); } public void SetupHostShouldSetChildDomainsAppBaseToTestSourceLocation() @@ -111,7 +113,7 @@ public void SetupHostShouldSetChildDomainsAppBaseToTestSourceLocation() var expectedObject = sourceHost.Object.CreateInstanceForType(typeof(DummyClass), null) as DummyClass; // Assert - Verify(Path.GetDirectoryName(typeof(DesktopTestSourceHostTests).Assembly.Location) == expectedObject?.AppDomainAppBase); + expectedObject?.AppDomainAppBase.Should().Be(Path.GetDirectoryName(typeof(DesktopTestSourceHostTests).Assembly.Location)); } finally { @@ -145,7 +147,7 @@ public void SetupHostShouldHaveParentDomainsAppBaseSetToTestSourceLocation() var expectedObject = sourceHost.CreateInstanceForType(typeof(DummyClass), null) as DummyClass; // Assert - Verify(Path.GetDirectoryName(typeof(DesktopTestSourceHostTests).Assembly.Location) == expectedObject?.AppDomainAppBase); + expectedObject?.AppDomainAppBase.Should().Be(Path.GetDirectoryName(typeof(DesktopTestSourceHostTests).Assembly.Location)); } finally { @@ -214,7 +216,7 @@ public void NoAppDomainShouldGetCreatedWhenDisableAppDomainIsSetToTrue() { // Act testSourceHost.Object.SetupHost(); - Verify(testSourceHost.Object.AppDomain is null); + testSourceHost.Object.AppDomain.Should().BeNull(); } finally { @@ -245,7 +247,7 @@ public void AppDomainShouldGetCreatedWhenDisableAppDomainIsSetToFalse() { // Act testSourceHost.Object.SetupHost(); - Verify(testSourceHost.Object.AppDomain is not null); + testSourceHost.Object.AppDomain.Should().NotBeNull(); } finally { diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestSourceTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestSourceTests.cs index 84f72290ca..461efbd2dd 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestSourceTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestSourceTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -14,18 +16,18 @@ public class DesktopTestSourceTests : TestContainer public DesktopTestSourceTests() => _testSource = new TestSourceHandler(); - public void ValidSourceExtensionsShouldContainDllExtensions() => Verify(_testSource.ValidSourceExtensions.Contains(".dll")); + public void ValidSourceExtensionsShouldContainDllExtensions() => _testSource.ValidSourceExtensions.Contains(".dll").Should().BeTrue(); - public void ValidSourceExtensionsShouldContainExeExtensions() => Verify(_testSource.ValidSourceExtensions.ToList().Contains(".exe")); + public void ValidSourceExtensionsShouldContainExeExtensions() => _testSource.ValidSourceExtensions.ToList().Contains(".exe").Should().BeTrue(); - public void ValidSourceExtensionsShouldContainAppxExtensions() => Verify(_testSource.ValidSourceExtensions.Contains(".appx")); + public void ValidSourceExtensionsShouldContainAppxExtensions() => _testSource.ValidSourceExtensions.Contains(".appx").Should().BeTrue(); - public void IsAssemblyReferencedShouldReturnTrueIfAssemblyNameIsNull() => Verify(_testSource.IsAssemblyReferenced(null!, "DummySource")); + public void IsAssemblyReferencedShouldReturnTrueIfAssemblyNameIsNull() => _testSource.IsAssemblyReferenced(null!, "DummySource").Should().BeTrue(); - public void IsAssemblyReferencedShouldReturnTrueIfSourceIsNull() => Verify(_testSource.IsAssemblyReferenced(Assembly.GetExecutingAssembly().GetName(), null!)); + public void IsAssemblyReferencedShouldReturnTrueIfSourceIsNull() => _testSource.IsAssemblyReferenced(Assembly.GetExecutingAssembly().GetName(), null!).Should().BeTrue(); - public void IsAssemblyReferencedShouldReturnTrueIfAnAssemblyIsReferencedInSource() => Verify(_testSource.IsAssemblyReferenced(typeof(Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute).Assembly.GetName(), Assembly.GetExecutingAssembly().Location)); + public void IsAssemblyReferencedShouldReturnTrueIfAnAssemblyIsReferencedInSource() => _testSource.IsAssemblyReferenced(typeof(Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute).Assembly.GetName(), Assembly.GetExecutingAssembly().Location).Should().BeTrue(); - public void IsAssemblyReferencedShouldReturnFalseIfAnAssemblyIsNotReferencedInSource() => Verify(!_testSource.IsAssemblyReferenced(new AssemblyName("foobar"), Assembly.GetExecutingAssembly().Location)); + public void IsAssemblyReferencedShouldReturnFalseIfAnAssemblyIsNotReferencedInSource() => _testSource.IsAssemblyReferenced(new AssemblyName("foobar"), Assembly.GetExecutingAssembly().Location).Should().BeFalse(); } #endif diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopThreadOperationsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopThreadOperationsTests.cs index 50142b5856..097ca7b672 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopThreadOperationsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopThreadOperationsTests.cs @@ -3,6 +3,8 @@ #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -21,8 +23,8 @@ public void ExecuteShouldRunActionOnANewThread() var cancellationTokenSource = new CancellationTokenSource(); void Action() => actionThreadID = Environment.CurrentManagedThreadId; - Verify(_asyncOperations.Execute(Action, 1000, cancellationTokenSource.Token)); - Verify(Environment.CurrentManagedThreadId != actionThreadID); + _asyncOperations.Execute(Action, 1000, cancellationTokenSource.Token).Should().BeTrue(); + Environment.CurrentManagedThreadId.Should().NotBe(actionThreadID); } public void TokenCancelShouldAbortExecutingAction() @@ -35,7 +37,7 @@ public void TokenCancelShouldAbortExecutingAction() bool result = _asyncOperations.Execute(() => Thread.Sleep(10000), 100000, cancellationTokenSource.Token); // validate - Verify(!result, "The execution failed to abort"); + result.Should().BeFalse("The execution failed to abort"); } public void TokenCancelShouldAbortIfAlreadyCanceled() @@ -48,7 +50,7 @@ public void TokenCancelShouldAbortIfAlreadyCanceled() bool result = _asyncOperations.Execute(() => Thread.Sleep(10000), 100000, cancellationTokenSource.Token); // validate - Verify(!result, "The execution failed to abort"); + result.Should().BeFalse("The execution failed to abort"); } } #endif diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/FileOperationsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/FileOperationsTests.cs index 1b4ad57d0c..c4caf34c1c 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/FileOperationsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/FileOperationsTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if !NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -17,12 +19,12 @@ public class FileOperationsTests : TestContainer public void LoadAssemblyShouldThrowExceptionIfTheFileNameHasInvalidCharacters() { string filePath = "temp<>txt"; - void A() => _fileOperations.LoadAssembly(filePath); + Action action = () => _fileOperations.LoadAssembly(filePath); #if NETCOREAPP - VerifyThrows(A); + action.Should().Throw(); #else - VerifyThrows(A); + action.Should().Throw(); #endif } @@ -34,14 +36,14 @@ public void LoadAssemblyShouldNotThrowFileLoadExceptionIfTheFileNameHasValidFile // This test is checking that. It still fails with FileNotFoundException, because the file does not exist, but it should not throw FileLoadException. // (The FileLoadException used for the unparseable name is weird choice, and confusing to me, but that is what the runtime decided to do. No dll is being loaded.) string filePath = "temp=txt"; - void A() => _fileOperations.LoadAssembly(filePath); + Action action = () => _fileOperations.LoadAssembly(filePath); - VerifyThrows(A); + action.Should().Throw(); #endif } public void LoadAssemblyShouldThrowExceptionIfFileIsNotFound() => - VerifyThrows(() => _fileOperations.LoadAssembly("temptxt")); + new Action(() => _fileOperations.LoadAssembly("temptxt")).Should().Throw(); public void LoadAssemblyShouldLoadAssemblyInCurrentContext() { @@ -54,15 +56,15 @@ public void LoadAssemblyShouldLoadAssemblyInCurrentContext() #if !WIN_UI public void DoesFileExistReturnsTrueForAllFiles() { - Verify(_fileOperations.DoesFileExist(null!)); - Verify(_fileOperations.DoesFileExist("foobar")); + _fileOperations.DoesFileExist(null!).Should().BeTrue(); + _fileOperations.DoesFileExist("foobar").Should().BeTrue(); } #endif public void GetFullFilePathShouldReturnAssemblyFileName() { - Verify(_fileOperations.GetFullFilePath(null!) is null); - Verify(_fileOperations.GetFullFilePath("assemblyFileName") == "assemblyFileName"); + _fileOperations.GetFullFilePath(null!).Should().BeNull(); + _fileOperations.GetFullFilePath("assemblyFileName").Should().Be("assemblyFileName"); } } #pragma warning restore SA1649 // SA1649FileNameMustMatchTypeName diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestAdapterSettingsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestAdapterSettingsTests.cs index 74b6be51e0..eaa1380860 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestAdapterSettingsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestAdapterSettingsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -41,8 +43,8 @@ public void ResolveEnvironmentVariableShouldResolvePathWhenPassedAbsolutePath() string? result = adapterSettings.ResolveEnvironmentVariableAndReturnFullPathIfExist(path, baseDirectory); - Verify(result is not null); - Verify(string.Equals(result, expectedResult, StringComparison.OrdinalIgnoreCase)); + result.Should().NotBeNull(); + result.Should().BeEquivalentTo(expectedResult, options => options.IgnoringCase()); } public void ResolveEnvironmentVariableShouldResolvePathWithAnEnvironmentVariable() @@ -59,8 +61,8 @@ public void ResolveEnvironmentVariableShouldResolvePathWithAnEnvironmentVariable string? result = adapterSettings.ResolveEnvironmentVariableAndReturnFullPathIfExist(path, baseDirectory); - Verify(result is not null); - Verify(string.Equals(result, expectedResult, StringComparison.OrdinalIgnoreCase)); + result.Should().NotBeNull(); + result.Should().BeEquivalentTo(expectedResult, options => options.IgnoringCase()); } public void ResolveEnvironmentVariableShouldResolvePathWhenPassedRelativePathWithoutDot() @@ -76,8 +78,8 @@ public void ResolveEnvironmentVariableShouldResolvePathWhenPassedRelativePathWit string? result = adapterSettings.ResolveEnvironmentVariableAndReturnFullPathIfExist(path, baseDirectory); - Verify(result is not null); - Verify(string.Equals(result, expectedResult, StringComparison.OrdinalIgnoreCase)); + result.Should().NotBeNull(); + result.Should().BeEquivalentTo(expectedResult, options => options.IgnoringCase()); } public void ResolveEnvironmentVariableShouldResolvePathWhenPassedRelativePathWithDot() @@ -93,8 +95,8 @@ public void ResolveEnvironmentVariableShouldResolvePathWhenPassedRelativePathWit string? result = adapterSettings.ResolveEnvironmentVariableAndReturnFullPathIfExist(path, baseDirectory); - Verify(result is not null); - Verify(string.Equals(result, expectedResult, StringComparison.OrdinalIgnoreCase)); + result.Should().NotBeNull(); + result.Should().BeEquivalentTo(expectedResult, options => options.IgnoringCase()); } public void ResolveEnvironmentVariableShouldResolvePathWhenPassedRelativePath() @@ -116,8 +118,8 @@ public void ResolveEnvironmentVariableShouldResolvePathWhenPassedRelativePath() string? result = adapterSettings.ResolveEnvironmentVariableAndReturnFullPathIfExist(path, baseDirectory); - Verify(result is not null); - Verify(string.Equals(result, expectedResult, StringComparison.OrdinalIgnoreCase)); + result.Should().NotBeNull(); + result.Should().BeEquivalentTo(expectedResult, options => options.IgnoringCase()); } public void ResolveEnvironmentVariableShouldResolvePathWhenPassedNetworkPath() @@ -134,8 +136,8 @@ public void ResolveEnvironmentVariableShouldResolvePathWhenPassedNetworkPath() string? result = adapterSettings.ResolveEnvironmentVariableAndReturnFullPathIfExist(path, baseDirectory); - Verify(result is not null); - Verify(string.Equals(result, expectedResult, StringComparison.OrdinalIgnoreCase)); + result.Should().NotBeNull(); + result.Should().BeEquivalentTo(expectedResult, options => options.IgnoringCase()); } public void ResolveEnvironmentVariableShouldReturnFalseForInvalidPath() @@ -145,7 +147,7 @@ public void ResolveEnvironmentVariableShouldReturnFalseForInvalidPath() string? result = new TestableMSTestAdapterSettings().ResolveEnvironmentVariableAndReturnFullPathIfExist(path, baseDirectory); - Verify(result is null); + result.Should().BeNull(); } #endregion @@ -169,13 +171,13 @@ public void GetDirectoryListWithRecursivePropertyShouldReadRunSettingCorrectly() }; IList result = adapterSettings.GetDirectoryListWithRecursiveProperty(baseDirectory); - Verify(result is not null); - Verify(result.Count == 2); + result.Should().NotBeNull(); + result.Count.Should().Be(2); for (int i = 0; i < 2; i++) { - Verify(string.Equals(result[i].DirectoryPath, expectedResult[i].DirectoryPath, StringComparison.OrdinalIgnoreCase)); - Verify(result[i].IncludeSubDirectories == expectedResult[i].IncludeSubDirectories); + result[i].DirectoryPath.Should().BeEquivalentTo(expectedResult[i].DirectoryPath, options => options.IgnoringCase()); + result[i].IncludeSubDirectories.Should().Be(expectedResult[i].IncludeSubDirectories); } } @@ -225,7 +227,7 @@ public void ToSettingsShouldThrowExceptionWhenRunSettingsXmlIsWrong() void ShouldThrowException() => MSTestAdapterSettings.ToSettings(reader); - VerifyThrows(ShouldThrowException); + new Action(ShouldThrowException).Should().Throw(); } #endregion @@ -243,7 +245,7 @@ public void DeploymentEnabledIsByDefaultTrueWhenNotSpecified() var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); reader.Read(); var adapterSettings = MSTestAdapterSettings.ToSettings(reader); - Verify(adapterSettings.DeploymentEnabled); + adapterSettings.DeploymentEnabled.Should().BeTrue(); } public void DeploymentEnabledShouldBeConsumedFromRunSettingsWhenSpecified() @@ -258,7 +260,7 @@ public void DeploymentEnabledShouldBeConsumedFromRunSettingsWhenSpecified() var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); reader.Read(); var adapterSettings = MSTestAdapterSettings.ToSettings(reader); - Verify(!adapterSettings.DeploymentEnabled); + adapterSettings.DeploymentEnabled.Should().BeFalse(); } #endregion @@ -276,7 +278,7 @@ public void DeployTestSourceDependenciesIsEnabledByDefault() var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); reader.Read(); var adapterSettings = MSTestAdapterSettings.ToSettings(reader); - Verify(adapterSettings.DeployTestSourceDependencies); + adapterSettings.DeployTestSourceDependencies.Should().BeTrue(); } public void DeployTestSourceDependenciesWhenFalse() @@ -291,7 +293,7 @@ public void DeployTestSourceDependenciesWhenFalse() var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); reader.Read(); var adapterSettings = MSTestAdapterSettings.ToSettings(reader); - Verify(!adapterSettings.DeployTestSourceDependencies); + adapterSettings.DeployTestSourceDependencies.Should().BeFalse(); } public void DeployTestSourceDependenciesWhenTrue() @@ -306,7 +308,7 @@ public void DeployTestSourceDependenciesWhenTrue() var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); reader.Read(); var adapterSettings = MSTestAdapterSettings.ToSettings(reader); - Verify(adapterSettings.DeployTestSourceDependencies); + adapterSettings.DeployTestSourceDependencies.Should().BeTrue(); } #endregion @@ -335,9 +337,9 @@ public void ToSettings_ShouldInitializeDeploymentAndAssemblyResolutionSettingsCo var settings = MSTestAdapterSettings.ToSettings(mockConfig.Object); // Assert - Verify(settings.DeploymentEnabled); - Verify(settings.DeployTestSourceDependencies); - Verify(!settings.DeleteDeploymentDirectoryAfterTestRunIsComplete); + settings.DeploymentEnabled.Should().BeTrue(); + settings.DeployTestSourceDependencies.Should().BeTrue(); + settings.DeleteDeploymentDirectoryAfterTestRunIsComplete.Should().BeFalse(); } public void IsAppDomainCreationDisabled_ShouldPreferJsonConfigurationOverSettingsXml() @@ -365,7 +367,7 @@ public void IsAppDomainCreationDisabled_ShouldPreferJsonConfigurationOverSetting bool result = MSTestAdapterSettings.IsAppDomainCreationDisabled(settingsXml); // Assert - Verify(result); + result.Should().BeTrue(); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestSettingsProviderTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestSettingsProviderTests.cs index 874367ce73..dad57c6bff 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestSettingsProviderTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/MSTestSettingsProviderTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; @@ -27,16 +29,16 @@ public void GetPropertiesShouldReturnDeploymentInformation() // so passing 'null' source will also suffice. IDictionary properties = _settingsProvider.GetProperties(null); - Verify(properties is not null); - Verify(properties.Count > 0); + properties.Should().NotBeNull(); + properties.Count.Should().BeGreaterThan(0); } public void SettingsShouldReturnDefaultSettingsIfNotInitialized() { MSTestAdapterSettings settings = MSTestSettingsProvider.Settings; - Verify(settings is not null); - Verify(settings.DeploymentEnabled); + settings.Should().NotBeNull(); + settings.DeploymentEnabled.Should().BeTrue(); } public void SettingsShouldReturnInitializedSettings() @@ -51,11 +53,11 @@ public void SettingsShouldReturnInitializedSettings() var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); reader.Read(); _settingsProvider.Load(reader); - Verify(!MSTestSettingsProvider.Settings.DeploymentEnabled); + MSTestSettingsProvider.Settings.DeploymentEnabled.Should().BeFalse(); } public void LoadShouldThrowIfReaderIsNull() => - VerifyThrows(() => _settingsProvider.Load(null!)); + new Action(() => _settingsProvider.Load(null!)).Should().Throw(); public void LoadShouldReadAndFillInSettings() { @@ -69,12 +71,12 @@ public void LoadShouldReadAndFillInSettings() var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); reader.Read(); _settingsProvider.Load(reader); - Verify(!MSTestSettingsProvider.Settings.DeploymentEnabled); + MSTestSettingsProvider.Settings.DeploymentEnabled.Should().BeFalse(); } public void LoadShouldReadAndFillInSettingsFromIConfiguration() { - Verify(MSTestSettingsProvider.Settings.DeploymentEnabled); + MSTestSettingsProvider.Settings.DeploymentEnabled.Should().BeTrue(); MSTestSettingsProvider.Load(new MockConfiguration( new Dictionary() @@ -82,7 +84,7 @@ public void LoadShouldReadAndFillInSettingsFromIConfiguration() ["mstest:deployment:enabled"] = "false", }, null)); - Verify(!MSTestSettingsProvider.Settings.DeploymentEnabled); + MSTestSettingsProvider.Settings.DeploymentEnabled.Should().BeFalse(); } private sealed class MockConfiguration : IConfiguration diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs index d5d58ad8bb..3a8a2407ea 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -19,11 +21,11 @@ public void GetCustomAttributesShouldReturnAllAttributes() object[] attributes = _reflectionOperations.GetCustomAttributes(methodInfo); - Verify(attributes is not null); - Verify(attributes.Length == 2); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(2); string[] expectedAttributes = ["DummyA : base", "DummySingleA : base"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } public void GetCustomAttributesShouldReturnAllAttributesWithBaseInheritance() @@ -32,12 +34,12 @@ public void GetCustomAttributesShouldReturnAllAttributesWithBaseInheritance() object[] attributes = _reflectionOperations.GetCustomAttributes(methodInfo); - Verify(attributes is not null); - Verify(attributes.Length == 3); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(3); // Notice that the DummySingleA on the base method does not show up since it can only be defined once. string[] expectedAttributes = ["DummyA : derived", "DummySingleA : derived", "DummyA : base"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } public void GetCustomAttributesOnTypeShouldReturnAllAttributes() @@ -46,11 +48,11 @@ public void GetCustomAttributesOnTypeShouldReturnAllAttributes() object[] attributes = GetMemberAttributes(type); - Verify(attributes is not null); - Verify(attributes.Length == 1); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(1); string[] expectedAttributes = ["DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } private object[] GetMemberAttributes(Type type) @@ -62,11 +64,11 @@ public void GetCustomAttributesOnTypeShouldReturnAllAttributesWithBaseInheritanc object[] attributes = GetMemberAttributes(type); - Verify(attributes is not null); - Verify(attributes.Length == 2); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(2); string[] expectedAttributes = ["DummyA : a", "DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } public void GetSpecificCustomAttributesShouldReturnAllAttributes() @@ -75,11 +77,11 @@ public void GetSpecificCustomAttributesShouldReturnAllAttributes() object[] attributes = _reflectionOperations.GetCustomAttributes(methodInfo, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Length == 1); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(1); string[] expectedAttributes = ["DummyA : base"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } public void GetSpecificCustomAttributesShouldReturnAllAttributesWithBaseInheritance() @@ -88,11 +90,11 @@ public void GetSpecificCustomAttributesShouldReturnAllAttributesWithBaseInherita object[] attributes = _reflectionOperations.GetCustomAttributes(methodInfo, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Length == 2); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(2); string[] expectedAttributes = ["DummyA : derived", "DummyA : base"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } public void GetSpecificCustomAttributesOnTypeShouldReturnAllAttributes() @@ -101,11 +103,11 @@ public void GetSpecificCustomAttributesOnTypeShouldReturnAllAttributes() object[] attributes = _reflectionOperations.GetCustomAttributes(type, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Length == 1); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(1); string[] expectedAttributes = ["DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } public void GetSpecificCustomAttributesOnTypeShouldReturnAllAttributesWithBaseInheritance() @@ -114,11 +116,11 @@ public void GetSpecificCustomAttributesOnTypeShouldReturnAllAttributesWithBaseIn object[] attributes = _reflectionOperations.GetCustomAttributes(type, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Length == 2); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(2); string[] expectedAttributes = ["DummyA : a", "DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } public void GetSpecificCustomAttributesOnAssemblyShouldReturnAllAttributes() @@ -127,11 +129,11 @@ public void GetSpecificCustomAttributesOnAssemblyShouldReturnAllAttributes() object[] attributes = _reflectionOperations.GetCustomAttributes(asm, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Length == 2); + attributes.Should().NotBeNull(); + attributes.Length.Should().Be(2); string[] expectedAttributes = ["DummyA : a1", "DummyA : a2"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).SequenceEqual(expectedAttributes).Should().BeTrue(); } private static string[] GetAttributeValuePairs(object[] attributes) diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs index 2328dc34e3..cb047b0059 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestContextImplementationTests.cs @@ -6,6 +6,8 @@ using System.Data.Common; #endif +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; @@ -40,7 +42,7 @@ public void TestContextConstructorShouldInitializeProperties() { _testContextImplementation = CreateTestContextImplementation(); - Verify(_testContextImplementation.Properties is not null); + _testContextImplementation.Properties.Should().NotBeNull(); } public void TestContextConstructorShouldInitializeDefaultProperties() @@ -50,17 +52,17 @@ public void TestContextConstructorShouldInitializeDefaultProperties() _testContextImplementation = CreateTestContextImplementation(); - Verify(_testContextImplementation.Properties is not null); + _testContextImplementation.Properties.Should().NotBeNull(); - Verify(_testContextImplementation.Properties["FullyQualifiedTestClassName"]!.Equals("A.C.M")); - Verify(_testContextImplementation.Properties["TestName"]!.Equals("M")); + _testContextImplementation.Properties["FullyQualifiedTestClassName"]!.Should().Be("A.C.M"); + _testContextImplementation.Properties["TestName"]!.Should().Be("M"); } public void CurrentTestOutcomeShouldReturnDefaultOutcome() { _testContextImplementation = CreateTestContextImplementation(); - Verify(_testContextImplementation.CurrentTestOutcome == UnitTestOutcome.Failed); + _testContextImplementation.CurrentTestOutcome.Should().Be(UnitTestOutcome.Failed); } public void CurrentTestOutcomeShouldReturnOutcomeSet() @@ -69,7 +71,7 @@ public void CurrentTestOutcomeShouldReturnOutcomeSet() _testContextImplementation.SetOutcome(UnitTestOutcome.InProgress); - Verify(_testContextImplementation.CurrentTestOutcome == UnitTestOutcome.InProgress); + _testContextImplementation.CurrentTestOutcome.Should().Be(UnitTestOutcome.InProgress); } public void FullyQualifiedTestClassNameShouldReturnTestMethodsFullClassName() @@ -78,7 +80,7 @@ public void FullyQualifiedTestClassNameShouldReturnTestMethodsFullClassName() _testContextImplementation = CreateTestContextImplementation(); - Verify(_testContextImplementation.FullyQualifiedTestClassName == "A.C.M"); + _testContextImplementation.FullyQualifiedTestClassName.Should().Be("A.C.M"); } public void TestNameShouldReturnTestMethodsName() @@ -87,7 +89,7 @@ public void TestNameShouldReturnTestMethodsName() _testContextImplementation = CreateTestContextImplementation(); - Verify(_testContextImplementation.TestName == "M"); + _testContextImplementation.TestName.Should().Be("M"); } public void PropertiesShouldReturnPropertiesPassedToTestContext() @@ -100,8 +102,8 @@ public void PropertiesShouldReturnPropertiesPassedToTestContext() _testContextImplementation = CreateTestContextImplementation(); - Verify(_testContextImplementation.Properties[property1.Key] == property1.Value); - Verify(_testContextImplementation.Properties[property2.Key] == property2.Value); + _testContextImplementation.Properties[property1.Key].Should().Be(property1.Value); + _testContextImplementation.Properties[property2.Key].Should().Be(property2.Value); } public void ContextShouldReturnTestContextObject() @@ -110,8 +112,8 @@ public void ContextShouldReturnTestContextObject() _testContextImplementation = CreateTestContextImplementation(); - Verify(_testContextImplementation.Context is not null); - Verify(_testContextImplementation.Context.TestName == "M"); + _testContextImplementation.Context.Should().NotBeNull(); + _testContextImplementation.Context.TestName.Should().Be("M"); } public void TryGetPropertyValueShouldReturnTrueIfPropertyIsPresent() @@ -120,16 +122,16 @@ public void TryGetPropertyValueShouldReturnTrueIfPropertyIsPresent() _testContextImplementation = CreateTestContextImplementation(); - Verify(_testContextImplementation.TryGetPropertyValue("TestName", out object? propValue)); - Verify("M".Equals(propValue)); + _testContextImplementation.TryGetPropertyValue("TestName", out object? propValue).Should().BeTrue(); + propValue.Should().Be("M"); } public void TryGetPropertyValueShouldReturnFalseIfPropertyIsNotPresent() { _testContextImplementation = CreateTestContextImplementation(); - Verify(!_testContextImplementation.TryGetPropertyValue("Random", out object? propValue)); - Verify(propValue is null); + _testContextImplementation.TryGetPropertyValue("Random", out object? propValue).Should().BeFalse(); + propValue.Should().BeNull(); } public void AddPropertyShouldAddPropertiesToThePropertyBag() @@ -138,23 +140,23 @@ public void AddPropertyShouldAddPropertiesToThePropertyBag() var property = new KeyValuePair("SomeNewProperty", "SomeValue"); _testContextImplementation.AddProperty(property.Key, property.Value); - Verify(_testContextImplementation.Properties[property.Key]!.Equals(property.Value)); + _testContextImplementation.Properties[property.Key]!.Should().Be(property.Value); } public void AddResultFileShouldThrowIfFileNameIsNull() { _testContextImplementation = CreateTestContextImplementation(); - ArgumentException exception = VerifyThrows(() => _testContextImplementation.AddResultFile(null!)); - Verify(exception.Message.Contains(Resource.Common_CannotBeNullOrEmpty)); + Action action = () => _testContextImplementation.AddResultFile(null!); + action.Should().Throw().WithMessage("*" + Resource.Common_CannotBeNullOrEmpty + "*"); } public void AddResultFileShouldThrowIfFileNameIsEmpty() { _testContextImplementation = CreateTestContextImplementation(); - ArgumentException exception = VerifyThrows(() => _testContextImplementation.AddResultFile(string.Empty)); - Verify(exception.Message.Contains(Resource.Common_CannotBeNullOrEmpty)); + Action action = () => _testContextImplementation.AddResultFile(string.Empty); + action.Should().Throw().WithMessage("*" + Resource.Common_CannotBeNullOrEmpty + "*"); } public void AddResultFileShouldAddFileToResultsFiles() @@ -165,7 +167,7 @@ public void AddResultFileShouldAddFileToResultsFiles() IList? resultsFiles = _testContextImplementation.GetResultFiles(); - Verify(resultsFiles!.Contains("C:\\temp.txt")); + resultsFiles!.Should().Contain("C:\\temp.txt"); } public void AddResultFileShouldAddMultipleFilesToResultsFiles() @@ -177,36 +179,36 @@ public void AddResultFileShouldAddMultipleFilesToResultsFiles() IList? resultsFiles = _testContextImplementation.GetResultFiles(); - Verify(resultsFiles!.Contains("C:\\files\\file1.txt")); - Verify(resultsFiles.Contains("C:\\files\\files2.html")); + resultsFiles!.Should().Contain("C:\\files\\file1.txt"); + resultsFiles.Should().Contain("C:\\files\\files2.html"); } public void WriteShouldWriteToStringWriter() { _testContextImplementation = CreateTestContextImplementation(); _testContextImplementation.Write("{0} Testing write", 1); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing write")); + _testContextImplementation.GetDiagnosticMessages()!.Should().Contain("1 Testing write"); } public void WriteShouldWriteToStringWriterForNullCharacters() { _testContextImplementation = CreateTestContextImplementation(); _testContextImplementation.Write("{0} Testing \0 write \0", 1); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing \\0 write \\0")); + _testContextImplementation.GetDiagnosticMessages()!.Should().Contain("1 Testing \\0 write \\0"); } public void WriteWithMessageShouldWriteToStringWriter() { _testContextImplementation = CreateTestContextImplementation(); _testContextImplementation.Write("1 Testing write"); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing write")); + _testContextImplementation.GetDiagnosticMessages()!.Should().Contain("1 Testing write"); } public void WriteWithMessageShouldWriteToStringWriterForNullCharacters() { _testContextImplementation = CreateTestContextImplementation(); _testContextImplementation.Write("1 Testing \0 write \0"); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing \\0 write \\0")); + _testContextImplementation.GetDiagnosticMessages()!.Should().Contain("1 Testing \\0 write \\0"); } public void WriteWithMessageShouldWriteToStringWriterForReturnCharacters() @@ -214,7 +216,7 @@ public void WriteWithMessageShouldWriteToStringWriterForReturnCharacters() _testContextImplementation = CreateTestContextImplementation(); _testContextImplementation.Write("2 Testing write \n\r"); _testContextImplementation.Write("3 Testing write\n\r"); - Verify(_testContextImplementation.GetDiagnosticMessages() == "2 Testing write \n\r3 Testing write\n\r"); + _testContextImplementation.GetDiagnosticMessages().Should().Be("2 Testing write \n\r3 Testing write\n\r"); } public void WriteLineShouldWriteToStringWriter() @@ -223,7 +225,7 @@ public void WriteLineShouldWriteToStringWriter() _testContextImplementation.WriteLine("{0} Testing write", 1); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing write")); + _testContextImplementation.GetDiagnosticMessages()!.Should().Contain("1 Testing write"); } public void WriteLineShouldWriteToStringWriterForNullCharacters() @@ -232,7 +234,7 @@ public void WriteLineShouldWriteToStringWriterForNullCharacters() _testContextImplementation.WriteLine("{0} Testing \0 write \0", 1); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing \\0 write \\0")); + _testContextImplementation.GetDiagnosticMessages()!.Should().Contain("1 Testing \\0 write \\0"); } public void WriteLineWithMessageShouldWriteToStringWriter() @@ -241,7 +243,7 @@ public void WriteLineWithMessageShouldWriteToStringWriter() _testContextImplementation.WriteLine("1 Testing write"); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing write")); + _testContextImplementation.GetDiagnosticMessages()!.Should().Contain("1 Testing write"); } public void WriteLineWithMessageShouldWriteToStringWriterForNullCharacters() @@ -250,7 +252,7 @@ public void WriteLineWithMessageShouldWriteToStringWriterForNullCharacters() _testContextImplementation.WriteLine("1 Testing \0 write \0"); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing \\0 write \\0")); + _testContextImplementation.GetDiagnosticMessages()!.Should().Contain("1 Testing \\0 write \\0"); } public void GetDiagnosticMessagesShouldReturnMessagesFromWriteLine() @@ -260,8 +262,8 @@ public void GetDiagnosticMessagesShouldReturnMessagesFromWriteLine() _testContextImplementation.WriteLine("1 Testing write"); _testContextImplementation.WriteLine("2 Its a happy day"); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("1 Testing write")); - Verify(_testContextImplementation.GetDiagnosticMessages()!.Contains("2 Its a happy day")); + _testContextImplementation.GetDiagnosticMessages().Should().Contain("1 Testing write"); + _testContextImplementation.GetDiagnosticMessages().Should().Contain("2 Its a happy day"); } public void ClearDiagnosticMessagesShouldClearMessagesFromWriteLine() @@ -273,7 +275,7 @@ public void ClearDiagnosticMessagesShouldClearMessagesFromWriteLine() _testContextImplementation.ClearDiagnosticMessages(); - Verify(_testContextImplementation.GetDiagnosticMessages() == string.Empty); + _testContextImplementation.GetDiagnosticMessages().Should().Be(string.Empty); } #if NETFRAMEWORK @@ -291,8 +293,8 @@ public void SetDataRowShouldSetDataRowObjectForCurrentRun() _testContextImplementation.SetDataRow(dataTable.Select()[0]); - Verify(2.Equals(_testContextImplementation.DataRow!.ItemArray[0])); - Verify("Hello".Equals(_testContextImplementation.DataRow.ItemArray[1])); + _testContextImplementation.DataRow!.ItemArray[0].Should().Be(2); + _testContextImplementation.DataRow.ItemArray[1].Should().Be("Hello"); } public void SetDataConnectionShouldSetDbConnectionForFetchingData() @@ -305,8 +307,8 @@ public void SetDataConnectionShouldSetDbConnectionForFetchingData() _testContextImplementation.SetDataConnection(connection); - Verify(_testContextImplementation.DataConnection!.ConnectionString - == "Dsn=Excel Files;dbq=.\\data.xls;defaultdir=.; driverid=790;maxbuffersize=2048;pagetimeout=5"); + _testContextImplementation.DataConnection!.ConnectionString + .Should().Be("Dsn=Excel Files;dbq=.\\data.xls;defaultdir=.; driverid=790;maxbuffersize=2048;pagetimeout=5"); } #endif @@ -317,7 +319,7 @@ public void GetResultFilesShouldReturnNullIfNoAddedResultFiles() IList? resultFiles = _testContextImplementation.GetResultFiles(); - Verify(resultFiles is null); + resultFiles.Should().BeNull(); } public void GetResultFilesShouldReturnListOfAddedResultFiles() @@ -329,9 +331,9 @@ public void GetResultFilesShouldReturnListOfAddedResultFiles() IList? resultFiles = _testContextImplementation.GetResultFiles(); - Verify(resultFiles!.Count > 0, "GetResultFiles returned added elements"); - Verify(resultFiles.Contains("C:\\files\\myfile.txt")); - Verify(resultFiles.Contains("C:\\files\\myfile2.txt")); + resultFiles!.Count.Should().BeGreaterThan(0, "GetResultFiles returned added elements"); + resultFiles.Should().Contain("C:\\files\\myfile.txt"); + resultFiles.Should().Contain("C:\\files\\myfile2.txt"); } #endif diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs index 6619a81bb9..a9de17f85a 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; @@ -44,7 +46,7 @@ public TestDeploymentTests() public void GetDeploymentItemsReturnsNullWhenNoDeploymentItems() { MethodInfo methodInfo = typeof(TestDeploymentTests).GetMethod("GetDeploymentItemsReturnsNullWhenNoDeploymentItems")!; - Verify(new TestDeployment().GetDeploymentItems(methodInfo, typeof(TestDeploymentTests), _warnings) is null); + new TestDeployment().GetDeploymentItems(methodInfo, typeof(TestDeploymentTests), _warnings).Should().BeNull(); } public void GetDeploymentItemsReturnsDeploymentItems() @@ -83,7 +85,7 @@ public void GetDeploymentItemsReturnsDeploymentItems() DefaultDeploymentItemOutputDirectory), }; - Verify(expectedDeploymentItems.SequenceEqual(deploymentItems)); + deploymentItems.Should().BeEquivalentTo(expectedDeploymentItems); } #endregion @@ -116,7 +118,7 @@ public void CleanupShouldNotDeleteDirectoriesIfRunSettingsSpecifiesSo() var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); - Verify(testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object)); + testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object).Should().BeTrue(); testDeployment.Cleanup(); @@ -133,7 +135,7 @@ public void CleanupShouldDeleteRootDeploymentDirectory() var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); - Verify(testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object)); + testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object).Should().BeTrue(); // Act. testDeployment.Cleanup(); @@ -145,7 +147,7 @@ public void CleanupShouldDeleteRootDeploymentDirectory() #region GetDeploymentDirectory tests - public void GetDeploymentDirectoryShouldReturnNullIfDeploymentDirectoryIsNull() => Verify(new TestDeployment().GetDeploymentDirectory() is null); + public void GetDeploymentDirectoryShouldReturnNullIfDeploymentDirectoryIsNull() => new TestDeployment().GetDeploymentDirectory().Should().BeNull(); public void GetDeploymentDirectoryShouldReturnDeploymentOutputDirectory() { @@ -157,10 +159,10 @@ public void GetDeploymentDirectoryShouldReturnDeploymentOutputDirectory() var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); - Verify(testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object)); + testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object).Should().BeTrue(); // Act. - Verify(testRunDirectories.OutDirectory == testDeployment.GetDeploymentDirectory()); + testDeployment.GetDeploymentDirectory().Should().Be(testRunDirectories.OutDirectory); } #endregion @@ -191,10 +193,10 @@ public void DeployShouldReturnFalseWhenDeploymentEnabledSetToFalseButHasDeployme mstestSettingsProvider.Load(reader); // Deployment should not happen - Verify(!testDeployment.Deploy(new List { testCase }, null, null!)); + testDeployment.Deploy(new List { testCase }, null, null!).Should().BeFalse(); // Deployment directories should not be created - Verify(testDeployment.GetDeploymentDirectory() is null); + testDeployment.GetDeploymentDirectory().Should().BeNull(); } public void DeployShouldReturnFalseWhenDeploymentEnabledSetToFalseAndHasNoDeploymentItems() @@ -214,10 +216,10 @@ public void DeployShouldReturnFalseWhenDeploymentEnabledSetToFalseAndHasNoDeploy mstestSettingsProvider.Load(reader); // Deployment should not happen - Verify(!testDeployment.Deploy(new List { testCase }, null, null!)); + testDeployment.Deploy(new List { testCase }, null, null!).Should().BeFalse(); // Deployment directories should get created - Verify(testDeployment.GetDeploymentDirectory() is not null); + testDeployment.GetDeploymentDirectory().Should().NotBeNull(); } public void DeployShouldReturnFalseWhenDeploymentEnabledSetToTrueButHasNoDeploymentItems() @@ -237,10 +239,10 @@ public void DeployShouldReturnFalseWhenDeploymentEnabledSetToTrueButHasNoDeploym mstestSettingsProvider.Load(reader); // Deployment should not happen - Verify(!testDeployment.Deploy(new List { testCase }, null, null!)); + testDeployment.Deploy(new List { testCase }, null, null!).Should().BeFalse(); // Deployment directories should get created - Verify(testDeployment.GetDeploymentDirectory() is not null); + testDeployment.GetDeploymentDirectory().Should().NotBeNull(); } // TODO: This test has to have mocks. It actually deploys stuff and we cannot assume that all the dependencies get copied over to bin\debug. @@ -267,10 +269,10 @@ internal void DeployShouldReturnTrueWhenDeploymentEnabledSetToTrueAndHasDeployme mstestSettingsProvider.Load(reader); // Deployment should happen - Verify(testDeployment.Deploy(new List { testCase }, null, new Mock().Object)); + testDeployment.Deploy(new List { testCase }, null, new Mock().Object).Should().BeTrue(); // Deployment directories should get created - Verify(testDeployment.GetDeploymentDirectory() is not null); + testDeployment.GetDeploymentDirectory().Should().NotBeNull(); } #endregion @@ -291,8 +293,8 @@ public void GetDeploymentInformationShouldReturnAppBaseDirectoryIfRunDirectoryIs [TestContext.TestRunResultsDirectoryLabel] = applicationBaseDirectory, [TestContext.TestResultsDirectoryLabel] = applicationBaseDirectory, }; - Verify(properties is not null); - Verify(expectedProperties.SequenceEqual(properties)); + properties.Should().NotBeNull(); + properties.Should().BeEquivalentTo(expectedProperties); } public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceIsNull() @@ -306,7 +308,7 @@ public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceI var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); - Verify(testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object)); + testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object).Should().BeTrue(); // Act. IDictionary properties = TestDeployment.GetDeploymentInformation(null); @@ -321,8 +323,8 @@ public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceI [TestContext.TestResultsDirectoryLabel] = testRunDirectories.InDirectory, }; - Verify(properties is not null); - Verify(expectedProperties.SequenceEqual(properties)); + properties.Should().NotBeNull(); + properties.Should().BeEquivalentTo(expectedProperties); } public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceIsNotNull() @@ -336,7 +338,7 @@ public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceI var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); - Verify(testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object)); + testDeployment.Deploy(new List { testCase }, mockRunContext.Object, new Mock().Object).Should().BeTrue(); // Act. IDictionary properties = TestDeployment.GetDeploymentInformation(typeof(TestDeploymentTests).Assembly.Location); @@ -351,8 +353,8 @@ public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceI [TestContext.TestResultsDirectoryLabel] = testRunDirectories.InDirectory, }; - Verify(properties is not null); - Verify(expectedProperties.SequenceEqual(properties)); + properties.Should().NotBeNull(); + properties.Should().BeEquivalentTo(expectedProperties); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestSourceHostTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestSourceHostTests.cs index ee2fce2c4c..4ce88e1131 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestSourceHostTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestSourceHostTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if !NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -19,8 +21,8 @@ public void CreateInstanceForTypeCreatesAnInstanceOfAGivenTypeThroughDefaultCons { var type = _testSourceHost.CreateInstanceForType(typeof(DummyType), null) as DummyType; - Verify(type is not null); - Verify(type.IsDefaultConstructorCalled); + type.Should().NotBeNull(); + type.IsDefaultConstructorCalled.Should().BeTrue(); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadOperationsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadOperationsTests.cs index 89456b1846..00de96306e 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadOperationsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ThreadOperationsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -22,8 +24,8 @@ private void ExecuteShouldStartTheActionOnANewThread() void Action() => actionThreadID = Environment.CurrentManagedThreadId; CancellationTokenSource tokenSource = new(); - Verify(_asyncOperations.Execute(Action, 10000, tokenSource.Token)); - Verify(Environment.CurrentManagedThreadId != actionThreadID); + _asyncOperations.Execute(Action, 10000, tokenSource.Token).Should().BeTrue(); + Environment.CurrentManagedThreadId.Should().NotBe(actionThreadID); } #endif @@ -32,7 +34,7 @@ private void ExecuteShouldReturnFalseIfTheActionTimesOut() static void Action() => Task.Delay(1000).Wait(); CancellationTokenSource tokenSource = new(); - Verify(!_asyncOperations.Execute(Action, 1, tokenSource.Token)); + _asyncOperations.Execute(Action, 1, tokenSource.Token).Should().BeFalse(); } #pragma warning restore IDE0051 // Remove unused private members } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/AppDomainUtilitiesTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/AppDomainUtilitiesTests.cs index e74e3cd51d..683f1e1331 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/AppDomainUtilitiesTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/AppDomainUtilitiesTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; using TestFramework.ForTestingMSTest; @@ -40,7 +42,7 @@ public void SetConfigurationFileShouldSetOMRedirectionIfConfigFileIsPresent() AppDomainUtilities.SetConfigurationFile(setup, configFile); // Assert Config file being set. - Verify(configFile == setup.ConfigurationFile); + setup.ConfigurationFile.Should().Be(configFile); // Assert Config Bytes. string expectedRedir = @@ -53,7 +55,7 @@ public void SetConfigurationFileShouldSetOMRedirectionIfConfigFileIsPresent() byte[] observedConfigBytes = setup.GetConfigurationBytes(); string observedXml = Encoding.UTF8.GetString(observedConfigBytes); - Verify(SanitizeString(observedXml).Contains(SanitizeString(expectedRedir)), "Config must have OM redirection"); + SanitizeString(observedXml).Should().Contain(SanitizeString(expectedRedir), "Config must have OM redirection"); // Local functions static string SanitizeString(string str) @@ -67,9 +69,9 @@ public void SetConfigurationFileShouldSetToCurrentDomainsConfigFileIfSourceDoesN AppDomainUtilities.SetConfigurationFile(setup, null); // Assert Config file being set. - Verify(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile == setup.ConfigurationFile); + AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.Should().Be(setup.ConfigurationFile); - Verify(setup.GetConfigurationBytes() is null); + setup.GetConfigurationBytes().Should().BeNull(); } public void GetTargetFrameworkVersionFromVersionStringShouldReturnDefaultVersionIfVersionIsPortable() @@ -78,8 +80,8 @@ public void GetTargetFrameworkVersionFromVersionStringShouldReturnDefaultVersion Version version = AppDomainUtilities.GetTargetFrameworkVersionFromVersionString(".NETPortable,Version=v4.5,Profile=Profile259"); - Verify(expected.Major == version.Major); - Verify(expected.Minor == version.Minor); + version.Major.Should().Be(expected.Major); + version.Minor.Should().Be(expected.Minor); } public void GetTargetFrameworkVersionFromVersionStringShouldReturnCorrectVersion() @@ -88,8 +90,8 @@ public void GetTargetFrameworkVersionFromVersionStringShouldReturnCorrectVersion Version version = AppDomainUtilities.GetTargetFrameworkVersionFromVersionString(".NETFramework,Version=v4.5"); - Verify(expected.Major == version.Major); - Verify(expected.Minor == version.Minor); + version.Major.Should().Be(expected.Major); + version.Minor.Should().Be(expected.Minor); } #region Testable Implementations diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs index 578c096bdd..6068c81530 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; @@ -73,13 +75,12 @@ public void DeployShouldReturnFalseWhenNoDeploymentItemsOnTestCase() .Returns([]); #endif - Verify( - !_deploymentUtility.Deploy( - new List { testCase }, - testCase.Source, - _mockRunContext.Object, - _mockTestExecutionRecorder.Object, - testRunDirectories)); + _deploymentUtility.Deploy( + new List { testCase }, + testCase.Source, + _mockRunContext.Object, + _mockTestExecutionRecorder.Object, + testRunDirectories).Should().BeFalse(); } #if NETFRAMEWORK @@ -99,13 +100,12 @@ public void DeployShouldDeploySourceAndItsConfigFile() .Returns([]); // Act. - Verify( - _deploymentUtility.Deploy( - new List { testCase }, - testCase.Source, - _mockRunContext.Object, - _mockTestExecutionRecorder.Object, - testRunDirectories)); + _deploymentUtility.Deploy( + new List { testCase }, + testCase.Source, + _mockRunContext.Object, + _mockTestExecutionRecorder.Object, + testRunDirectories).Should().BeTrue(); // Assert. string? warning; @@ -145,13 +145,12 @@ public void DeployShouldDeployDependentFiles() .Returns([]); // Act. - Verify( - _deploymentUtility.Deploy( - new List { testCase }, - testCase.Source, - _mockRunContext.Object, - _mockTestExecutionRecorder.Object, - testRunDirectories)); + _deploymentUtility.Deploy( + new List { testCase }, + testCase.Source, + _mockRunContext.Object, + _mockTestExecutionRecorder.Object, + testRunDirectories).Should().BeTrue(); // Assert. string? warning; @@ -183,13 +182,12 @@ public void DeployShouldDeploySatelliteAssemblies() .Returns([satelliteFullPath]); // Act. - Verify( - _deploymentUtility.Deploy( - new List { testCase }, - testCase.Source, - _mockRunContext.Object, - _mockTestExecutionRecorder.Object, - testRunDirectories)); + _deploymentUtility.Deploy( + new List { testCase }, + testCase.Source, + _mockRunContext.Object, + _mockTestExecutionRecorder.Object, + testRunDirectories).Should().BeTrue(); // Assert. string? warning; @@ -225,13 +223,12 @@ public void DeployShouldNotDeployIfOutputDirectoryIsInvalid() #endif // Act. - Verify( - _deploymentUtility.Deploy( - new List { testCase }, - testCase.Source, - _mockRunContext.Object, - _mockTestExecutionRecorder.Object, - testRunDirectories)); + _deploymentUtility.Deploy( + new List { testCase }, + testCase.Source, + _mockRunContext.Object, + _mockTestExecutionRecorder.Object, + testRunDirectories).Should().BeTrue(); // Assert. string? warning; @@ -281,13 +278,12 @@ public void DeployShouldDeployContentsOfADirectoryIfSpecified() fu => fu.AddFilesFromDirectory(DefaultDeploymentItemPath, It.IsAny>(), It.IsAny())).Returns(directoryContentFiles); // Act. - Verify( - _deploymentUtility.Deploy( - new List { testCase }, - testCase.Source, - _mockRunContext.Object, - _mockTestExecutionRecorder.Object, - testRunDirectories)); + _deploymentUtility.Deploy( + new List { testCase }, + testCase.Source, + _mockRunContext.Object, + _mockTestExecutionRecorder.Object, + testRunDirectories).Should().BeTrue(); // Assert. string? warning; @@ -326,13 +322,12 @@ public void DeployShouldDeployPdbWithSourceIfPdbFileIsPresentInSourceDirectory() }); // Act. - Verify( - _deploymentUtility.Deploy( - new List { testCase }, - testCase.Source, - _mockRunContext.Object, - _mockTestExecutionRecorder.Object, - testRunDirectories)); + _deploymentUtility.Deploy( + new List { testCase }, + testCase.Source, + _mockRunContext.Object, + _mockTestExecutionRecorder.Object, + testRunDirectories).Should().BeTrue(); // Assert. string sourceFile = Assembly.GetExecutingAssembly().GetName().Name + ".exe"; @@ -382,13 +377,12 @@ public void DeployShouldNotDeployPdbFileOfAssemblyIfPdbFileIsNotPresentInAssembl }); // Act. - Verify( - _deploymentUtility.Deploy( - new List { testCase }, - testCase.Source, - _mockRunContext.Object, - _mockTestExecutionRecorder.Object, - testRunDirectories)); + _deploymentUtility.Deploy( + new List { testCase }, + testCase.Source, + _mockRunContext.Object, + _mockTestExecutionRecorder.Object, + testRunDirectories).Should().BeTrue(); // Assert. _mockFileUtility.Verify( diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs index 0996e422a2..2a8b3acd1b 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; using TestFramework.ForTestingMSTest; @@ -18,11 +20,11 @@ public void GetSpecificCustomAttributesOnAssemblyShouldReturnAllAttributes() List attributes = ReflectionUtility.GetCustomAttributes(asm, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Count == 2); + attributes.Should().NotBeNull(); + attributes.Count.Should().Be(2); string[] expectedAttributes = ["DummyA : a1", "DummyA : a2"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes)).Should().BeTrue(); } internal static string[] GetAttributeValuePairs(IEnumerable attributes) diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/VSInstallationUtilitiesTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/VSInstallationUtilitiesTests.cs index 8d00f9b4fb..ae357edd10 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/VSInstallationUtilitiesTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/VSInstallationUtilitiesTests.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NETFRAMEWORK +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -14,7 +16,7 @@ public void CheckResolutionPathsDoNotContainPrivateAssembliesPathTest() { TestSourceHost isolatedHost = new(null!, null, null); List paths = isolatedHost.GetResolutionPaths(Assembly.GetExecutingAssembly().FullName, true); - Verify(!paths.Contains(EngineConstants.PublicAssemblies) || paths.Contains(EngineConstants.PrivateAssemblies)); + (!paths.Contains(EngineConstants.PublicAssemblies) || paths.Contains(EngineConstants.PrivateAssemblies)).Should().BeTrue(); } } #endif diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/XmlUtilitiesTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/XmlUtilitiesTests.cs index 6f35bd4894..fb3a7050ac 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/XmlUtilitiesTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/XmlUtilitiesTests.cs @@ -3,6 +3,8 @@ #if NETFRAMEWORK +using AwesomeAssertions; + using TestFramework.ForTestingMSTest; using static MSTestAdapter.PlatformServices.UnitTests.Utilities.AppDomainUtilitiesTests; @@ -48,7 +50,7 @@ public void AddAssemblyRedirectionShouldAddRedirectionToAnEmptyXml() expectedConfigBytes = ms.ToArray(); } - Verify(expectedConfigBytes.SequenceEqual(configBytes)); + configBytes.SequenceEqual(expectedConfigBytes).Should().BeTrue(); } public void AddAssemblyRedirectionShouldAddRedirectionToAnEmptyConfig() @@ -88,7 +90,7 @@ public void AddAssemblyRedirectionShouldAddRedirectionToAnEmptyConfig() expectedConfigBytes = ms.ToArray(); } - Verify(expectedConfigBytes.SequenceEqual(configBytes)); + configBytes.SequenceEqual(expectedConfigBytes).Should().BeTrue(); } public void AddAssemblyRedirectionShouldAddRedirectionToAConfigWithARuntimeSectionOnly() @@ -132,7 +134,7 @@ public void AddAssemblyRedirectionShouldAddRedirectionToAConfigWithARuntimeSecti expectedConfigBytes = ms.ToArray(); } - Verify(expectedConfigBytes.SequenceEqual(configBytes)); + configBytes.SequenceEqual(expectedConfigBytes).Should().BeTrue(); } public void AddAssemblyRedirectionShouldAddRedirectionToAConfigWithRedirections() @@ -186,7 +188,7 @@ public void AddAssemblyRedirectionShouldAddRedirectionToAConfigWithRedirections( expectedConfigBytes = ms.ToArray(); } - Verify(expectedConfigBytes.SequenceEqual(configBytes)); + configBytes.SequenceEqual(expectedConfigBytes).Should().BeTrue(); } } #endif diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs index 5f83427888..ca93865092 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; using Moq; @@ -22,13 +24,13 @@ public FileUtilityTests() public void ReplaceInvalidFileNameCharactersShouldReturnFileNameIfItHasNoInvalidChars() { string fileName = "galaxy"; - Verify(fileName == FileUtility.ReplaceInvalidFileNameCharacters(fileName)); + FileUtility.ReplaceInvalidFileNameCharacters(fileName).Should().Be(fileName); } public void ReplaceInvalidFileNameCharactersShouldReplaceInvalidChars() { string fileName = "galaxy<>far:far?away"; - Verify(FileUtility.ReplaceInvalidFileNameCharacters(fileName) == "galaxy__far_far_away"); + FileUtility.ReplaceInvalidFileNameCharacters(fileName).Should().Be("galaxy__far_far_away"); } #region AddFilesFromDirectory tests @@ -42,7 +44,7 @@ public void AddFilesInADirectoryShouldReturnAllTopLevelFilesInADirectory() List files = _fileUtility.Object.AddFilesFromDirectory("C:\\randomclock", false); - Verify(topLevelFiles.SequenceEqual(files)); + topLevelFiles.SequenceEqual(files).Should().BeTrue(); } public void AddFilesInADirectoryShouldReturnAllFilesUnderSubFolders() @@ -62,7 +64,7 @@ public void AddFilesInADirectoryShouldReturnAllFilesUnderSubFolders() List files = _fileUtility.Object.AddFilesFromDirectory("MainClock", false); - Verify(allFiles.SequenceEqual(files)); + allFiles.SequenceEqual(files).Should().BeTrue(); } public void AddFilesInADirectoryShouldReturnAllFilesUnderSubFoldersEvenIfAFolderIsEmpty() @@ -85,7 +87,7 @@ public void AddFilesInADirectoryShouldReturnAllFilesUnderSubFoldersEvenIfAFolder string[] expectedFiles = new string[allFiles.Length - 1]; Array.Copy(allFiles, 0, expectedFiles, 0, 6); - Verify(expectedFiles.SequenceEqual(files)); + expectedFiles.SequenceEqual(files).Should().BeTrue(); } public void AddFilesWithIgnoreDirectory() @@ -119,11 +121,11 @@ public void AddFilesWithIgnoreDirectory() Console.WriteLine($"File to validate {sourceFile}"); if (sourceFile.Contains("Results")) { - Verify(!files.Any(file => file.Contains("Results")), $"{sourceFile} returned in the list from AddFilesFromDirectory"); + files.Any(file => file.Contains("Results")).Should().BeFalse($"{sourceFile} returned in the list from AddFilesFromDirectory"); } else { - Verify(files.Any(file => file.Equals(sourceFile, StringComparison.OrdinalIgnoreCase)), $"{sourceFile} not returned in the list from AddFilesFromDirectory"); + files.Any(file => file.Equals(sourceFile, StringComparison.OrdinalIgnoreCase)).Should().BeTrue($"{sourceFile} not returned in the list from AddFilesFromDirectory"); } } } @@ -156,7 +158,7 @@ public void AddFilesWithNoIgnoreDirectory() // Validate foreach (string sourceFile in allFiles) { - Verify(files.Any(file => file.Equals(sourceFile, StringComparison.OrdinalIgnoreCase)), $"{sourceFile} not returned in the list from AddFilesFromDirectory"); + files.Any(file => file.Equals(sourceFile, StringComparison.OrdinalIgnoreCase)).Should().BeTrue($"{sourceFile} not returned in the list from AddFilesFromDirectory"); } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs index 539c42f503..f84165fe42 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Deployment; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Resources; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; @@ -45,8 +47,8 @@ public void GetClassLevelDeploymentItemsShouldReturnEmptyListWhenNoDeploymentIte .Returns([]); IList deploymentItems = _deploymentItemUtility.GetClassLevelDeploymentItems(typeof(DeploymentItemUtilityTests), _warnings); - Verify(deploymentItems is not null); - Verify(deploymentItems.Count == 0); + deploymentItems.Should().NotBeNull(); + deploymentItems.Count.Should().Be(0); } public void GetClassLevelDeploymentItemsShouldReturnADeploymentItem() @@ -66,7 +68,7 @@ public void GetClassLevelDeploymentItemsShouldReturnADeploymentItem() _defaultDeploymentItemPath, _defaultDeploymentItemOutputDirectory), }; - Verify(expectedDeploymentItems.SequenceEqual(deploymentItems.ToArray())); + expectedDeploymentItems.SequenceEqual(deploymentItems.ToArray()).Should().BeTrue(); } public void GetClassLevelDeploymentItemsShouldReturnMoreThanOneDeploymentItems() @@ -97,7 +99,7 @@ public void GetClassLevelDeploymentItemsShouldReturnMoreThanOneDeploymentItems() deploymentItemAttributes[1].Value), }; - Verify(expectedDeploymentItems.SequenceEqual(deploymentItems.ToArray())); + expectedDeploymentItems.SequenceEqual(deploymentItems.ToArray()).Should().BeTrue(); } public void GetClassLevelDeploymentItemsShouldNotReturnDuplicateDeploymentItemEntries() @@ -125,7 +127,7 @@ public void GetClassLevelDeploymentItemsShouldNotReturnDuplicateDeploymentItemEn _defaultDeploymentItemOutputDirectory) ]; - Verify(expectedDeploymentItems.SequenceEqual(deploymentItems.ToArray())); + expectedDeploymentItems.SequenceEqual(deploymentItems.ToArray()).Should().BeTrue(); } public void GetClassLevelDeploymentItemsShouldReportWarningsForInvalidDeploymentItems() @@ -150,9 +152,9 @@ public void GetClassLevelDeploymentItemsShouldReportWarningsForInvalidDeployment _defaultDeploymentItemOutputDirectory), }; - Verify(expectedDeploymentItems.SequenceEqual(deploymentItems.ToArray())); - Verify(_warnings.Count == 1); - Verify(_warnings.ToArray()[0].Contains(Resource.DeploymentItemPathCannotBeNullOrEmpty)); + expectedDeploymentItems.SequenceEqual(deploymentItems.ToArray()).Should().BeTrue(); + _warnings.Count.Should().Be(1); + _warnings.ToArray()[0].Contains(Resource.DeploymentItemPathCannotBeNullOrEmpty).Should().BeTrue(); } #endregion @@ -165,7 +167,7 @@ public void GetDeploymentItemsShouldReturnNullOnNoDeploymentItems() _mockReflectionUtility.Setup(x => x.GetCustomAttributes(method, typeof(DeploymentItemAttribute))) .Returns([]); - Verify(_deploymentItemUtility.GetDeploymentItems(method, null!, _warnings) is null); + _deploymentItemUtility.GetDeploymentItems(method, null!, _warnings).Should().BeNull(); } public void GetDeploymentItemsShouldReturnMethodLevelDeploymentItemsOnly() @@ -190,7 +192,7 @@ public void GetDeploymentItemsShouldReturnMethodLevelDeploymentItemsOnly() null!, _warnings); - Verify(deploymentItemAttributes.SequenceEqual(deploymentItems)); + deploymentItemAttributes.SequenceEqual(deploymentItems).Should().BeTrue(); } public void GetDeploymentItemsShouldReturnClassLevelDeploymentItemsOnly() @@ -224,7 +226,7 @@ public void GetDeploymentItemsShouldReturnClassLevelDeploymentItemsOnly() _defaultDeploymentItemOutputDirectory) ]; - Verify(expectedDeploymentItems.SequenceEqual(deploymentItems)); + expectedDeploymentItems.SequenceEqual(deploymentItems).Should().BeTrue(); } public void GetDeploymentItemsShouldReturnClassAndMethodLevelDeploymentItems() @@ -265,7 +267,7 @@ public void GetDeploymentItemsShouldReturnClassAndMethodLevelDeploymentItems() _defaultDeploymentItemOutputDirectory), }; - Verify(expectedDeploymentItems.SequenceEqual(deploymentItems)); + expectedDeploymentItems.SequenceEqual(deploymentItems).Should().BeTrue(); } public void GetDeploymentItemsShouldReturnClassAndMethodLevelDeploymentItemsWithoutDuplicates() @@ -315,7 +317,7 @@ public void GetDeploymentItemsShouldReturnClassAndMethodLevelDeploymentItemsWith _defaultDeploymentItemOutputDirectory), }; - Verify(expectedDeploymentItems.SequenceEqual(deploymentItems)); + expectedDeploymentItems.SequenceEqual(deploymentItems).Should().BeTrue(); } #endregion @@ -324,28 +326,26 @@ public void GetDeploymentItemsShouldReturnClassAndMethodLevelDeploymentItemsWith public void IsValidDeploymentItemShouldReportWarningIfSourcePathIsNull() { - Verify(!DeploymentItemUtility.IsValidDeploymentItem(null, _defaultDeploymentItemOutputDirectory, out string? warning)); - - Verify(Resource.DeploymentItemPathCannotBeNullOrEmpty.Contains(warning)); + DeploymentItemUtility.IsValidDeploymentItem(null, _defaultDeploymentItemOutputDirectory, out string? warning).Should().BeFalse(); + Resource.DeploymentItemPathCannotBeNullOrEmpty.Should().Contain(warning!); } public void IsValidDeploymentItemShouldReportWarningIfSourcePathIsEmpty() { - Verify(!DeploymentItemUtility.IsValidDeploymentItem(string.Empty, _defaultDeploymentItemOutputDirectory, out string? warning)); - - Verify(Resource.DeploymentItemPathCannotBeNullOrEmpty.Contains(warning)); + DeploymentItemUtility.IsValidDeploymentItem(string.Empty, _defaultDeploymentItemOutputDirectory, out string? warning).Should().BeFalse(); + Resource.DeploymentItemPathCannotBeNullOrEmpty.Should().Contain(warning!); } public void IsValidDeploymentItemShouldReportWarningIfDeploymentOutputDirectoryIsNull() { - Verify(!DeploymentItemUtility.IsValidDeploymentItem(_defaultDeploymentItemPath, null, out string? warning)); + DeploymentItemUtility.IsValidDeploymentItem(_defaultDeploymentItemPath, null, out string? warning).Should().BeFalse(); StringAssert.Contains(Resource.DeploymentItemOutputDirectoryCannotBeNull, warning); } public void IsValidDeploymentItemShouldReportWarningIfSourcePathHasInvalidCharacters() { - Verify(!DeploymentItemUtility.IsValidDeploymentItem("C:<>", _defaultDeploymentItemOutputDirectory, out string? warning)); + DeploymentItemUtility.IsValidDeploymentItem("C:<>", _defaultDeploymentItemOutputDirectory, out string? warning).Should().BeFalse(); StringAssert.Contains( string.Format( @@ -358,7 +358,7 @@ public void IsValidDeploymentItemShouldReportWarningIfSourcePathHasInvalidCharac public void IsValidDeploymentItemShouldReportWarningIfOutputDirectoryHasInvalidCharacters() { - Verify(!DeploymentItemUtility.IsValidDeploymentItem(_defaultDeploymentItemPath, "<>", out string? warning)); + DeploymentItemUtility.IsValidDeploymentItem(_defaultDeploymentItemPath, "<>", out string? warning).Should().BeFalse(); StringAssert.Contains( string.Format( @@ -371,7 +371,7 @@ public void IsValidDeploymentItemShouldReportWarningIfOutputDirectoryHasInvalidC public void IsValidDeploymentItemShouldReportWarningIfDeploymentOutputDirectoryIsRooted() { - Verify(!DeploymentItemUtility.IsValidDeploymentItem(_defaultDeploymentItemPath, "C:\\temp", out string? warning)); + DeploymentItemUtility.IsValidDeploymentItem(_defaultDeploymentItemPath, "C:\\temp", out string? warning).Should().BeFalse(); StringAssert.Contains( string.Format( @@ -383,9 +383,9 @@ public void IsValidDeploymentItemShouldReportWarningIfDeploymentOutputDirectoryI public void IsValidDeploymentItemShouldReturnTrueForAValidDeploymentItem() { - Verify(DeploymentItemUtility.IsValidDeploymentItem(_defaultDeploymentItemPath, _defaultDeploymentItemOutputDirectory, out string? warning)); + DeploymentItemUtility.IsValidDeploymentItem(_defaultDeploymentItemPath, _defaultDeploymentItemOutputDirectory, out string? warning).Should().BeTrue(); - Verify(warning is null); + warning.Should().BeNull(); } #endregion @@ -396,7 +396,7 @@ public void HasDeployItemsShouldReturnFalseForNoDeploymentItems() TestCase testCase = new("A.C.M", new Uri("executor://testExecutor"), "A"); testCase.SetPropertyValue(DeploymentItemsProperty, null); - Verify(!DeploymentItemUtility.HasDeploymentItems(testCase)); + DeploymentItemUtility.HasDeploymentItems(testCase).Should().BeFalse(); } public void HasDeployItemsShouldReturnTrueWhenDeploymentItemsArePresent() @@ -410,7 +410,7 @@ public void HasDeployItemsShouldReturnTrueWhenDeploymentItemsArePresent() ]; testCase.SetPropertyValue(DeploymentItemsProperty, kvpArray); - Verify(DeploymentItemUtility.HasDeploymentItems(testCase)); + DeploymentItemUtility.HasDeploymentItems(testCase).Should().BeTrue(); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13ReflectionUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13ReflectionUtilityTests.cs index c22a003840..437d051c22 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13ReflectionUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13ReflectionUtilityTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Utilities; using TestFramework.ForTestingMSTest; @@ -17,11 +19,11 @@ public void GetCustomAttributesShouldReturnAllAttributes() IReadOnlyList attributes = ReflectionUtility.GetCustomAttributes(methodInfo); - Verify(attributes is not null); - Verify(attributes.Count == 2); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(2); string[] expectedAttributes = ["DummyA : base", "DummySingleA : base"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } public void GetCustomAttributesShouldReturnAllAttributesWithBaseInheritance() @@ -30,12 +32,12 @@ public void GetCustomAttributesShouldReturnAllAttributesWithBaseInheritance() IReadOnlyList attributes = ReflectionUtility.GetCustomAttributes(methodInfo); - Verify(attributes is not null); - Verify(attributes.Count == 3); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(3); // Notice that the DummySingleA on the base method does not show up since it can only be defined once. string[] expectedAttributes = ["DummyA : derived", "DummySingleA : derived", "DummyA : base"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } public void GetCustomAttributesOnTypeShouldReturnAllAttributes() @@ -44,11 +46,11 @@ public void GetCustomAttributesOnTypeShouldReturnAllAttributes() IReadOnlyList attributes = ReflectionUtility.GetCustomAttributes(type); - Verify(attributes is not null); - Verify(attributes.Count == 1); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(1); string[] expectedAttributes = ["DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } public void GetCustomAttributesOnTypeShouldReturnAllAttributesWithBaseInheritance() @@ -57,11 +59,11 @@ public void GetCustomAttributesOnTypeShouldReturnAllAttributesWithBaseInheritanc IReadOnlyList attributes = ReflectionUtility.GetCustomAttributes(type); - Verify(attributes is not null); - Verify(attributes.Count == 2); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(2); string[] expectedAttributes = ["DummyA : a", "DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } public void GetSpecificCustomAttributesShouldReturnAllAttributes() @@ -70,11 +72,11 @@ public void GetSpecificCustomAttributesShouldReturnAllAttributes() IReadOnlyList attributes = ReflectionUtility.GetCustomAttributesCore(methodInfo, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Count == 1); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(1); string[] expectedAttributes = ["DummyA : base"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } public void GetSpecificCustomAttributesShouldReturnAllAttributesWithBaseInheritance() @@ -83,11 +85,11 @@ public void GetSpecificCustomAttributesShouldReturnAllAttributesWithBaseInherita IReadOnlyList attributes = ReflectionUtility.GetCustomAttributesCore(methodInfo, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Count == 2); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(2); string[] expectedAttributes = ["DummyA : derived", "DummyA : base"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } public void GetSpecificCustomAttributesOnTypeShouldReturnAllAttributes() @@ -96,11 +98,11 @@ public void GetSpecificCustomAttributesOnTypeShouldReturnAllAttributes() IReadOnlyList attributes = ReflectionUtility.GetCustomAttributesCore(type, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Count == 1); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(1); string[] expectedAttributes = ["DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } public void GetSpecificCustomAttributesOnTypeShouldReturnAllAttributesWithBaseInheritance() @@ -109,11 +111,11 @@ public void GetSpecificCustomAttributesOnTypeShouldReturnAllAttributesWithBaseIn IReadOnlyList attributes = ReflectionUtility.GetCustomAttributesCore(type, typeof(DummyAAttribute)); - Verify(attributes is not null); - Verify(attributes.Count == 2); + attributes.Should().NotBeNull(); + attributes.Should().HaveCount(2); string[] expectedAttributes = ["DummyA : a", "DummyA : ba"]; - Verify(expectedAttributes.SequenceEqual(GetAttributeValuePairs(attributes))); + GetAttributeValuePairs(attributes).Should().Equal(expectedAttributes); } internal static List GetAttributeValuePairs(IEnumerable attributes) diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/XxHash128Tests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/XxHash128Tests.cs index 59811406ca..06293a7d5e 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/XxHash128Tests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/XxHash128Tests.cs @@ -3,6 +3,8 @@ using System.Buffers.Binary; +using AwesomeAssertions; + using TestFramework.ForTestingMSTest; using TestFx.Hashing; @@ -14,10 +16,14 @@ public class XxHash128Tests : TestContainer { public void Hash_InvalidInputs_Throws() { - VerifyThrows(() => XxHash128.Hash(null!)); - VerifyThrows(() => XxHash128.Hash(null!, 42)); + Action action = () => XxHash128.Hash(null!); + action.Should().Throw(); + + action = () => XxHash128.Hash(null!, 42); + action.Should().Throw(); - VerifyThrows(() => XxHash128.Hash([1, 2, 3], new byte[7])); + action = () => XxHash128.Hash([1, 2, 3], new byte[7]); + action.Should().Throw(); } public void Hash_OneShot_Expected() @@ -36,12 +42,12 @@ public void Hash_OneShot_Expected() // Validate `byte[] XxHash128.Hash` with and without a seed if (test.Seed == 0) { - Verify(expectedHash128 == ReadHashBigEndian(XxHash128.Hash(input))); + ReadHashBigEndian(XxHash128.Hash(input)).Should().Be(expectedHash128); // TestFx-specific: We don't have ROS overload. // Verify(expectedHash128 == ReadHashBigEndian(XxHash128.Hash((ReadOnlySpan)input))); } - Verify(expectedHash128 == ReadHashBigEndian(XxHash128.Hash(input, test.Seed))); + ReadHashBigEndian(XxHash128.Hash(input, test.Seed)).Should().Be(expectedHash128); // TestFx-specific: We don't have ROS overload. // Verify(expectedHash128 == ReadHashBigEndian(XxHash128.Hash((ReadOnlySpan)input, test.Seed))); #if NET @@ -56,27 +62,27 @@ public void Hash_OneShot_Expected() if (test.Seed == 0) { Array.Clear(destination, 0, destination.Length); - Verify(XxHash128.TryHash(input, destination, out bytesWritten)); - Verify(bytesWritten == 16); - Verify(expectedHash128 == ReadHashBigEndian(destination)); + XxHash128.TryHash(input, destination, out bytesWritten).Should().BeTrue(); + bytesWritten.Should().Be(16); + ReadHashBigEndian(destination).Should().Be(expectedHash128); } Array.Clear(destination, 0, destination.Length); - Verify(XxHash128.TryHash(input, destination, out bytesWritten, test.Seed)); - Verify(bytesWritten == 16); - Verify(expectedHash128 == ReadHashBigEndian(destination)); + XxHash128.TryHash(input, destination, out bytesWritten, test.Seed).Should().BeTrue(); + bytesWritten.Should().Be(16); + ReadHashBigEndian(destination).Should().Be(expectedHash128); // Validate `XxHash128.Hash(span, out int)` with and without a seed if (test.Seed == 0) { Array.Clear(destination, 0, destination.Length); - Verify(XxHash128.Hash(input, destination) == 16); - Verify(expectedHash128 == ReadHashBigEndian(destination)); + XxHash128.Hash(input, destination).Should().Be(16); + ReadHashBigEndian(destination).Should().Be(expectedHash128); } Array.Clear(destination, 0, destination.Length); - Verify(XxHash128.Hash(input, destination, test.Seed) == 16); - Verify(expectedHash128 == ReadHashBigEndian(destination)); + XxHash128.Hash(input, destination, test.Seed).Should().Be(16); + ReadHashBigEndian(destination).Should().Be(expectedHash128); } } @@ -119,27 +125,27 @@ public void Hash_Streaming_Expected() // Validate that the hash we get from doing a one-shot of all the data up to this point // matches the incremental hash for the data appended until now. #if NET - Verify(XxHash128.HashToUInt128(asciiBytes.AsSpan(0, processed), test.Seed) == hash.GetCurrentHashAsUInt128()); + hash.GetCurrentHashAsUInt128().Should().Be(XxHash128.HashToUInt128(asciiBytes.AsSpan(0, processed), test.Seed)); #endif // TestFx-specific: We don't have TryGetCurrentHash, so we assign GetCurrentHash directly to destination. destination = hash.GetCurrentHash(); // Verify(hash.TryGetCurrentHash(destination, out int bytesWritten)); // TestFx-specific: We don't have Hash overload for span. So we call ToArray. - Verify(XxHash128.Hash(asciiBytes.AsSpan(0, processed).ToArray(), destination2, test.Seed) == 16); - Verify(destination.SequenceEqual(destination2)); + XxHash128.Hash(asciiBytes.AsSpan(0, processed).ToArray(), destination2, test.Seed).Should().Be(16); + destination.Should().Equal(destination2); // Verify(bytesWritten == 16); } // Validate the final hash code. #if NET - Verify(new UInt128(test.HashHigh, test.HashLow) == hash.GetCurrentHashAsUInt128()); + hash.GetCurrentHashAsUInt128().Should().Be(new UInt128(test.HashHigh, test.HashLow)); #endif Array.Clear(destination, 0, destination.Length); // TestFx-specific: We don't have GetHashAndReset. So, we just call GetCurrentHash followed by Reset. destination = hash.GetCurrentHash(); hash.Reset(); // Verify(hash.GetHashAndReset(destination) == 16); - Verify(expectedHash128 == ReadHashBigEndian(destination)); + ReadHashBigEndian(destination).Should().Be(expectedHash128); } } } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ns10TestSourceTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ns10TestSourceTests.cs index 9421b7dacd..316205b0c7 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ns10TestSourceTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/ns10TestSourceTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using TestFramework.ForTestingMSTest; @@ -14,23 +16,23 @@ public class TestSourceTests : TestContainer public TestSourceTests() => _testSource = new TestSourceHandler(); public void ValidSourceExtensionsShouldContainDllExtensions() - => Verify(_testSource.ValidSourceExtensions.ToList().Contains(".dll")); + => _testSource.ValidSourceExtensions.ToList().Should().Contain(".dll"); public void ValidSourceExtensionsShouldContainExeExtensions() - => Verify(_testSource.ValidSourceExtensions.ToList().Contains(".exe")); + => _testSource.ValidSourceExtensions.ToList().Should().Contain(".exe"); public void IsAssemblyReferencedShouldReturnTrueIfSourceOrAssemblyNameIsNull() { - Verify(_testSource.IsAssemblyReferenced(null!, null!)); - Verify(_testSource.IsAssemblyReferenced(null!, string.Empty)); - Verify(_testSource.IsAssemblyReferenced(new AssemblyName(), null!)); + _testSource.IsAssemblyReferenced(null!, null!).Should().BeTrue(); + _testSource.IsAssemblyReferenced(null!, string.Empty).Should().BeTrue(); + _testSource.IsAssemblyReferenced(new AssemblyName(), null!).Should().BeTrue(); } public void IsAssemblyReferencedShouldReturnTrueForAllSourceOrAssemblyNames() { #if !NETFRAMEWORK #pragma warning disable IDE0022 // Use expression body for method - Verify(_testSource.IsAssemblyReferenced(new AssemblyName("ReferenceAssembly"), "SourceAssembly")); + _testSource.IsAssemblyReferenced(new AssemblyName("ReferenceAssembly"), "SourceAssembly").Should().BeTrue(); #pragma warning restore IDE0022 // Use expression body for method #endif } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj b/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj index c5e56de437..9bedf38e43 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestAdapter.UnitTests.csproj @@ -27,6 +27,7 @@ + diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestDiscovererTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/MSTestDiscovererTests.cs index 9c7c8944bc..ff1c32bd94 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestDiscovererTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestDiscovererTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface; @@ -53,54 +55,54 @@ protected override void Dispose(bool disposing) public void MSTestDiscovererHasMSTestAdapterAsExecutorUri() { DefaultExecutorUriAttribute attribute = typeof(MSTestDiscoverer).GetCustomAttributes().First(); - Verify(attribute is not null); - Verify(attribute.ExecutorUri == "executor://MSTestAdapter/v4"); + attribute.Should().NotBeNull(); + attribute.ExecutorUri.Should().Be("executor://MSTestAdapter/v4"); } public void MSTestDiscovererHasXapAsFileExtension() { IEnumerable attributes = typeof(MSTestDiscoverer).GetCustomAttributes(); - Verify(attributes is not null); - Verify(attributes.Count(attribute => attribute.FileExtension == ".xap") == 1); + attributes.Should().NotBeNull(); + attributes.Count(attribute => attribute.FileExtension == ".xap").Should().Be(1); } public void MSTestDiscovererHasAppxAsFileExtension() { IEnumerable attributes = typeof(MSTestDiscoverer).GetCustomAttributes(); - Verify(attributes is not null); - Verify(attributes.Count(attribute => attribute.FileExtension == ".appx") == 1); + attributes.Should().NotBeNull(); + attributes.Count(attribute => attribute.FileExtension == ".appx").Should().Be(1); } public void MSTestDiscovererHasDllAsFileExtension() { IEnumerable attributes = typeof(MSTestDiscoverer).GetCustomAttributes(); - Verify(attributes is not null); - Verify(attributes.Count(attribute => attribute.FileExtension == ".dll") == 1); + attributes.Should().NotBeNull(); + attributes.Count(attribute => attribute.FileExtension == ".dll").Should().Be(1); } public void MSTestDiscovererHasExeAsFileExtension() { IEnumerable attributes = typeof(MSTestDiscoverer).GetCustomAttributes(); - Verify(attributes is not null); - Verify(attributes.Count(attribute => attribute.FileExtension == ".exe") == 1); + object value = attributes.Should().NotBeNull(); + attributes.Count(attribute => attribute.FileExtension == ".exe").Should().Be(1); } public void DiscoverTestsShouldThrowIfSourcesIsNull() { - void A() => _discoverer.DiscoverTests(null!, _mockDiscoveryContext.Object, _mockMessageLogger.Object, _mockTestCaseDiscoverySink.Object); - VerifyThrows(A); + Action action = () => _discoverer.DiscoverTests(null!, _mockDiscoveryContext.Object, _mockMessageLogger.Object, _mockTestCaseDiscoverySink.Object); + action.Should().Throw(); } public void DiscoverTestsShouldThrowIfDiscoverySinkIsNull() { - void A() => _discoverer.DiscoverTests(new List(), _mockDiscoveryContext.Object, _mockMessageLogger.Object, null!); - VerifyThrows(A); + Action action = () => _discoverer.DiscoverTests(new List(), _mockDiscoveryContext.Object, _mockMessageLogger.Object, null!); + action.Should().Throw(); } public void DiscoverTestsShouldThrowIfLoggerIsNull() { - void A() => _discoverer.DiscoverTests(new List(), _mockDiscoveryContext.Object, null!, _mockTestCaseDiscoverySink.Object); - VerifyThrows(A); + Action action = () => _discoverer.DiscoverTests(new List(), _mockDiscoveryContext.Object, null!, _mockTestCaseDiscoverySink.Object); + action.Should().Throw(); } public void DiscoverTestsShouldThrowIfSourcesAreNotValid() @@ -109,8 +111,8 @@ public void DiscoverTestsShouldThrowIfSourcesAreNotValid() _mockTestSourceHandler.Setup(tsv => tsv.ValidSourceExtensions) .Returns(new List { }); - void A() => _discoverer.DiscoverTests(new List(), _mockDiscoveryContext.Object, _mockMessageLogger.Object, _mockTestCaseDiscoverySink.Object); - VerifyThrows(A); + Action action = () => _discoverer.DiscoverTests(new List(), _mockDiscoveryContext.Object, _mockMessageLogger.Object, _mockTestCaseDiscoverySink.Object); + action.Should().Throw(); } public void DiscoverTestsShouldNotThrowIfDiscoveryContextIsNull() @@ -206,25 +208,26 @@ public void AreValidSourcesShouldThrowIfPlatformsValidSourceExtensionsIsNull() { _mockTestSourceHandler.SetupGet(ts => ts.ValidSourceExtensions).Returns((List)null!); var sources = new List { "dummy" }; - VerifyThrows(() => MSTestDiscovererHelpers.AreValidSources(sources, _mockTestSourceHandler.Object)); + Action action = () => MSTestDiscovererHelpers.AreValidSources(sources, _mockTestSourceHandler.Object); + action.Should().Throw(); } public void AreValidSourcesShouldReturnFalseIfValidSourceExtensionsIsEmpty() { _mockTestSourceHandler.SetupGet(ts => ts.ValidSourceExtensions).Returns(new List { }); - Verify(!MSTestDiscovererHelpers.AreValidSources(new List { "dummy.te" }, _mockTestSourceHandler.Object)); + MSTestDiscovererHelpers.AreValidSources(new List { "dummy.te" }, _mockTestSourceHandler.Object).Should().BeFalse(); } public void AreValidSourcesShouldReturnTrueForValidSourceExtensions() { _mockTestSourceHandler.SetupGet(ts => ts.ValidSourceExtensions).Returns(new List { ".te" }); - Verify(MSTestDiscovererHelpers.AreValidSources(new List { "dummy.te" }, _mockTestSourceHandler.Object)); + MSTestDiscovererHelpers.AreValidSources(new List { "dummy.te" }, _mockTestSourceHandler.Object).Should().BeTrue(); } public void AreValidSourcesShouldReturnFalseForInvalidSourceExtensions() { _mockTestSourceHandler.SetupGet(ts => ts.ValidSourceExtensions).Returns(new List { ".nte", ".tep" }); - Verify(!MSTestDiscovererHelpers.AreValidSources(new List { "dummy.te" }, _mockTestSourceHandler.Object)); + MSTestDiscovererHelpers.AreValidSources(new List { "dummy.te" }, _mockTestSourceHandler.Object).Should().BeFalse(); } [TestClass] diff --git a/test/UnitTests/MSTestAdapter.UnitTests/MSTestExecutorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/MSTestExecutorTests.cs index 413944208d..bc41d98845 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/MSTestExecutorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/MSTestExecutorTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using AwesomeAssertions; + using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -33,7 +35,7 @@ public void MSTestExecutorShouldProvideTestExecutionUri() var extensionUriString = (ExtensionUriAttribute)testExecutor.GetType().GetCustomAttributes(typeof(ExtensionUriAttribute), false).Single(); - Verify(extensionUriString.ExtensionUri == EngineConstants.ExecutorUriString); + extensionUriString.ExtensionUri.Should().Be(EngineConstants.ExecutorUriString); } public async Task RunTestsShouldNotExecuteTestsIfTestSettingsIsGiven() diff --git a/test/Utilities/TestFramework.ForTestingMSTest/TestContainer.cs b/test/Utilities/TestFramework.ForTestingMSTest/TestContainer.cs index 72a81401cc..0e1ce1a995 100644 --- a/test/Utilities/TestFramework.ForTestingMSTest/TestContainer.cs +++ b/test/Utilities/TestFramework.ForTestingMSTest/TestContainer.cs @@ -10,8 +10,6 @@ namespace TestFramework.ForTestingMSTest; /// public abstract class TestContainer : IDisposable { - internal static readonly string IsVerifyException = nameof(IsVerifyException); - /// /// Initializes a new instance of the class. /// Constructor is used to provide some initialization before each test. @@ -46,122 +44,4 @@ public void Dispose() Dispose(disposing: true); GC.SuppressFinalize(this); } - - public static void Verify( - [DoesNotReturnIf(false)] bool condition, - string? message = null, - [CallerArgumentExpression(nameof(condition))] string? expression = default, - [CallerMemberName] string? caller = default, - [CallerFilePath] string? filePath = default, - [CallerLineNumber] int lineNumber = default) - { - if (!condition) - { - Throw(message, expression, caller, filePath, lineNumber); - } - } - - public static Exception VerifyThrows( - Action action, - [CallerArgumentExpression(nameof(action))] string? expression = default, - [CallerMemberName] string? caller = default, - [CallerFilePath] string? filePath = default, - [CallerLineNumber] int lineNumber = default) - { - try - { - action(); - } - catch (Exception ex) - { - return ex; - } - - Throw(null, expression, caller, filePath, lineNumber); - return null; - } - - public static async Task VerifyThrowsAsync( - Func taskGetter, - [CallerArgumentExpression(nameof(taskGetter))] string? expression = default, - [CallerMemberName] string? caller = default, - [CallerFilePath] string? filePath = default, - [CallerLineNumber] int lineNumber = default) - { - try - { - await taskGetter(); - } - catch (Exception ex) - { - return ex; - } - - Throw(null, expression, caller, filePath, lineNumber); - return null; - } - - public static T VerifyThrows( - Action action, - [CallerArgumentExpression(nameof(action))] - string? expression = default, - [CallerMemberName] string? caller = default, - [CallerFilePath] string? filePath = default, - [CallerLineNumber] int lineNumber = default) - where T : Exception - { - try - { - action(); - } - catch (T ex) - { - return ex; - } - - Throw(null, expression, caller, filePath, lineNumber); - return null; - } - - public static async Task VerifyThrowsAsync( - Func taskGetter, - [CallerArgumentExpression(nameof(taskGetter))] - string? expression = default, - [CallerMemberName] string? caller = default, - [CallerFilePath] string? filePath = default, - [CallerLineNumber] int lineNumber = default) - where T : Exception - { - try - { - await taskGetter(); - } - catch (T ex) - { - return ex; - } - - Throw(null, expression, caller, filePath, lineNumber); - return null; - } - - public static void Fail( - [CallerMemberName] string? caller = default, - [CallerFilePath] string? filePath = default, - [CallerLineNumber] int lineNumber = default) - => Throw(null, string.Empty, caller, filePath, lineNumber); - - [DoesNotReturn] - private static void Throw(string? message, string? expression, string? caller, string? filePath, int lineNumber) - { - string exceptionMessage = $"Verification failed for {expression ?? ""} at line {lineNumber} of method '{caller ?? ""}' in file '{filePath ?? ""}'."; - if (message is not null) - { - exceptionMessage += Environment.NewLine + message; - } - - var verifyException = new Exception(exceptionMessage); - verifyException.Data.Add(IsVerifyException, true); - throw verifyException; - } }