From f0377a1f62803c204e6288f778fe22cc67abd994 Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Wed, 20 May 2026 19:26:24 +0200 Subject: [PATCH 1/2] [tests] Upgrade tests/dotnet to NUnit v4 Assert.That syntax Migrate all classic assertions (AreEqual, IsTrue, IsNull, etc.) to Assert.That constraint syntax in tests/dotnet/UnitTests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/dotnet/UnitTests/AppIconTest.cs | 4 +- tests/dotnet/UnitTests/AssetsTest.cs | 18 +-- tests/dotnet/UnitTests/BundleStructureTest.cs | 11 +- tests/dotnet/UnitTests/DotNetUnitTests.csproj | 4 +- tests/dotnet/UnitTests/Extensions.cs | 2 +- tests/dotnet/UnitTests/MauiTest.cs | 20 +-- tests/dotnet/UnitTests/MlaunchTest.cs | 4 +- tests/dotnet/UnitTests/PackTest.cs | 14 +- .../UnitTests/PartialAppManifestTest.cs | 14 +- tests/dotnet/UnitTests/PostBuildTest.cs | 4 +- tests/dotnet/UnitTests/ProjectTest.cs | 148 +++++++++--------- tests/dotnet/UnitTests/PublishTrimmedTest.cs | 4 +- tests/dotnet/UnitTests/RegistrarTest.cs | 6 +- tests/dotnet/UnitTests/ResourcePrefixTest.cs | 24 +-- tests/dotnet/UnitTests/TemplateProjectTest.cs | 4 +- tests/dotnet/UnitTests/TemplateTest.cs | 10 +- tests/dotnet/UnitTests/TestBaseClass.cs | 4 +- tests/dotnet/UnitTests/WindowsTest.cs | 12 +- tests/dotnet/UnitTests/XcodeProjectTests.cs | 11 +- 19 files changed, 159 insertions(+), 159 deletions(-) diff --git a/tests/dotnet/UnitTests/AppIconTest.cs b/tests/dotnet/UnitTests/AppIconTest.cs index e8bea97b7c7e..970676172b53 100644 --- a/tests/dotnet/UnitTests/AppIconTest.cs +++ b/tests/dotnet/UnitTests/AppIconTest.cs @@ -656,7 +656,7 @@ void TestXCAssetsImpl (ApplePlatform platform, string runtimeIdentifiers, Dictio try { var doc = AssetsTest.ProcessAssets (assetsCar, AssetsTest.GetFullSdkVersion (platform, runtimeIdentifiers)); - Assert.IsNotNull (doc, "There was an issue processing the asset binary."); + Assert.That (doc, Is.Not.Null, "There was an issue processing the asset binary."); var foundAssets = AssetsTest.FindAssets (platform, doc); @@ -666,7 +666,7 @@ void TestXCAssetsImpl (ApplePlatform platform, string runtimeIdentifiers, Dictio expectedAssets.Add (asset); } - CollectionAssert.AreEquivalent (expectedAssets, foundAssets, "Incorrect assets"); + Assert.That (foundAssets, Is.EquivalentTo (expectedAssets), "Incorrect assets"); } catch { Console.WriteLine ($"Assets.car: {assetsCar}"); throw; diff --git a/tests/dotnet/UnitTests/AssetsTest.cs b/tests/dotnet/UnitTests/AssetsTest.cs index 0f2655513ca4..3466457299e9 100644 --- a/tests/dotnet/UnitTests/AssetsTest.cs +++ b/tests/dotnet/UnitTests/AssetsTest.cs @@ -55,7 +55,7 @@ void TestXCAssetsImpl (ApplePlatform platform, string runtimeIdentifiers, bool i Assert.That (assetsCar, Does.Exist, "Assets.car"); var doc = ProcessAssets (assetsCar, GetFullSdkVersion (platform, runtimeIdentifiers)); - Assert.IsNotNull (doc, "There was an issue processing the asset binary."); + Assert.That (doc, Is.Not.Null, "There was an issue processing the asset binary."); var foundAssets = FindAssets (platform, doc); @@ -78,12 +78,12 @@ void TestXCAssetsImpl (ApplePlatform platform, string runtimeIdentifiers, bool i throw new ArgumentOutOfRangeException ($"Unknown platform: {platform}"); } - CollectionAssert.AreEquivalent (expectedAssets, foundAssets, $"Incorrect assets in {assetsCar}"); + Assert.That (foundAssets, Is.EquivalentTo (expectedAssets), $"Incorrect assets in {assetsCar}"); var arm64txt = Path.Combine (resourcesDirectory, "arm64.txt"); var x64txt = Path.Combine (resourcesDirectory, "x64.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm64")), File.Exists (arm64txt), "arm64.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-x64")), File.Exists (x64txt), "x64.txt"); + Assert.That (File.Exists (arm64txt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm64"))), "arm64.txt"); + Assert.That (File.Exists (x64txt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-x64"))), "x64.txt"); } void ConfigureAssets (string projectPath, string runtimeIdentifiers, string config, bool isStartingWithAssets) @@ -128,7 +128,7 @@ void MakeSymlinks (string sourceDir, string destDir) var executable = "ln"; var arguments = new string [] { "-s", sourceDir, destDir }; var rv = Execution.RunAsync (executable, arguments, timeout: TimeSpan.FromSeconds (60)).Result; - Assert.AreEqual (0, rv.ExitCode, $"Creating Symlink Error: {rv.Output.MergedOutput}. Unexpected ExitCode"); + Assert.That (rv.ExitCode, Is.EqualTo (0), $"Creating Symlink Error: {rv.Output.MergedOutput}. Unexpected ExitCode"); } public static string GetFullSdkVersion (ApplePlatform platform, string runtimeIdentifiers) @@ -161,12 +161,12 @@ void ProcessUpdateSymlink (string xcassetsDir) var assets = Directory.EnumerateFiles (xcassetsDir, "*.*", SearchOption.AllDirectories).ToArray (); // assets first value is a .DS_Store file that work trigger MSBuild recompile so we want the second value - Assert.Greater (assets.Length, 1); + Assert.That (assets.Length, Is.GreaterThan (1)); var executable = "touch"; var arguments = new string [] { assets [1] }; var rv = Execution.RunAsync (executable, arguments, timeout: TimeSpan.FromSeconds (120)).Result; - Assert.AreEqual (0, rv.ExitCode, $"Processing Update Symlink Error: {rv.Output.MergedOutput}. Unexpected ExitCode"); + Assert.That (rv.ExitCode, Is.EqualTo (0), $"Processing Update Symlink Error: {rv.Output.MergedOutput}. Unexpected ExitCode"); } public static JsonDocument ProcessAssets (string assetsPath, string sdkVersion) @@ -176,7 +176,7 @@ public static JsonDocument ProcessAssets (string assetsPath, string sdkVersion) var tmpfile = Path.Combine (tmpdir, "Assets.json"); var arguments = new string [] { "--sdk", sdkVersion, "assetutil", "--info", assetsPath, "-o", tmpfile }; var rv = Execution.RunAsync (executable, arguments, timeout: TimeSpan.FromSeconds (120)).Result; - Assert.AreEqual (0, rv.ExitCode, $"Processing Assets Error: {rv.Output.StandardError}. Unexpected ExitCode"); + Assert.That (rv.ExitCode, Is.EqualTo (0), $"Processing Assets Error: {rv.Output.StandardError}. Unexpected ExitCode"); var s = File.ReadAllText (tmpfile); try { @@ -212,7 +212,7 @@ public static HashSet FindAssets (ApplePlatform platform, JsonDocument d case ApplePlatform.MacCatalyst: case ApplePlatform.iOS: case ApplePlatform.TVOS: - Assert.AreEqual ("2", schemaVersion.ToString (), "Verify SchemaVersion"); + Assert.That (schemaVersion.ToString (), Is.EqualTo ("2"), "Verify SchemaVersion"); break; default: throw new ArgumentOutOfRangeException ($"Unknown platform: {platform}"); diff --git a/tests/dotnet/UnitTests/BundleStructureTest.cs b/tests/dotnet/UnitTests/BundleStructureTest.cs index 13b5f6ca256a..20d21a660f7d 100644 --- a/tests/dotnet/UnitTests/BundleStructureTest.cs +++ b/tests/dotnet/UnitTests/BundleStructureTest.cs @@ -311,6 +311,7 @@ internal static void CheckAppBundleContents (ApplePlatform platform, IEnumerable if (platform != ApplePlatform.MacOSX) AddMultiRidAssembly (platform, expectedFiles, assemblyDirectory, "MonoTouch.Dialog", runtimeIdentifiers, forceSingleRid: (platform == ApplePlatform.MacCatalyst && !isReleaseBuild), includeDebugFiles: includeDebugFiles); expectedFiles.Add (Path.Combine (assemblyDirectory, "nunit.framework.dll")); + expectedFiles.Add (Path.Combine (assemblyDirectory, "nunit.framework.legacy.dll")); expectedFiles.Add (Path.Combine (assemblyDirectory, "nunitlite.dll")); expectedFiles.Add (Path.Combine (assemblyDirectory, "Mono.Options.dll")); AddMultiRidAssembly (platform, expectedFiles, assemblyDirectory, "Touch.Client", runtimeIdentifiers, platform == ApplePlatform.MacOSX || (platform == ApplePlatform.MacCatalyst && !isReleaseBuild), includeDebugFiles: includeDebugFiles); @@ -680,7 +681,7 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat var appExecutable = GetNativeExecutable (platform, appPath); CheckAppBundleContents (platform, appPath, rids, signature, isReleaseBuild); - CollectionAssert.AreEqual (expectedWarnings, warningMessages, "Warnings"); + Assert.That (warningMessages, Is.EqualTo (expectedWarnings), "Warnings"); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); // touch AppDelegate.cs, and rebuild should succeed and do the right thing @@ -692,7 +693,7 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat warningMessages = FilterWarnings (warnings); CheckAppBundleContents (platform, appPath, rids, signature, isReleaseBuild); - CollectionAssert.AreEqual (expectedWarnings, warningMessages, "Warnings Rebuild 1"); + Assert.That (warningMessages, Is.EqualTo (expectedWarnings), "Warnings Rebuild 1"); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); // remove the bin directory, and rebuild should succeed and do the right thing @@ -704,7 +705,7 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat warningMessages = FilterWarnings (warnings); CheckAppBundleContents (platform, appPath, rids, signature, isReleaseBuild); - CollectionAssert.AreEqual (expectedWarnings, warningMessages, "Warnings Rebuild 2"); + Assert.That (warningMessages, Is.EqualTo (expectedWarnings), "Warnings Rebuild 2"); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); // a simple rebuild should succeed @@ -713,7 +714,7 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat warningMessages = FilterWarnings (warnings); CheckAppBundleContents (platform, appPath, rids, signature, isReleaseBuild); - CollectionAssert.AreEqual (expectedWarnings, warningMessages, "Warnings Rebuild 3"); + Assert.That (warningMessages, Is.EqualTo (expectedWarnings), "Warnings Rebuild 3"); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); } @@ -794,7 +795,7 @@ static void AssertLibraryArchitectures (string appBundle, string [] runtimeIdent }); foreach (var lib in libraries) { var libArchitectures = renderArchitectures (MachO.GetArchitectures (lib)); - Assert.AreEqual (expectedArchitectures, libArchitectures, $"Architectures in {lib}"); + Assert.That (libArchitectures, Is.EqualTo (expectedArchitectures), $"Architectures in {lib}"); } } } diff --git a/tests/dotnet/UnitTests/DotNetUnitTests.csproj b/tests/dotnet/UnitTests/DotNetUnitTests.csproj index cacebf7a322e..5a35feef92d1 100644 --- a/tests/dotnet/UnitTests/DotNetUnitTests.csproj +++ b/tests/dotnet/UnitTests/DotNetUnitTests.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/tests/dotnet/UnitTests/Extensions.cs b/tests/dotnet/UnitTests/Extensions.cs index 1d04abf51f24..ba97980be9a9 100644 --- a/tests/dotnet/UnitTests/Extensions.cs +++ b/tests/dotnet/UnitTests/Extensions.cs @@ -96,7 +96,7 @@ public static void AssertWarnings (this IEnumerable actualWarning Console.WriteLine ($"If this is expected, an updated list of expected warnings in stored in {fn}"); File.WriteAllText (fn, sb.ToString ()); - // Rather than doing an Assert.IsEmpty, which produces a horrendous error message, we'll do an Assert.Multiple which generates a + // Rather than doing an Assert.That(..., Is.Empty), which produces a horrendous error message, we'll do an Assert.Multiple which generates a // nice enumerated output of all the failures. Assert.Multiple (() => { // fail for each of the new warnings diff --git a/tests/dotnet/UnitTests/MauiTest.cs b/tests/dotnet/UnitTests/MauiTest.cs index cf64f548d8b4..a8f6f3a069ae 100644 --- a/tests/dotnet/UnitTests/MauiTest.cs +++ b/tests/dotnet/UnitTests/MauiTest.cs @@ -52,19 +52,19 @@ void BuildMauiAppImpl (ApplePlatform platform, string runtimeIdentifiers, bool d AssertThatLinkerExecuted (rv); var infoPlistPath = GetInfoPListPath (platform, appPath); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mymauiapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MyMauiApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("1", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("1.0", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mymauiapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MyMauiApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("1"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("1.0"), "CFBundleShortVersionString"); - Assert.IsTrue (BinLog.TryFindPropertyValue (rv.BinLogPath, "TrimMode", out var trimModeValue), "Could not find the property 'TrimMode' in the binlog."); - Assert.IsTrue (BinLog.TryFindPropertyValue (rv.BinLogPath, "_LinkMode", out var linkModeValue), "Could not find the property '_LinkMode' in the binlog."); - Assert.IsTrue (BinLog.TryFindPropertyValue (rv.BinLogPath, "MtouchLink", out var mtouchLinkValue), "Could not find the property 'MtouchLink' in the binlog."); + Assert.That (BinLog.TryFindPropertyValue (rv.BinLogPath, "TrimMode", out var trimModeValue), Is.True, "Could not find the property 'TrimMode' in the binlog."); + Assert.That (BinLog.TryFindPropertyValue (rv.BinLogPath, "_LinkMode", out var linkModeValue), Is.True, "Could not find the property '_LinkMode' in the binlog."); + Assert.That (BinLog.TryFindPropertyValue (rv.BinLogPath, "MtouchLink", out var mtouchLinkValue), Is.True, "Could not find the property 'MtouchLink' in the binlog."); - Assert.AreEqual ("copy", trimModeValue, "TrimMode"); - Assert.AreEqual ("None", linkModeValue, "LinkMode"); - Assert.AreEqual ("None", mtouchLinkValue, "MtouchLink"); + Assert.That (trimModeValue, Is.EqualTo ("copy"), "TrimMode"); + Assert.That (linkModeValue, Is.EqualTo ("None"), "LinkMode"); + Assert.That (mtouchLinkValue, Is.EqualTo ("None"), "MtouchLink"); } [TestCase (ApplePlatform.MacCatalyst, "maccatalyst-arm64")] diff --git a/tests/dotnet/UnitTests/MlaunchTest.cs b/tests/dotnet/UnitTests/MlaunchTest.cs index fb7c3b9ba8b5..0610eb3f4dd0 100644 --- a/tests/dotnet/UnitTests/MlaunchTest.cs +++ b/tests/dotnet/UnitTests/MlaunchTest.cs @@ -48,11 +48,11 @@ public void GetMlaunchInstallArguments (ApplePlatform platform, string runtimeId expectedArguments.Append ("--installdev "); expectedArguments.Append (appPath.Substring (Path.GetDirectoryName (project_path)!.Length + 1)).Append ('/'); expectedArguments.Append ($" --wait-for-exit:false"); - Assert.AreEqual (expectedArguments.ToString (), mlaunchInstallArguments); + Assert.That (mlaunchInstallArguments, Is.EqualTo (expectedArguments.ToString ())); var scriptContents = File.ReadAllText (outputPath).Trim ('\n'); var expectedScriptContents = mlaunchPath + " " + expectedArguments.ToString (); - Assert.AreEqual (expectedScriptContents, scriptContents, "Script contents"); + Assert.That (scriptContents, Is.EqualTo (expectedScriptContents), "Script contents"); } public static object [] GetMlaunchRunArgumentsTestCases () diff --git a/tests/dotnet/UnitTests/PackTest.cs b/tests/dotnet/UnitTests/PackTest.cs index a9882a16414a..c5992b43650a 100644 --- a/tests/dotnet/UnitTests/PackTest.cs +++ b/tests/dotnet/UnitTests/PackTest.cs @@ -62,8 +62,8 @@ void BindingOldStyleImpl (ApplePlatform platform, Dictionary? pr var rv = DotNet.AssertPackFailure (project_path, properties, msbuildParallelism: false); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); - Assert.AreEqual ($"Creating a NuGet package is not supported for projects that have ObjcBindingNativeLibrary items. Migrate to use NativeReference items instead.", errors [0].Message, "Error message"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ($"Creating a NuGet package is not supported for projects that have ObjcBindingNativeLibrary items. Migrate to use NativeReference items instead."), "Error message"); } [Test] @@ -191,8 +191,8 @@ void BindingXcFrameworksProjectImpl (ApplePlatform platform, bool noBindingEmbed var assemblyName = "bindings-framework-test"; if (!noBindingEmbedding) { - Assert.IsFalse (platformSpecificXcframework, "Invalid test variation: platformSpecificXcframework"); - Assert.IsFalse (compressedXcframework, "Invalid test variation: compressedXcframework"); + Assert.That (platformSpecificXcframework, Is.False, "Invalid test variation: platformSpecificXcframework"); + Assert.That (compressedXcframework, Is.False, "Invalid test variation: compressedXcframework"); } if (!platformSpecificXcframework) { @@ -365,7 +365,7 @@ void BindingCompressedXcFrameworksProjectImpl (ApplePlatform platform, bool comp using var archive = ZipFile.OpenRead (nupkg); var files = archive.Entries.Select (v => v.FullName).ToHashSet (); var tfm = platform.ToFrameworkWithPlatformVersion (isExecutable: false); - Assert.AreEqual (compressed ? 6 : 9, archive.Entries.Count, $"nupkg file count - {nupkg}"); + Assert.That (archive.Entries.Count, Is.EqualTo (compressed ? 6 : 9), $"nupkg file count - {nupkg}"); Assert.That (files, Does.Contain (assemblyName + ".nuspec"), "nuspec"); Assert.That (files, Does.Contain ("_rels/.rels"), ".rels"); Assert.That (files, Does.Contain ("[Content_Types].xml"), "[Content_Types].xml"); @@ -382,7 +382,7 @@ void BindingCompressedXcFrameworksProjectImpl (ApplePlatform platform, bool comp "XStaticArTest.xcframework.zip", "XStaticObjectTest.xcframework.zip", }; - CollectionAssert.AreEqual (innerZipContents.OrderBy (v => v), innerZip.OrderBy (v => v), "Inner zip"); + Assert.That (innerZip.OrderBy (v => v), Is.EqualTo (innerZipContents.OrderBy (v => v)), "Inner zip"); manifest = ZipHelpers.GetInnerString (nupkg, resourcesZip, "manifest"); } else { Assert.That (files, Does.Contain ($"lib/{tfm}/{assemblyName}.resources/manifest"), $"manifest"); @@ -431,7 +431,7 @@ void BindingCompressedXcFrameworksProjectImpl (ApplePlatform platform, bool comp """; - Assert.AreEqual (expectedManifest, manifest, "manifest contents"); + Assert.That (manifest, Is.EqualTo (expectedManifest), "manifest contents"); } [Test] diff --git a/tests/dotnet/UnitTests/PartialAppManifestTest.cs b/tests/dotnet/UnitTests/PartialAppManifestTest.cs index 9d386fcbaea6..d15907131285 100644 --- a/tests/dotnet/UnitTests/PartialAppManifestTest.cs +++ b/tests/dotnet/UnitTests/PartialAppManifestTest.cs @@ -18,11 +18,11 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers) var infoPlistPath = GetInfoPListPath (platform, appPath); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mypartialappmanifestapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MyPartialAppManifestApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); - Assert.AreEqual ("SomeValue", infoPlist.GetString ("Something").Value, "Something"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mypartialappmanifestapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MyPartialAppManifestApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("Something").Value, Is.EqualTo ("SomeValue"), "Something"); var partialAppManifestPath = Path.Combine (Path.GetDirectoryName (project_path)!, "..", "Partial.plist"); Configuration.Touch (partialAppManifestPath); @@ -56,13 +56,13 @@ public void AppWithLibraryWithResourcesReference (ApplePlatform platform, string var infoPlistPath = GetInfoPListPath (platform, appPath); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("Here I am", infoPlist.GetString ("LibraryWithResources").Value, "LibraryWithResources 1"); + Assert.That (infoPlist.GetString ("LibraryWithResources").Value, Is.EqualTo ("Here I am"), "LibraryWithResources 1"); // build again, nothing should change DotNet.AssertBuild (project_path, properties); infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("Here I am", infoPlist.GetString ("LibraryWithResources").Value, "LibraryWithResources 2"); + Assert.That (infoPlist.GetString ("LibraryWithResources").Value, Is.EqualTo ("Here I am"), "LibraryWithResources 2"); } } } diff --git a/tests/dotnet/UnitTests/PostBuildTest.cs b/tests/dotnet/UnitTests/PostBuildTest.cs index 12f20d9901f2..3f8d8b76e8a6 100644 --- a/tests/dotnet/UnitTests/PostBuildTest.cs +++ b/tests/dotnet/UnitTests/PostBuildTest.cs @@ -222,14 +222,14 @@ public void PublishFailureTest (ApplePlatform platform, string runtimeIdentifier var rv = DotNet.AssertPublishFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error Count"); + Assert.That (errors.Length, Is.EqualTo (1), "Error Count"); string expectedErrorMessage; if (runtimeIdentifiers.IndexOf (';') >= 0) { expectedErrorMessage = $"A runtime identifier for a device architecture must be specified in order to publish this project. '{runtimeIdentifiers}' are simulator architectures."; } else { expectedErrorMessage = $"A runtime identifier for a device architecture must be specified in order to publish this project. '{runtimeIdentifiers}' is a simulator architecture."; } - Assert.AreEqual (expectedErrorMessage, errors [0].Message, "Error Message"); + Assert.That (errors [0].Message, Is.EqualTo (expectedErrorMessage), "Error Message"); Assert.That (pkgPath, Does.Not.Exist, "ipa/pkg creation"); } diff --git a/tests/dotnet/UnitTests/ProjectTest.cs b/tests/dotnet/UnitTests/ProjectTest.cs index 23d89f113666..ad174b7015af 100644 --- a/tests/dotnet/UnitTests/ProjectTest.cs +++ b/tests/dotnet/UnitTests/ProjectTest.cs @@ -26,10 +26,10 @@ public void BuildMySingleView (string runtimeIdentifier) AssertAppContents (platform, appPath); var infoPlistPath = Path.Combine (appPath, "Info.plist"); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mysingletitle", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySingleTitle", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysingletitle"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySingleTitle"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); } [Test] @@ -84,10 +84,10 @@ public void BuildMyCatalystApp (string runtimeIdentifier) AssertAppContents (platform, appPath); var infoPlistPath = Path.Combine (appPath, "Contents", "Info.plist"); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mycatalystapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MyCatalystApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mycatalystapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MyCatalystApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); } [TestCase (ApplePlatform.iOS)] @@ -115,7 +115,7 @@ public void BuildMyClassLibrary (ApplePlatform platform) using var ad = AssemblyDefinition.ReadAssembly (dll, new ReaderParameters { ReadingMode = ReadingMode.Deferred }); var r = ad.MainModule.AssemblyReferences.Where (v => v.Name == $"Microsoft.{platform.AsString ()}").First (); var actualReferenceVersionString = $"{r.Version.Major}.{r.Version.Minor}"; - Assert.AreEqual (expectedReferenceVersionString, actualReferenceVersionString, $"Referenced version of Microsoft.{platform.AsString ()}.dll"); + Assert.That (actualReferenceVersionString, Is.EqualTo (expectedReferenceVersionString), $"Referenced version of Microsoft.{platform.AsString ()}.dll"); Assert.That (r.Version.Build, Is.EqualTo (0), "Build"); Assert.That (r.Version.Revision, Is.EqualTo (0), "Revision"); } @@ -398,10 +398,10 @@ public void BuildFatApp (ApplePlatform platform, string runtimeIdentifiers) var infoPlistPath = GetInfoPListPath (platform, appPath); Assert.That (infoPlistPath, Does.Exist, "Info.plist"); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mysimpleapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySimpleApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysimpleapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySimpleApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); } [Test] @@ -429,8 +429,8 @@ public void BuildFatMonoTouchTest (ApplePlatform platform, string runtimeIdentif var infoPlistPath = GetInfoPListPath (platform, appPath); Assert.That (infoPlistPath, Does.Exist, "Info.plist"); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.monotouch-test", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MonoTouchTest", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.monotouch-test"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MonoTouchTest"), "CFBundleDisplayName"); } [Test] @@ -448,8 +448,8 @@ public void InvalidRuntimeIdentifiers (ApplePlatform platform, string runtimeIde var properties = GetDefaultProperties (runtimeIdentifiers); var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); - Assert.AreEqual ($"Building for all the runtime identifiers '{runtimeIdentifiers}' at the same time isn't possible, because they represent different platform variations.", errors [0].Message, "Error message"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ($"Building for all the runtime identifiers '{runtimeIdentifiers}' at the same time isn't possible, because they represent different platform variations."), "Error message"); } [Test] @@ -507,8 +507,8 @@ public void IsOverrideRuntimeIdentifier (ApplePlatform platform, string runtimeI properties ["cmdline:RuntimeIdentifier"] = "maccatalyst-x64"; var rv = DotNet.AssertBuild (project_path, properties); var warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, warnings.Length, "Warning Count"); - Assert.AreEqual ("RuntimeIdentifier was set on the command line, and will override the value for RuntimeIdentifiers set in the project file.", warnings [0].Message, "Warning message"); + Assert.That (warnings.Length, Is.EqualTo (1), "Warning Count"); + Assert.That (warnings [0].Message, Is.EqualTo ("RuntimeIdentifier was set on the command line, and will override the value for RuntimeIdentifiers set in the project file."), "Warning message"); } [Test] @@ -525,8 +525,8 @@ public void IsNotOverrideRuntimeIdentifier (ApplePlatform platform, string runti props ["RuntimeIdentifiers"] = "maccatalyst-arm64"; var rv = DotNet.AssertBuildFailure (projectPath, props); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual ("Both RuntimeIdentifier and RuntimeIdentifiers were passed on the command line, but only one of them can be set at a time.", errors [0].Message); - Assert.AreEqual (1, errors.Length, "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ("Both RuntimeIdentifier and RuntimeIdentifiers were passed on the command line, but only one of them can be set at a time.")); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); } [Test] @@ -584,14 +584,14 @@ public void InvalidRuntimeIdentifier (ApplePlatform platform, string runtimeIden var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); var uniqueErrors = errors.Select (v => v.Message).Distinct ().ToArray (); - Assert.AreEqual (1, uniqueErrors.Length, "Error count"); + Assert.That (uniqueErrors.Length, Is.EqualTo (1), "Error count"); string expectedError; if (notRecognized) { expectedError = $"The specified RuntimeIdentifier '{runtimeIdentifier}' is not recognized. See https://aka.ms/netsdk1083 for more information."; } else { expectedError = $"The RuntimeIdentifier '{runtimeIdentifier}' is invalid."; } - Assert.AreEqual (expectedError, uniqueErrors [0], "Error message"); + Assert.That (uniqueErrors [0], Is.EqualTo (expectedError), "Error message"); } [Test] @@ -611,7 +611,7 @@ public void InvalidRuntimeIdentifier_Restore (ApplePlatform platform, string run DotNet.AssertRestore (project_path, properties); } else { var rv = DotNet.Restore (project_path, properties); - Assert.AreNotEqual (0, rv.ExitCode, "Expected failure"); + Assert.That (rv.ExitCode, Is.Not.EqualTo (0), "Expected failure"); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); Assert.That (errors.Length, Is.GreaterThan (0), "Error count"); Assert.That (errors [0].Message, Does.Match (failureMessagePattern), "Message failure"); @@ -650,16 +650,16 @@ public void FilesInAppBundle (ApplePlatform platform, string runtimeIdentifiers) // Build again - this time it'll fail var rv = DotNet.Build (project_path, properties); var warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).ToArray (); - Assert.AreNotEqual (0, rv.ExitCode, "Unexpected success"); - Assert.AreEqual (1, warnings.Length, "Warning Count"); - Assert.AreEqual ($"Found files in the root directory of the app bundle. This will likely cause codesign to fail. Files:\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherfile.txt\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherdir\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherdir/otherfile.log", warnings [0].Message, "Warning"); + Assert.That (rv.ExitCode, Is.Not.EqualTo (0), "Unexpected success"); + Assert.That (warnings.Length, Is.EqualTo (1), "Warning Count"); + Assert.That (warnings [0].Message, Is.EqualTo ($"Found files in the root directory of the app bundle. This will likely cause codesign to fail. Files:\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherfile.txt\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherdir\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherdir/otherfile.log"), "Warning"); // Build again, asking for automatic removal of the extraneous files. var enableAutomaticCleanupProperties = new Dictionary (properties); enableAutomaticCleanupProperties ["EnableAutomaticAppBundleRootDirectoryCleanup"] = "true"; rv = DotNet.AssertBuild (project_path, enableAutomaticCleanupProperties); warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).ToArray (); - Assert.AreEqual (0, warnings.Length, "Warning Count"); + Assert.That (warnings.Length, Is.EqualTo (0), "Warning Count"); // Verify that the files were in fact removed. Assert.That (Path.Combine (appPath, "otherfile.txt"), Does.Not.Exist, "otherfile"); @@ -686,10 +686,10 @@ public void BuildCoreCLR (ApplePlatform platform, string runtimeIdentifiers) var infoPlistPath = GetInfoPListPath (platform, appPath); Assert.That (infoPlistPath, Does.Exist, "Info.plist"); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mysimpleapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySimpleApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysimpleapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySimpleApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); var appExecutable = GetNativeExecutable (platform, appPath); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); @@ -760,9 +760,9 @@ public void BindingWithDefaultCompileInclude (ApplePlatform platform) // Verify that the MyNativeClass class exists in the assembly, and that it's actually a class. var ad = AssemblyDefinition.ReadAssembly (dllPath, new ReaderParameters { ReadingMode = ReadingMode.Deferred }); var myNativeClass = ad.MainModule.Types.FirstOrDefault (v => v.FullName == "MyApiDefinition.MyNativeClass"); - Assert.IsFalse (myNativeClass!.IsInterface, "IsInterface"); + Assert.That (myNativeClass!.IsInterface, Is.False, "IsInterface"); var myStruct = ad.MainModule.Types.FirstOrDefault (v => v.FullName == "MyClassLibrary.MyStruct"); - Assert.IsTrue (myStruct!.IsValueType, "MyStruct"); + Assert.That (myStruct!.IsValueType, Is.True, "MyStruct"); var warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).Select (v => v.Message); Assert.That (warnings, Is.Empty, $"Build warnings:\n\t{string.Join ("\n\t", warnings)}"); @@ -806,13 +806,13 @@ public void AppWithResources (ApplePlatform platform, string runtimeIdentifiers) case ApplePlatform.TVOS: case ApplePlatform.MacCatalyst: var uiAppFonts = plist.GetArray ("UIAppFonts"); - Assert.IsNotNull (uiAppFonts, "UIAppFonts"); - Assert.AreEqual (1, uiAppFonts.Count, "UIAppFonts.Count"); - Assert.AreEqual ("B.otf", ((PString) uiAppFonts [0]).Value, "UIAppFonts [0]"); + Assert.That (uiAppFonts, Is.Not.Null, "UIAppFonts"); + Assert.That (uiAppFonts.Count, Is.EqualTo (1), "UIAppFonts.Count"); + Assert.That (((PString) uiAppFonts [0]).Value, Is.EqualTo ("B.otf"), "UIAppFonts [0]"); break; case ApplePlatform.MacOSX: var applicationFontsPath = plist.GetString ("ATSApplicationFontsPath")?.Value; - Assert.AreEqual (".", applicationFontsPath, "ATSApplicationFontsPath"); + Assert.That (applicationFontsPath, Is.EqualTo ("."), "ATSApplicationFontsPath"); break; default: throw new ArgumentOutOfRangeException ($"Unknown platform: {platform}"); @@ -840,9 +840,9 @@ public void AppWithResources (ApplePlatform platform, string runtimeIdentifiers) var arm64txt = Path.Combine (resourcesDirectory, "arm64.txt"); var armtxt = Path.Combine (resourcesDirectory, "arm.txt"); var x64txt = Path.Combine (resourcesDirectory, "x64.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm64")), File.Exists (arm64txt), "arm64.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm")), File.Exists (armtxt), "arm.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-x64")), File.Exists (x64txt), "x64.txt"); + Assert.That (File.Exists (arm64txt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm64"))), "arm64.txt"); + Assert.That (File.Exists (armtxt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm"))), "arm.txt"); + Assert.That (File.Exists (x64txt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-x64"))), "x64.txt"); var b_otf = Path.Combine (Path.GetDirectoryName (project_path)!, "Resources", "B.otf"); Configuration.Touch (b_otf); @@ -1017,7 +1017,7 @@ public void LibraryWithResources (ApplePlatform platform, bool? bundleOriginalRe } else { expectedResources = new List (); } - CollectionAssert.AreEquivalent (expectedResources, actualResources, "Resources"); + Assert.That (actualResources, Is.EquivalentTo (expectedResources), "Resources"); var zeroLengthResources = actualAssemblyResources.Where (v => v.ResourceType == ResourceType.Embedded && ((EmbeddedResource) v).GetResourceData ().Length == 0).Select (v => v.Name).ToArray (); Assert.That (zeroLengthResources, Is.Empty, $"0-length resources"); @@ -1128,7 +1128,7 @@ void AppWithLibraryWithResourcesReferenceImpl (ApplePlatform platform, string ru if (bundleOriginalResources) { var infoPlist = appBundleInfo.GetFile (GetInfoPListPath (platform, "")); var appManifest = PDictionary.FromByteArray (infoPlist, out var _)!; - Assert.AreEqual ("Here I am", appManifest.GetString ("LibraryWithResources").Value, "Partial plist entry"); + Assert.That (appManifest.GetString ("LibraryWithResources").Value, Is.EqualTo ("Here I am"), "Partial plist entry"); } }); @@ -1904,7 +1904,7 @@ void BuildProjectsWithExtensionsImpl (ApplePlatform platform, string runtimeIden var pathToSearch = Path.Combine (Path.GetDirectoryName (consumingProjectDir)!, "bin", "Debug"); string [] configFiles = Directory.GetFiles (pathToSearch, "*.runtimeconfig.*", SearchOption.AllDirectories); - Assert.AreNotEqual (0, configFiles.Length, "runtimeconfig.json file does not exist"); + Assert.That (configFiles.Length, Is.Not.EqualTo (0), "runtimeconfig.json file does not exist"); } [TestCase (ApplePlatform.iOS, "iossimulator-x64", false)] @@ -1937,11 +1937,11 @@ public void BuildProjectsWithExtensionsAndFrameworks (ApplePlatform platform, st var extensionPath = Path.Combine (appPath, GetPlugInsRelativePath (platform), "ExtensionProjectWithFrameworks.appex"); Assert.That (Directory.Exists (extensionPath), $"App extension directory does not exist: {extensionPath}"); var extensionFrameworksPath = Path.Combine (extensionPath, GetFrameworksRelativePath (platform)); - Assert.IsFalse (Directory.Exists (extensionFrameworksPath), $"App extension framework directory exists when it shouldn't: {extensionFrameworksPath}"); + Assert.That (Directory.Exists (extensionFrameworksPath), Is.False, $"App extension framework directory exists when it shouldn't: {extensionFrameworksPath}"); var pathToSearch = Path.Combine (Path.GetDirectoryName (consumingProjectDir)!, "bin", "Debug"); var configFiles = Directory.GetFiles (pathToSearch, "*.runtimeconfig.*", SearchOption.AllDirectories); - Assert.AreNotEqual (0, configFiles.Length, "runtimeconfig.json file does not exist"); + Assert.That (configFiles.Length, Is.Not.EqualTo (0), "runtimeconfig.json file does not exist"); var appFrameworksPath = Path.Combine (appPath, GetFrameworksRelativePath (platform)); Assert.That (Directory.Exists (appFrameworksPath), $"App Frameworks directory does not exist: {appFrameworksPath}"); @@ -2026,8 +2026,8 @@ public void CatalystAppOptimizedForMacOS (ApplePlatform platform, string runtime if (failureExpected) { var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); - Assert.AreEqual ($"The UIDeviceFamily value '6' is not valid for this platform. It's only valid for Mac Catalyst.", errors [0].Message, "Error message"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ($"The UIDeviceFamily value '6' is not valid for this platform. It's only valid for Mac Catalyst."), "Error message"); } else { DotNet.AssertBuild (project_path, properties); } @@ -2147,10 +2147,10 @@ void BuildSupportedNetVersionApp (ApplePlatform platform, string runtimeIdentifi var infoPlistPath = GetInfoPListPath (platform, appPath); Assert.That (infoPlistPath, Does.Exist, "Info.plist"); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mysimpleapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySimpleApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual (netVersion, infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual (netVersion, infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysimpleapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySimpleApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo (netVersion), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo (netVersion), "CFBundleShortVersionString"); var appExecutable = GetNativeExecutable (platform, appPath); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); @@ -2297,7 +2297,7 @@ public void CustomizedCodeSigning (ApplePlatform platform, string runtimeIdentif foreach (var dylib in signedDylibs) { var path = Path.Combine (appPath, dylib); Assert.That (path, Does.Exist, "dylib exists"); - Assert.IsTrue (IsDylibSigned (path), $"Signed: {path}"); + Assert.That (IsDylibSigned (path), Is.True, $"Signed: {path}"); } appBundleContents.ExceptWith (signedDylibs); // And that there are unsigned dylibs, but not the system ones @@ -2307,9 +2307,9 @@ public void CustomizedCodeSigning (ApplePlatform platform, string runtimeIdentif foreach (var unsignedDylib in remainingDylibs) { var path = Path.Combine (appPath, unsignedDylib); Assert.That (path, Does.Exist, "unsigned dylib existence"); - Assert.IsFalse (IsDylibSigned (path), $"Unsigned: {path}"); + Assert.That (IsDylibSigned (path), Is.False, $"Unsigned: {path}"); } - Assert.AreEqual (2, remainingDylibs.Length, "Unsigned count"); + Assert.That (remainingDylibs.Length, Is.EqualTo (2), "Unsigned count"); // Verify that a Resources subdirectory causes the build to fail. switch (platform) { @@ -2379,11 +2379,11 @@ public void AutoAllowJitEntitlements (ApplePlatform platform, string runtimeIden var executable = GetNativeExecutable (platform, appPath); var foundEntitlements = TryGetEntitlements (executable, out var entitlements); if (configuration == "Release") { - Assert.IsTrue (foundEntitlements, "Found in Release"); - Assert.IsTrue (entitlements!.Get ("com.apple.security.cs.allow-jit")?.Value, "Jit Allowed"); + Assert.That (foundEntitlements, Is.True, "Found in Release"); + Assert.That (entitlements!.Get ("com.apple.security.cs.allow-jit")?.Value, Is.True, "Jit Allowed"); } else { var jitNotAllowed = !foundEntitlements || !entitlements!.ContainsKey ("com.apple.security.cs.allow-jit"); - Assert.True (jitNotAllowed, "Jit Not Allowed"); + Assert.That (jitNotAllowed, Is.True, "Jit Not Allowed"); } } @@ -2491,8 +2491,8 @@ public void BuildAndExecuteAppWithWinExeOutputType (ApplePlatform platform, stri var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); - Assert.AreEqual ($"WinExe is not a valid output type for macOS", errors [0].Message, "Error message"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ($"WinExe is not a valid output type for macOS"), "Error message"); } [Test] @@ -2535,9 +2535,9 @@ public void BuildMyNativeAotAppWithTrimAnalysisWarning (ApplePlatform platform, warnings = warnings.Where (w => w.Message?.Trim () != "Supported iPhone orientations have not been set").ToArray (); } - Assert.AreEqual (1, warnings.Length, "Warning count"); - Assert.AreEqual (warnings [0].Code, "IL2075", "Warning code"); - Assert.AreEqual (warnings [0].Message, "'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperties()'. The return value of method 'System.Object.GetType()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to."); + Assert.That (warnings.Length, Is.EqualTo (1), "Warning count"); + Assert.That ("IL2075", Is.EqualTo (warnings [0].Code), "Warning code"); + Assert.That ("'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperties()'. The return value of method 'System.Object.GetType()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.", Is.EqualTo (warnings [0].Message)); } [Test] @@ -2571,7 +2571,7 @@ public void PublishAot (ApplePlatform platform, string runtimeIdentifiers, strin properties ["TrimmerSingleWarn"] = "false"; // don't be shy, we want to know what the problem is var rv = DotNet.AssertBuild (project_path, properties); - Assert.True (Directory.Exists (appPath), $"App file expected at: {appPath}"); + Assert.That (Directory.Exists (appPath), Is.True, $"App file expected at: {appPath}"); // Verify that we have no warnings, but unfortunately we still have some we haven't fixed yet. // Ignore those, and fail the test if we stop getting them (so that we can update the test to not ignore them anymore). @@ -2853,14 +2853,14 @@ public void SourcelinkTest (ApplePlatform platform, string runtimeIdentifiers, s .GetFiles (Path.GetDirectoryName (project_path)!, $"Microsoft.{platformName}.pdb", SearchOption.AllDirectories) .FirstOrDefault (); - Assert.NotNull (pdbFile, "No PDB file found"); + Assert.That (pdbFile, Is.Not.Null, "No PDB file found"); var tool = "sourcelink"; var toolPath = Directory.GetCurrentDirectory (); DotNet.InstallTool (tool, toolPath); var test = DotNet.RunTool (Path.Combine (toolPath, tool), "test", pdbFile!); - Assert.AreEqual ($"sourcelink test passed: {pdbFile}", test.StandardOutput.ToString ().TrimEnd ('\n')); + Assert.That (test.StandardOutput.ToString ().TrimEnd ('\n'), Is.EqualTo ($"sourcelink test passed: {pdbFile}")); } @@ -2922,7 +2922,7 @@ public void DedupEnabledTest (ApplePlatform platform, string runtimeIdentifiers, DotNet.AssertBuild (project_path, properties); var objDir = GetObjDir (project_path, platform, runtimeIdentifiers); - Assert.True (FindAOTedAssemblyFile (objDir, "aot-instances.dll"), $"Dedup optimization should be enabled for AOT compilation on: {platform} with RID: {runtimeIdentifiers}"); + Assert.That (FindAOTedAssemblyFile (objDir, "aot-instances.dll"), Is.True, $"Dedup optimization should be enabled for AOT compilation on: {platform} with RID: {runtimeIdentifiers}"); } [Test] @@ -2946,7 +2946,7 @@ public void DedupDisabledTest (ApplePlatform platform, string runtimeIdentifiers DotNet.AssertBuild (project_path, properties); var objDir = GetObjDir (project_path, platform, runtimeIdentifiers); - Assert.False (FindAOTedAssemblyFile (objDir, "aot-instances.dll"), $"Dedup optimization should not be enabled for AOT compilation on: {platform} with RID: {runtimeIdentifiers}"); + Assert.That (FindAOTedAssemblyFile (objDir, "aot-instances.dll"), Is.False, $"Dedup optimization should not be enabled for AOT compilation on: {platform} with RID: {runtimeIdentifiers}"); } [Test] @@ -2968,10 +2968,10 @@ public void DedupUniversalAppTest (ApplePlatform platform, string runtimeIdentif var objDir = GetObjDir (project_path, platform, runtimeIdentifiers); var objDirMacCatalystArm64 = Path.Combine (objDir, "maccatalyst-arm64"); - Assert.True (FindAOTedAssemblyFile (objDirMacCatalystArm64, "aot-instances.dll"), $"Dedup optimization should be enabled for AOT compilation on: {platform} with RID: maccatalyst-arm64"); + Assert.That (FindAOTedAssemblyFile (objDirMacCatalystArm64, "aot-instances.dll"), Is.True, $"Dedup optimization should be enabled for AOT compilation on: {platform} with RID: maccatalyst-arm64"); var objDirMacCatalystx64 = Path.Combine (objDir, "maccatalyst-x64"); - Assert.False (FindAOTedAssemblyFile (objDirMacCatalystx64, "aot-instances.dll"), $"Dedup optimization should not be enabled for AOT compilation on: {platform} with RID: maccatalyst-x64"); + Assert.That (FindAOTedAssemblyFile (objDirMacCatalystx64, "aot-instances.dll"), Is.False, $"Dedup optimization should not be enabled for AOT compilation on: {platform} with RID: maccatalyst-x64"); var appExecutable = GetNativeExecutable (platform, appPath); @@ -3751,9 +3751,9 @@ public void LinkedWithNativeLibraries (ApplePlatform platform, string runtimeIde var appExecutable = GetNativeExecutable (platform, appPath); var actualFrameworks = GetLinkedWithFrameworks (appExecutable); - CollectionAssert.AreEquivalent ( - expectedFrameworks.OrderBy (v => v).ToArray (), + Assert.That ( actualFrameworks.OrderBy (v => v).ToArray (), + Is.EquivalentTo (expectedFrameworks.OrderBy (v => v).ToArray ()), "Frameworks"); } @@ -3792,8 +3792,8 @@ public void SpacedAppTitle (ApplePlatform platform, string runtimeIdentifiers) var infoPlistPath = GetInfoPListPath (platform, appPath); var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.spacedapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("Spaced App Title", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.spacedapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("Spaced App Title"), "CFBundleDisplayName"); var appName = Path.GetFileNameWithoutExtension (appPath); switch (platform) { diff --git a/tests/dotnet/UnitTests/PublishTrimmedTest.cs b/tests/dotnet/UnitTests/PublishTrimmedTest.cs index f7675e066d2f..8e6a1296ebf0 100644 --- a/tests/dotnet/UnitTests/PublishTrimmedTest.cs +++ b/tests/dotnet/UnitTests/PublishTrimmedTest.cs @@ -21,9 +21,9 @@ public void DisableLinker (ApplePlatform platform, string runtimeIdentifiers) var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); var linkModeName = platform == ApplePlatform.MacOSX ? "LinkMode" : "MtouchLink"; - Assert.AreEqual ($"{platform.AsString ()} projects must build with PublishTrimmed=true. Current value: false. Set '{linkModeName}=None' instead to disable trimming for all assemblies.", errors [0].Message, "Error message"); + Assert.That (errors [0].Message, Is.EqualTo ($"{platform.AsString ()} projects must build with PublishTrimmed=true. Current value: false. Set '{linkModeName}=None' instead to disable trimming for all assemblies."), "Error message"); } } } diff --git a/tests/dotnet/UnitTests/RegistrarTest.cs b/tests/dotnet/UnitTests/RegistrarTest.cs index 767e5bda46e6..003efbdc3281 100644 --- a/tests/dotnet/UnitTests/RegistrarTest.cs +++ b/tests/dotnet/UnitTests/RegistrarTest.cs @@ -48,7 +48,7 @@ public void InvalidStaticRegistrarValidation (ApplePlatform platform, string? ru ExecuteProjectWithMagicWordAndAssert (projectPath, platform, runtimeIdentifiers); } else if (CanExecute (platform, runtimeIdentifiers)) { var rv = base.Execute (GetNativeExecutable (platform, appDir), out var output, out _); - Assert.AreEqual (1, rv.ExitCode, "Expected no validation"); + Assert.That (rv.ExitCode, Is.EqualTo (1), "Expected no validation"); } } finally { Environment.SetEnvironmentVariable ("XAMARIN_VALIDATE_STATIC_REGISTRAR_CODE", null); @@ -89,7 +89,7 @@ public void ClassRewriterTest (ApplePlatform platform, bool rewriteHandles) Assert.That (File.Exists (platformDll), "No platform dll."); var module = ModuleDefinition.ReadModule (platformDll); var classHandlesMaybe = AllTypes (module).FirstOrDefault (t => t.FullName == "ObjCRuntime.Runtime/ClassHandles"); - Assert.NotNull (classHandlesMaybe, "Couldn't find ClassHandles type."); + Assert.That (classHandlesMaybe, Is.Not.Null, "Couldn't find ClassHandles type."); var classHandles = classHandlesMaybe!; if (!rewriteHandles) { // NB: there is always at least one field named "unused" @@ -103,7 +103,7 @@ public void ClassRewriterTest (ApplePlatform platform, bool rewriteHandles) // NB: there is always at least one field named "unused" Assert.That (classHandles.HasFields && classHandles.Fields.Count () > 1, "There are no fields in ClassHandles - rewriter did nothing."); var field = classHandles.Fields.FirstOrDefault (f => f.Name.Contains ("SomeObj")); - Assert.IsNotNull (field, "Didn't find a field for 'SomeObj'"); + Assert.That (field, Is.Not.Null, "Didn't find a field for 'SomeObj'"); } } diff --git a/tests/dotnet/UnitTests/ResourcePrefixTest.cs b/tests/dotnet/UnitTests/ResourcePrefixTest.cs index f4860ff1489e..60836d12716d 100644 --- a/tests/dotnet/UnitTests/ResourcePrefixTest.cs +++ b/tests/dotnet/UnitTests/ResourcePrefixTest.cs @@ -17,7 +17,7 @@ public void ResourcePrefix_DefaultValues () foreach (var platform in platforms) { // Act & Assert var defaultValue = GetResourcePrefix (platform.AsString ().ToLower ()); - Assert.AreEqual ("Resources", defaultValue, $"Default value for {platform} should be 'Resources'"); + Assert.That (defaultValue, Is.EqualTo ("Resources"), $"Default value for {platform} should be 'Resources'"); } } @@ -33,7 +33,7 @@ public void ResourcePrefix_AppBundleResourcePrefix () var value = GetResourcePrefix (platform.AsString ().ToLower (), ("AppBundleResourcePrefix", customPrefix)); // Assert - Assert.AreEqual (customPrefix, value, $"{platform}: AppBundleResourcePrefix should be used"); + Assert.That (value, Is.EqualTo (customPrefix), $"{platform}: AppBundleResourcePrefix should be used"); } } @@ -48,27 +48,27 @@ public void ResourcePrefix_PlatformSpecific () // iOS and tvOS use IPhoneResourcePrefix if (Configuration.include_ios) { var iOSValue = GetResourcePrefix ("ios", ("IPhoneResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, iOSValue, "iOS should use IPhoneResourcePrefix"); + Assert.That (iOSValue, Is.EqualTo (customPrefix), "iOS should use IPhoneResourcePrefix"); } if (Configuration.include_tvos) { var tvOSValue = GetResourcePrefix ("tvos", ("IPhoneResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, tvOSValue, "tvOS should use IPhoneResourcePrefix"); + Assert.That (tvOSValue, Is.EqualTo (customPrefix), "tvOS should use IPhoneResourcePrefix"); } // Mac Catalyst uses IPhoneResourcePrefix if (Configuration.include_maccatalyst) { var macCatalystValue = GetResourcePrefix ("maccatalyst", ("IPhoneResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, macCatalystValue, "Mac Catalyst should use IPhoneResourcePrefix"); + Assert.That (macCatalystValue, Is.EqualTo (customPrefix), "Mac Catalyst should use IPhoneResourcePrefix"); } // macOS can use either XamMacResourcePrefix or MonoMacResourcePrefix if (Configuration.include_mac) { var macOSXamValue = GetResourcePrefix ("macos", ("XamMacResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, macOSXamValue, "macOS should use XamMacResourcePrefix"); + Assert.That (macOSXamValue, Is.EqualTo (customPrefix), "macOS should use XamMacResourcePrefix"); var macOSMonoValue = GetResourcePrefix ("macos", ("MonoMacResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, macOSMonoValue, "macOS should use MonoMacResourcePrefix"); + Assert.That (macOSMonoValue, Is.EqualTo (customPrefix), "macOS should use MonoMacResourcePrefix"); } } @@ -86,7 +86,7 @@ public void ResourcePrefix_Precedence () var iOSValue = GetResourcePrefix ("ios", ("AppBundleResourcePrefix", appBundlePrefix), ("IPhoneResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, iOSValue, "iOS should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); + Assert.That (iOSValue, Is.EqualTo (appBundlePrefix), "iOS should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); } // tvOS - AppBundleResourcePrefix should take precedence over IPhoneResourcePrefix @@ -94,7 +94,7 @@ public void ResourcePrefix_Precedence () var tvOSValue = GetResourcePrefix ("tvos", ("AppBundleResourcePrefix", appBundlePrefix), ("IPhoneResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, tvOSValue, "tvOS should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); + Assert.That (tvOSValue, Is.EqualTo (appBundlePrefix), "tvOS should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); } // Mac Catalyst - AppBundleResourcePrefix should take precedence over IPhoneResourcePrefix @@ -102,7 +102,7 @@ public void ResourcePrefix_Precedence () var macCatalystValue = GetResourcePrefix ("maccatalyst", ("AppBundleResourcePrefix", appBundlePrefix), ("IPhoneResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, macCatalystValue, "Mac Catalyst should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); + Assert.That (macCatalystValue, Is.EqualTo (appBundlePrefix), "Mac Catalyst should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); } // macOS - AppBundleResourcePrefix should take precedence over XamMacResourcePrefix @@ -110,13 +110,13 @@ public void ResourcePrefix_Precedence () var macOSXamValue = GetResourcePrefix ("macos", ("AppBundleResourcePrefix", appBundlePrefix), ("XamMacResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, macOSXamValue, "macOS should prioritize AppBundleResourcePrefix over XamMacResourcePrefix"); + Assert.That (macOSXamValue, Is.EqualTo (appBundlePrefix), "macOS should prioritize AppBundleResourcePrefix over XamMacResourcePrefix"); // macOS - AppBundleResourcePrefix should take precedence over MonoMacResourcePrefix var macOSMonoValue = GetResourcePrefix ("macos", ("AppBundleResourcePrefix", appBundlePrefix), ("MonoMacResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, macOSMonoValue, "macOS should prioritize AppBundleResourcePrefix over MonoMacResourcePrefix"); + Assert.That (macOSMonoValue, Is.EqualTo (appBundlePrefix), "macOS should prioritize AppBundleResourcePrefix over MonoMacResourcePrefix"); } } diff --git a/tests/dotnet/UnitTests/TemplateProjectTest.cs b/tests/dotnet/UnitTests/TemplateProjectTest.cs index ea4318b9294f..dfa469bbd044 100644 --- a/tests/dotnet/UnitTests/TemplateProjectTest.cs +++ b/tests/dotnet/UnitTests/TemplateProjectTest.cs @@ -177,8 +177,8 @@ public void NoBundleIdentifierError (ApplePlatform platform) var properties = GetDefaultProperties (); var result = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (result.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Errors"); - Assert.AreEqual ("A bundle identifier is required. Either add an 'ApplicationId' property in the project file, or add a 'CFBundleIdentifier' entry in the project's Info.plist file.", errors [0].Message); + Assert.That (errors.Length, Is.EqualTo (1), "Errors"); + Assert.That (errors [0].Message, Is.EqualTo ("A bundle identifier is required. Either add an 'ApplicationId' property in the project file, or add a 'CFBundleIdentifier' entry in the project's Info.plist file.")); } } } diff --git a/tests/dotnet/UnitTests/TemplateTest.cs b/tests/dotnet/UnitTests/TemplateTest.cs index 11da53ac3e5a..24c9e1d54dca 100644 --- a/tests/dotnet/UnitTests/TemplateTest.cs +++ b/tests/dotnet/UnitTests/TemplateTest.cs @@ -227,7 +227,7 @@ public void CreateAndBuildProjectTemplate (TemplateInfo info) var platform = info.Platform; var runtimeIdentifiers = GetDefaultRuntimeIdentifier (platform); - Assert.IsTrue (CanExecute (info.Platform, runtimeIdentifiers), "Must be executable to execute!"); + Assert.That (CanExecute (info.Platform, runtimeIdentifiers), Is.True, "Must be executable to execute!"); // First add some code to exit the template if it launches successfully. InsertCodeToExitAppAfterLaunch (language, outputDir); @@ -286,7 +286,7 @@ bool IsMatching (TemplateLanguage lang, TemplateLanguage? value) if (info.Execute) { var runtimeIdentifiers = GetDefaultRuntimeIdentifier (platform); - Assert.IsTrue (CanExecute (info.Platform, runtimeIdentifiers), "Must be executable to execute!"); + Assert.That (CanExecute (info.Platform, runtimeIdentifiers), Is.True, "Must be executable to execute!"); // First add some code to exit the template if it launches successfully. InsertCodeToExitAppAfterLaunch (language, outputDir); @@ -333,7 +333,7 @@ static void InsertCSharpCodeToExitAppAfterLaunch (string outputDir) var modifiedMainContents = mainContents.Replace ("// This is the main entry point of the application.", exitSampleWithSuccess); - Assert.AreNotEqual (modifiedMainContents, mainContents, "Failed to modify the main content"); + Assert.That (mainContents, Is.Not.EqualTo (modifiedMainContents), "Failed to modify the main content"); File.WriteAllText (mainFile, modifiedMainContents); } @@ -349,7 +349,7 @@ static void InsertFSharpCodeToExitAppAfterLaunch (string outputDir) var modifiedMainContents = mainContents.Replace ("// This is the main entry point of the application.", exitSampleWithSuccess); - Assert.AreNotEqual (modifiedMainContents, mainContents, "Failed to modify the main content"); + Assert.That (mainContents, Is.Not.EqualTo (modifiedMainContents), "Failed to modify the main content"); File.WriteAllText (mainFile, modifiedMainContents); } @@ -367,7 +367,7 @@ End Sub var modifiedMainContents = mainContents.Replace ("' This is the main entry point of the application.", exitSampleWithSuccess); - Assert.AreNotEqual (modifiedMainContents, mainContents, "Failed to modify the main content"); + Assert.That (mainContents, Is.Not.EqualTo (modifiedMainContents), "Failed to modify the main content"); File.WriteAllText (mainFile, modifiedMainContents); } } diff --git a/tests/dotnet/UnitTests/TestBaseClass.cs b/tests/dotnet/UnitTests/TestBaseClass.cs index 19e3511ada80..0d95abd4db43 100644 --- a/tests/dotnet/UnitTests/TestBaseClass.cs +++ b/tests/dotnet/UnitTests/TestBaseClass.cs @@ -492,7 +492,7 @@ public static StringBuilder AssertExecute (string executable, string [] argument Console.WriteLine ($"'{executable} {StringUtils.FormatArguments (arguments)}' exited with exit code {rv}:"); Console.WriteLine ("\t" + output.ToString ().Replace ("\n", "\n\t").TrimEnd (new char [] { '\n', '\t' })); } - Assert.AreEqual (0, rv, $"Unable to execute '{executable} {StringUtils.FormatArguments (arguments)}': exit code {rv}"); + Assert.That (rv, Is.EqualTo (0), $"Unable to execute '{executable} {StringUtils.FormatArguments (arguments)}': exit code {rv}"); return output; } @@ -528,7 +528,7 @@ protected bool TryGetEntitlements (string nativeExecutable, [NotNullWhen (true)] nativeExecutable }; var rv = ExecutionHelper.Execute ("codesign", args, out var codesignOutput, TimeSpan.FromSeconds (15)); - Assert.AreEqual (0, rv, $"'codesign {string.Join (" ", args)}' failed:\n{codesignOutput}"); + Assert.That (rv, Is.EqualTo (0), $"'codesign {string.Join (" ", args)}' failed:\n{codesignOutput}"); if (File.Exists (entitlementsPath)) { entitlements = PDictionary.FromFile (entitlementsPath); return entitlements is not null; diff --git a/tests/dotnet/UnitTests/WindowsTest.cs b/tests/dotnet/UnitTests/WindowsTest.cs index d546af38e4a9..b71e01bcab70 100644 --- a/tests/dotnet/UnitTests/WindowsTest.cs +++ b/tests/dotnet/UnitTests/WindowsTest.cs @@ -377,7 +377,7 @@ public void RemoteTest (ApplePlatform platform, string runtimeIdentifiers) using var zip = ZipFile.OpenRead (zippedAppBundlePath); ZipHelpers.DumpZipFile (zip, zippedAppBundlePath); var infoPlistEntry = zip.Entries.SingleOrDefault (v => v.Name == "Info.plist")!; - Assert.NotNull (infoPlistEntry, "Info.plist"); + Assert.That (infoPlistEntry, Is.Not.Null, "Info.plist"); // Parse the Info.plist // PDictionary.FromStream requires a seekable stream, but the zip stream isn't seekable, so copy to a @@ -387,10 +387,10 @@ public void RemoteTest (ApplePlatform platform, string runtimeIdentifiers) plistStream.CopyTo (memoryStream); var infoPlist = (PDictionary) PDictionary.FromStream (memoryStream)!; - Assert.AreEqual ("com.xamarin.mysimpleapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySimpleApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysimpleapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySimpleApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); //Validate that the output assemblies report file with the list of local assemblies, lengths and MVIDs has been created var outputAssembliesReportFileName = "OutputAssembliesReport.txt"; @@ -427,7 +427,7 @@ public void RemoteTest (ApplePlatform platform, string runtimeIdentifiers) Guid mvid = metadataReader.GetGuid (metadataReader.GetModuleDefinition ().Mvid); var fileWasUpdated = fileInfo.Length != localInfo.length || mvid != localInfo.mvid; - Assert.IsTrue (fileWasUpdated, $"The file '{fileName}' is identical to the one present in the output assemblies report file '{outputAssembliesReportFile}'"); + Assert.That (fileWasUpdated, Is.True, $"The file '{fileName}' is identical to the one present in the output assemblies report file '{outputAssembliesReportFile}'"); } } } diff --git a/tests/dotnet/UnitTests/XcodeProjectTests.cs b/tests/dotnet/UnitTests/XcodeProjectTests.cs index 2d213de9203f..89096c0cb944 100644 --- a/tests/dotnet/UnitTests/XcodeProjectTests.cs +++ b/tests/dotnet/UnitTests/XcodeProjectTests.cs @@ -32,8 +32,7 @@ void AssertXcFrameworkOutput (ApplePlatform platform, string testDir, string xco Assert.That (expectedXcodeFxOutput, Does.Exist, $"Expected xcframework output '{expectedXcodeFxOutput}' did not exist."); } else { var resourcesZip = Path.Combine (testDir, "bin", config, platform.ToFramework (), $"{TestName}.resources.zip"); - Assert.Contains ($"{xcodeProjName}{platform.AsString ()}.xcframework/Info.plist", ZipHelpers.List (resourcesZip), - $"Expected xcframework output was not found in '{resourcesZip}'."); + Assert.That (ZipHelpers.List (resourcesZip), Does.Contain ($"{xcodeProjName}{platform.AsString ()}.xcframework/Info.plist"), $"Expected xcframework output was not found in '{resourcesZip}'."); } } @@ -66,7 +65,7 @@ public void BuildAppiOS (string projConfig, string rid) Assert.That (appDir, Does.Exist, $"Expected app dir '{appDir}' did not exist."); var appContent = Directory.GetFiles (appDir, "*", SearchOption.AllDirectories); var expectedAppOutput = Path.Combine (testDir, "bin", projConfig, platform.ToFramework (), rid, $"{TestName}.app", "Frameworks", $"{xcodeProjName}.framework", "Info.plist"); - Assert.Contains (expectedAppOutput, appContent, $"Expected framework output '{expectedAppOutput}' did not exist."); + Assert.That (appContent, Does.Contain (expectedAppOutput), $"Expected framework output '{expectedAppOutput}' did not exist."); } @@ -189,7 +188,7 @@ public void PackBinding (ApplePlatform platform) zipContent = ZipHelpers.ListInnerZip (expectedNupkgOutput, $"lib/{tfm}/{TestName}.resources.zip"); expectedFxPath = $"{xcodeProjName}{platform.AsString ()}.xcframework/Info.plist"; } - Assert.Contains (expectedFxPath, zipContent, $"Expected xcframework output was not found in '{expectedNupkgOutput}'."); + Assert.That (zipContent, Does.Contain (expectedFxPath), $"Expected xcframework output was not found in '{expectedNupkgOutput}'."); } [Test] @@ -241,7 +240,7 @@ public void BuildIncremental (ApplePlatform platform) AssertTargetExecuted (allTargets, "_BuildXcodeProjects", "Third _BuildXcodeProjects"); Assert.That (expectedXcodeFxOutput, Does.Exist, $"Expected xcframework output '{expectedXcodeFxOutput}' did not exist."); var outputFxThirdWriteTime = File.GetLastWriteTime (expectedXcodeFxOutput); - Assert.IsTrue (outputFxThirdWriteTime > outputFxFirstWriteTime, $"Expected '{outputFxThirdWriteTime}' write time of '{outputFxThirdWriteTime}' to be greater than first write '{outputFxFirstWriteTime}'"); + Assert.That (outputFxThirdWriteTime > outputFxFirstWriteTime, Is.True, $"Expected '{outputFxThirdWriteTime}' write time of '{outputFxThirdWriteTime}' to be greater than first write '{outputFxFirstWriteTime}'"); } [Test] @@ -323,7 +322,7 @@ public void BuildMultiTargeting () var existingProjContent = File.ReadAllText (proj); var newProjContent = existingProjContent.Replace ($"{templatePlatform.ToFramework ()}", tfxs); File.WriteAllText (proj, newProjContent); - StringAssert.Contains (tfxs, File.ReadAllText (proj)); + Assert.That (File.ReadAllText (proj), Does.Contain (tfxs)); var xcodeProjName = "TemplateFx"; var xcodeProjDirSrc = Path.Combine (XCodeTestProjectDir, xcodeProjName); From ec40ca0867b5ebbd6b11668082acfcf0fa22113d Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Thu, 21 May 2026 09:20:05 +0200 Subject: [PATCH 2/2] [tests] Address PR review comments for NUnit v4 migration - Remove nunit.framework.legacy.dll from expected bundle files (the BundleStructure test project doesn't reference it) - Use centralized MicrosoftNETTestSdkPackageVersion property - Fix reversed actual/expected in Assert.That calls (ProjectTest.cs) - Add explicit null assertions before null-forgiving dereferences - Remove redundant null-forgiving operator on SingleOrDefault - Use Is.GreaterThan constraint instead of boolean comparison Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/dotnet/UnitTests/BundleStructureTest.cs | 1 - tests/dotnet/UnitTests/DotNetUnitTests.csproj | 2 +- tests/dotnet/UnitTests/ProjectTest.cs | 6 ++++-- tests/dotnet/UnitTests/WindowsTest.cs | 4 ++-- tests/dotnet/UnitTests/XcodeProjectTests.cs | 2 +- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/tests/dotnet/UnitTests/BundleStructureTest.cs b/tests/dotnet/UnitTests/BundleStructureTest.cs index 20d21a660f7d..f01bbb58fd5f 100644 --- a/tests/dotnet/UnitTests/BundleStructureTest.cs +++ b/tests/dotnet/UnitTests/BundleStructureTest.cs @@ -311,7 +311,6 @@ internal static void CheckAppBundleContents (ApplePlatform platform, IEnumerable if (platform != ApplePlatform.MacOSX) AddMultiRidAssembly (platform, expectedFiles, assemblyDirectory, "MonoTouch.Dialog", runtimeIdentifiers, forceSingleRid: (platform == ApplePlatform.MacCatalyst && !isReleaseBuild), includeDebugFiles: includeDebugFiles); expectedFiles.Add (Path.Combine (assemblyDirectory, "nunit.framework.dll")); - expectedFiles.Add (Path.Combine (assemblyDirectory, "nunit.framework.legacy.dll")); expectedFiles.Add (Path.Combine (assemblyDirectory, "nunitlite.dll")); expectedFiles.Add (Path.Combine (assemblyDirectory, "Mono.Options.dll")); AddMultiRidAssembly (platform, expectedFiles, assemblyDirectory, "Touch.Client", runtimeIdentifiers, platform == ApplePlatform.MacOSX || (platform == ApplePlatform.MacCatalyst && !isReleaseBuild), includeDebugFiles: includeDebugFiles); diff --git a/tests/dotnet/UnitTests/DotNetUnitTests.csproj b/tests/dotnet/UnitTests/DotNetUnitTests.csproj index 5a35feef92d1..f78948890a0e 100644 --- a/tests/dotnet/UnitTests/DotNetUnitTests.csproj +++ b/tests/dotnet/UnitTests/DotNetUnitTests.csproj @@ -8,7 +8,7 @@ - + diff --git a/tests/dotnet/UnitTests/ProjectTest.cs b/tests/dotnet/UnitTests/ProjectTest.cs index 3508a5377467..4fe2a5d3f241 100644 --- a/tests/dotnet/UnitTests/ProjectTest.cs +++ b/tests/dotnet/UnitTests/ProjectTest.cs @@ -760,8 +760,10 @@ public void BindingWithDefaultCompileInclude (ApplePlatform platform) // Verify that the MyNativeClass class exists in the assembly, and that it's actually a class. var ad = AssemblyDefinition.ReadAssembly (dllPath, new ReaderParameters { ReadingMode = ReadingMode.Deferred }); var myNativeClass = ad.MainModule.Types.FirstOrDefault (v => v.FullName == "MyApiDefinition.MyNativeClass"); + Assert.That (myNativeClass, Is.Not.Null, "MyNativeClass"); Assert.That (myNativeClass!.IsInterface, Is.False, "IsInterface"); var myStruct = ad.MainModule.Types.FirstOrDefault (v => v.FullName == "MyClassLibrary.MyStruct"); + Assert.That (myStruct, Is.Not.Null, "MyStruct type"); Assert.That (myStruct!.IsValueType, Is.True, "MyStruct"); var warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).Select (v => v.Message); @@ -2536,8 +2538,8 @@ public void BuildMyNativeAotAppWithTrimAnalysisWarning (ApplePlatform platform, } Assert.That (warnings.Length, Is.EqualTo (1), "Warning count"); - Assert.That ("IL2075", Is.EqualTo (warnings [0].Code), "Warning code"); - Assert.That ("'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperties()'. The return value of method 'System.Object.GetType()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.", Is.EqualTo (warnings [0].Message)); + Assert.That (warnings [0].Code, Is.EqualTo ("IL2075"), "Warning code"); + Assert.That (warnings [0].Message, Is.EqualTo ("'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperties()'. The return value of method 'System.Object.GetType()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.")); } [Test] diff --git a/tests/dotnet/UnitTests/WindowsTest.cs b/tests/dotnet/UnitTests/WindowsTest.cs index b71e01bcab70..a3fe051dbd38 100644 --- a/tests/dotnet/UnitTests/WindowsTest.cs +++ b/tests/dotnet/UnitTests/WindowsTest.cs @@ -376,13 +376,13 @@ public void RemoteTest (ApplePlatform platform, string runtimeIdentifiers) // Open the zipped app bundle and get the Info.plist using var zip = ZipFile.OpenRead (zippedAppBundlePath); ZipHelpers.DumpZipFile (zip, zippedAppBundlePath); - var infoPlistEntry = zip.Entries.SingleOrDefault (v => v.Name == "Info.plist")!; + var infoPlistEntry = zip.Entries.SingleOrDefault (v => v.Name == "Info.plist"); Assert.That (infoPlistEntry, Is.Not.Null, "Info.plist"); // Parse the Info.plist // PDictionary.FromStream requires a seekable stream, but the zip stream isn't seekable, so copy to a // MemoryStream and use that. Info.plist files aren't big, so this shouldn't become a memory consumption problem. - using var memoryStream = new MemoryStream ((int) infoPlistEntry.Length); + using var memoryStream = new MemoryStream ((int) infoPlistEntry!.Length); using var plistStream = infoPlistEntry.Open (); plistStream.CopyTo (memoryStream); diff --git a/tests/dotnet/UnitTests/XcodeProjectTests.cs b/tests/dotnet/UnitTests/XcodeProjectTests.cs index 89096c0cb944..aab50fe70c93 100644 --- a/tests/dotnet/UnitTests/XcodeProjectTests.cs +++ b/tests/dotnet/UnitTests/XcodeProjectTests.cs @@ -240,7 +240,7 @@ public void BuildIncremental (ApplePlatform platform) AssertTargetExecuted (allTargets, "_BuildXcodeProjects", "Third _BuildXcodeProjects"); Assert.That (expectedXcodeFxOutput, Does.Exist, $"Expected xcframework output '{expectedXcodeFxOutput}' did not exist."); var outputFxThirdWriteTime = File.GetLastWriteTime (expectedXcodeFxOutput); - Assert.That (outputFxThirdWriteTime > outputFxFirstWriteTime, Is.True, $"Expected '{outputFxThirdWriteTime}' write time of '{outputFxThirdWriteTime}' to be greater than first write '{outputFxFirstWriteTime}'"); + Assert.That (outputFxThirdWriteTime, Is.GreaterThan (outputFxFirstWriteTime), $"Expected '{expectedXcodeFxOutput}' third write time '{outputFxThirdWriteTime}' to be greater than first write '{outputFxFirstWriteTime}'"); } [Test]