### Example of SetUp and TestMethod Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/setup.html Demonstrates how SetUp initializes a counter before a test method increments and asserts its value. ```csharp [SetUp] public void Init() { _counter = 0; } [Test] public void TestMethod() { _counter++; Assert.That(_counter, Is.EqualTo(1)); } ``` -------------------------------- ### Attribute Usage Example Source: https://docs.nunit.org/articles/nunit/technical-notes/usage/SetUp-and-TearDown.html Illustrates the application of SetUp and TearDown attributes within a base class and a derived test fixture. Demonstrates how exceptions in setup methods affect execution flow. ```csharp public class BaseClass { [SetUp] public void BaseSetUp() { /* ... */ } // Exception thrown! [TearDown] public void BaseTearDown() { /* ... */ } } [TestFixture] public class DerivedClass : BaseClass { [SetUp] public void DerivedSetUp() { /* ... */ } [TearDown] public void DerivedTearDown() { /* ... */ } [Test] public void TestMethod() { /* ... */ } } ``` -------------------------------- ### Usage Examples Source: https://docs.nunit.org/api/NUnit.Framework.Diagnostics.ProgressTraceListener.html Examples of how to add and remove the ProgressTraceListener to and from the trace listeners collection. ```APIDOC ### Usage Examples To activate, place the following snippet into the one-time set-up method of either a test's fixture or the set-up fixture of a project: ```csharp System.Trace.Listeners.Add(new ProgressTraceListener()); ``` Make sure to only add a listener once: ```csharp if (!System.Trace.Listeners.OfType().Any()) System.Trace.Listeners.Add(new ProgressTraceListener()); ``` Alternatively, add it in the one-time set-up and again remove it in the one-time tear-down: ```csharp _progressTraceListener = new ProgressTraceListener(); System.Trace.Listeners.Add(_progressTraceListener); // In tear-down: System.Trace.Listeners.Remove(_progressTraceListener); _progressTraceListener.Close(); ``` ``` -------------------------------- ### Start Property Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.Syntax.LineSpanDirectiveTriviaSyntax.html Gets the starting position of the line directive. ```csharp public LineDirectivePositionSyntax Start { get; } ``` -------------------------------- ### Demonstrate SetUp and TearDown execution order with inheritance Source: https://docs.nunit.org/articles/nunit/writing-tests/setup-teardown/index.html Illustrates how teardown methods are only called if the corresponding setup method at the same level was successfully executed. ```csharp public class BaseClass { [SetUp] public void BaseSetUp() { /* ... */ } // Exception thrown! [TearDown] public void BaseTearDown() { /* ... */ } } [TestFixture] public class DerivedClass : BaseClass { [SetUp] public void DerivedSetUp() { /* ... */ } [TearDown] public void DerivedTearDown() { /* ... */ } [Test] public void TestMethod() { ... } } ``` -------------------------------- ### Example SetUpFixture Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/setupfixture.html Example of a SetUpFixture class with OneTimeSetUp and OneTimeTearDown methods. ```csharp [SetUpFixture] public class MySetUpClass { [OneTimeSetUp] public void RunBeforeAnyTests() { } [OneTimeTearDown] public void RunAfterAnyTests() { } } ``` -------------------------------- ### Example .addins File Configuration Source: https://docs.nunit.org/articles/nunit-engine/extensions/Installing-Extensions.html This example demonstrates the structure of an .addins file, showing how to include assemblies and directories for extension discovery. Comments explain each line's purpose. ```plaintext # This line is a comment and is ignored. The next (blank) line is ignored as well. *.dll # include all dlls in the same directory addins/*.dll # include all dlls in the addins directory too special/myassembly.dll # include a specific dll in a special directory /some/other/directory/ # process another directory, which may contain its own addins file # note that an absolute path is allowed, but is probably not a good idea # in most cases ``` -------------------------------- ### Measure Time for Setup Hook Source: https://docs.nunit.org/articles/nunit/extending-nunit/Execution-Hooks.html Measures and logs the time taken for setup methods. Apply this attribute to a class or method to automatically time its setup phases. ```csharp [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public sealed class TimeMeasurementHookAttribute : ExecutionHookAttribute { private readonly Dictionary _starts = new(); public override void BeforeEverySetUpHook(HookData hookData) { _starts[hookData.Context.Test.FullName] = DateTime.UtcNow; } public override void AfterEverySetUpHook(HookData hookData) { var key = hookData.Context.Test.FullName; if (_starts.TryGetValue(key, out var start)) { var elapsed = DateTime.UtcNow - start; TestContext.Progress.WriteLine($"[Timing] " + $"{hookData.Context.Test.MethodName} " + $"took {elapsed.TotalMilliseconds:F1} ms"); } } } ``` ```csharp [TestFixture] [TimeMeasurementHook] public class SampleTests { [SetUp] public void HeavySetUp() { /* ... */ } [Test] public void FastTest() { /* ... */ } } ``` -------------------------------- ### Demonstrate Setup and Teardown Execution Order Source: https://docs.nunit.org/articles/nunit/writing-tests/setup-teardown/SetUp-and-TearDown-Changes.html Illustrates how NUnit 3.0 teardown methods are only called if the corresponding setup method at the same inheritance level was executed. ```csharp public class BaseClass { [SetUp] public void BaseSetUp() { /* ... */ } // Exception thrown! [TearDown] public void BaseTearDown() { /* ... */ } } [TestFixture] public class DerivedClass : BaseClass { [SetUp] public void DerivedSetUp() { /* ... */ } [TearDown] public void DerivedTearDown() { /* ... */ } [Test] public void TestMethod() { /* ... */ } } ``` -------------------------------- ### StartTime Property Source: https://docs.nunit.org/api/NUnit.Framework.Interfaces.ITestResult.html Gets or sets the time the test started running. ```APIDOC ## StartTime Property ### Description Gets or sets the time the test started running. ### Declaration ```csharp DateTime StartTime { get; } ``` ### Property Value - **DateTime** - Description ``` -------------------------------- ### Basic SetUp Attribute Usage Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/setup.html A parameterless attribute that can only be applied to methods. ```csharp [SetUp] ``` -------------------------------- ### Example of OneTimeSetUp Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/onetimesetup.html An example demonstrating the use of OneTimeSetUp to initialize a shared value. ```csharp [OneTimeSetUp] public void Init() { _sharedValue = 42; } [Test] public void UsesInitializedState() { Assert.That(_sharedValue, Is.EqualTo(42)); } ``` -------------------------------- ### Method: WithStart Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.Syntax.LineSpanDirectiveTriviaSyntax.html Updates the start position of the LineSpanDirectiveTriviaSyntax. ```APIDOC ## WithStart(LineDirectivePositionSyntax) ### Description Returns a new LineSpanDirectiveTriviaSyntax instance with the specified start position. ### Parameters #### Parameters - **start** (LineDirectivePositionSyntax) - Required - The new start position for the directive. ### Returns - **LineSpanDirectiveTriviaSyntax** - A new instance with the updated start position. ``` -------------------------------- ### Specify Additional Setup and TearDown Methods Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit1032.html Configure the analyzer to recognize additional setup and teardown methods, including overridden methods from base classes, via .editorconfig. ```editorconfig dotnet_diagnostic.NUnit.additional_setup_methods = MySetup dotnet_diagnostic.NUnit.additional_teardown_methods = MyTearDown dotnet_diagnostic.NUnit.additional_one_time_setup_methods = MyOneTimeSetup dotnet_diagnostic.NUnit.additional_one_time_teardown_methods = MyOneTimeTearDown ``` -------------------------------- ### Random GUIDs Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/random.html Example demonstrating how to generate random GUIDs using the RandomAttribute. Note that GUIDs do not support range specification. ```csharp [TestFixture] public class RandomGuidTests { [Test] public void TestWithRandomGuid([Random(3)] Guid value) { // Generates 3 random GUIDs // Note: Guid does not support min/max range Assert.That(value, Is.Not.EqualTo(Guid.Empty)); } } ``` -------------------------------- ### NUnit2040 Violation Example Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit2040.html Example of code that triggers the NUnit2040 error due to using SameAs on a Guid struct. ```csharp var expected = Guid.Empty; var actual = expected; Assert.That(actual, Is.SameAs(expected)); ``` -------------------------------- ### Initialize DocumentationProvider Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.DocumentationProvider.html Protected constructor for the abstract class. ```csharp protected DocumentationProvider() ``` -------------------------------- ### Attributes Property Declaration Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.Syntax.XmlElementStartTagSyntax.html Gets the list of attributes associated with the XML start tag. ```csharp public SyntaxList Attributes { get; } ``` -------------------------------- ### Build and Test the Adapter Source: https://docs.nunit.org/articles/developer-info/Packaging-the-V3-and-V4-Adapter.html Commands to execute the build process for testing and acceptance verification. ```shell build -t Test build -t Acceptance ``` -------------------------------- ### Create Adapter Packages Source: https://docs.nunit.org/articles/developer-info/Packaging-the-V3-and-V4-Adapter.html Command to generate the release packages from the solution root folder. ```shell build -t Package ``` -------------------------------- ### Get Line Span for Text Span Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.html Gets the line span for a given text span within the syntax tree. This is useful for determining the start and end lines and columns of a specific code segment. ```csharp public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default) ``` -------------------------------- ### Example of TearDown Attribute Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/teardown.html Demonstrates the usage of SetUp and TearDown attributes in a test fixture. ```csharp [SetUp] public void Init() { _testRan = false; } [TearDown] public void Cleanup() { Assert.That(_testRan, Is.True); } [Test] public void Add() { _testRan = true; Assert.That(2 + 2, Is.EqualTo(4)); } ``` -------------------------------- ### SetUpAttribute Class Source: https://docs.nunit.org/api/NUnit.Framework.SetUpAttribute.html Details regarding the SetUpAttribute class, its syntax, and constructor. ```APIDOC ## SetUpAttribute ### Description Identifies a method to be called immediately before each test is run. ### Namespace NUnit.Framework ### Assembly nunit.framework.dll ### Syntax ```csharp [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class SetUpAttribute : NUnitAttribute ``` ### Constructors #### SetUpAttribute() Initializes a new instance of the SetUpAttribute class. ##### Declaration ```csharp public SetUpAttribute() ``` ``` -------------------------------- ### Example of NUnit3002 suppression Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit3002.html Demonstrates a test fixture where a non-nullable field is initialized in a SetUp method, preventing CS8618 compiler warnings. ```csharp [TestFixture] internal sealed class SomeClassFixture { private SomeClass instance; [SetUp] public void Setup() { instance = new SomeClass(); } [Test] public void Test() { Assert.That(instance.MethodUnderTest(), Is.True) } } ``` -------------------------------- ### Migration Example: Classic Assert to Extension Methods Source: https://docs.nunit.org/articles/nunit/writing-tests/assertions/assertion-models/classic_extensions.html Demonstrates the transition from using ClassicAssert methods to their equivalent extension methods in NUnit. Ensure you have 'using NUnit.Framework;' imported for extension methods. ```csharp using NUnit.Framework.Legacy; ClassicAssert.AreEqual(expected, actual); ClassicAssert.IsTrue(condition, "Custom message", arg1, arg2); StringAssert.Contains("substring", str); ``` ```csharp using NUnit.Framework; Assert.AreEqual(expected, actual); Assert.IsTrue(condition, "Custom message", arg1, arg2); Assert.StringContains("substring", str); ``` -------------------------------- ### TNode Value Property Source: https://docs.nunit.org/api/NUnit.Framework.Interfaces.TNode.html Gets or sets the text content of the TNode. This is the data that the node holds, typically appearing between the start and end tags in XML. ```csharp public string? Value { get; set; } ``` -------------------------------- ### Implementing a Custom Addin Source: https://docs.nunit.org/articles/nunit/technical-notes/nunit-internals/specs/Engine-Addins-Spec.html Use the AddinAttribute and IAddin interface to create complex extensions that require manual registration. Ensure the factory class lacks an ExtensionAttribute to prevent duplicate installation. ```csharp [Addin] public class MyAddin : IAddin { public bool Install(IExtensionHost host) { var ep = host.GetExtensionPoint("/NUnit/Engine/DriverFactory"); ep.Install(new NUnit2DriverFactory()); } } public class NUnit2DriverFactory : IDriverFactory { /* ... */ } ``` -------------------------------- ### Example Violation of NUnit1026 Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit1026.html Demonstrates test, setup, and test case methods with incorrect accessibility levels (internal and private protected). NUnit requires these methods to be public. ```csharp private int Value; [SetUp] void NUnit1026SetUp() { Value = 42; } [Test] void NUnit1026SampleTest() { Assert.That(Value, Is.GreaterThan(0)); } [TestCase(1)] private protected static void NUnit1026SampleTest2(int i) { Assert.Pass(); } ``` -------------------------------- ### Access Default DocumentationProvider Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.DocumentationProvider.html Static property to retrieve the default implementation. ```csharp public static DocumentationProvider Default { get; } ``` -------------------------------- ### NUnit Test Class Example (C#) Source: https://docs.nunit.org/articles/nunit/getting-started/installation.html A basic C# test class generated by the NUnit template. It includes a Setup method and a simple test method that passes. ```csharp namespace TestProject1; public class Tests { [SetUp] public void Setup() { } [Test] public void Test1() { Assert.Pass(); } } ``` -------------------------------- ### Filter all namespaces under a root namespace Source: https://docs.nunit.org/articles/nunit/running-tests/Test-Selection-Language.html To inclusively select all namespaces under a root namespace, use a regular expression with the `namespace` keyword and the `=~` operator. This example matches namespaces starting with 'My.Name.Space' followed by either the end of the string or a dot. ```plaintext namespace =~ ^My\.Name\.Space($|\.) ``` -------------------------------- ### BeforeEverySetUpHook Implementation Source: https://docs.nunit.org/api/NUnit.Framework.ExecutionHookMethodsAttribute.html Override this method to implement custom logic that runs immediately before every [SetUp] or [OneTimeSetUp] method is executed. It receives HookData for the current test context. ```csharp public virtual void BeforeEverySetUpHook(HookData hookData) ``` -------------------------------- ### Create NUnit Packages Source: https://docs.nunit.org/articles/developer-info/Packaging-the-Console-and-Engine.html Run the build script with the 'Package' target to create the NuGet packages for the release. Ensure you are on the release branch and have the latest changes. ```bash build -Target Package ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/SubstringConstraint.html Examples of using the Substring Constraint. ```csharp [Test] public void SubstringConstraint_Examples() { string phrase = "Make your tests fail before passing!"; Assert.That(phrase, Does.Contain("tests")); Assert.That(phrase, Does.Contain("TESTS").IgnoreCase); Assert.That(phrase, Does.Not.Contain("missing")); } ``` -------------------------------- ### WithInitializer Method Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.Syntax.ImplicitObjectCreationExpressionSyntax.html Returns a new instance with the specified initializer. ```csharp public ImplicitObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) ``` -------------------------------- ### Violating code example Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit2010.html Example of code that triggers the NUnit2010 analyzer. ```csharp [Test] public void Test() { ClassicAssert.True(actual == expected); } ``` -------------------------------- ### NUnit Project File Structure Source: https://docs.nunit.org/articles/nunit/running-tests/NUnit-Test-Projects.html Example of an .nunit project file defining multiple configurations and assembly paths. ```xml ``` -------------------------------- ### NUnit2022 Violation Example Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit2022.html Example of an assertion failing because IEnumerable does not have a Count property. ```csharp [Test] public void Test() { var enumerable = new [] {1,2,3}.Where(i => i > 1); // Actual argument type 'IEnumerable' has no property 'Count'. Assert.That(enumerable, Has.Count.EqualTo(2)); } ``` -------------------------------- ### Implement One-Time vs Per-Test Setup and TearDown Hooks Source: https://docs.nunit.org/articles/nunit/extending-nunit/Execution-Hooks.html Demonstrates how to distinguish between suite-level and test-level lifecycle events using the HookData context. ```csharp [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public sealed class OneTimeVsPerTestSetupTearDownHookAttribute : ExecutionHookAttribute { public override void BeforeEverySetUpHook(HookData data) { var scope = data.Context.Test.IsSuite ? "OneTimeSetUp" : "SetUp"; TestContext.Progress.WriteLine($"{scope}: {data.HookedMethod?.Name}"); } public override void AfterEveryTearDownHook(HookData data) { var scope = data.Context.Test.IsSuite ? "OneTimeTearDown" : "TearDown"; TestContext.Progress.WriteLine($"{scope}: {data.HookedMethod?.Name}"); } } ``` -------------------------------- ### ClassicAssert.AreNotEqual usage example Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit2006.html Example of the code pattern that triggers the NUnit2006 warning. ```csharp [Test] public void Test() { ClassicAssert.AreNotEqual(expression1, expression2) } ``` -------------------------------- ### Running .NET Core Tests from Command Line Source: https://docs.nunit.org/articles/nunit/getting-started/dotnet-core-and-dotnet-standard.html Examples of how to run NUnit tests for .NET Core projects using the 'dotnet test' command. ```bash dotnet test ``` ```bash dotnet test ``` ```bash dotnet test .\test\NetCore10Tests\NetCore10Tests.csproj ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/UniqueItemsConstraint.html Examples demonstrating the usage of the UniqueItems constraint. ```csharp [Test] public void UniqueItemsConstraint_Examples() { int[] numbers = { 1, 2, 3, 4, 5 }; string[] names = { "Alice", "Bob", "Carol" }; // Basic uniqueness check Assert.That(numbers, Is.Unique); Assert.That(names, Is.Unique); // Fails: contains duplicates Assert.That(new[] { 1, 2, 2, 3 }, Is.Not.Unique); // Case-insensitive uniqueness Assert.That(new[] { "Alice", "ALICE" }, Is.Unique); // Passes: different case Assert.That(new[] { "Alice", "ALICE" }, Is.Not.Unique.IgnoreCase); // Passes: same when ignoring case } ``` -------------------------------- ### With Attribute Lists Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.Syntax.SwitchStatementSyntax.html Returns a new instance with the specified attribute lists. ```csharp public SwitchStatementSyntax WithAttributeLists(SyntaxList attributeLists) ``` -------------------------------- ### Examples of Use Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/SamePathConstraint.html Examples demonstrating the usage of the SamePath constraint. ```csharp [Test] public void SamePathConstraint_Examples() { Assert.That("/folder1/./junk/../folder2", Is.SamePath("/folder1/folder2")); Assert.That("/folder1/./junk/../folder2/x", Is.Not.SamePath("/folder1/folder2")); Assert.That(@"C:\folder1\folder2", Is.SamePath(@"C:\Folder1\Folder2").IgnoreCase); Assert.That("/folder1/folder2", Is.Not.SamePath("/Folder1/Folder2").RespectCase); } ``` -------------------------------- ### Theory Example Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/theory.html Example of a Theory test in NUnit. ```csharp public class SqrtTests { [DatapointSource] public double[] values = new double[] { 0.0, 1.0, -1.0, 42.0 }; [Theory] public void SquareRootDefinition(double num) { Assume.That(num >= 0.0); double sqrt = Math.Sqrt(num); Assert.That(sqrt >= 0.0); Assert.That(sqrt * sqrt, Is.EqualTo(num).Within(0.000001)); } } ``` -------------------------------- ### NUnit Project File Example (.csproj) Source: https://docs.nunit.org/articles/nunit/getting-started/installation.html This is the typical structure of a .csproj file for an NUnit test project, including necessary NuGet package references. Ensure packages are updated to the latest versions. ```xml net8.0 enable enable false all runtime; build; native; contentfiles; analyzers; buildtransitive all runtime; build; native; contentfiles; analyzers; buildtransitive ``` -------------------------------- ### Guid Generation Source: https://docs.nunit.org/articles/nunit/writing-tests/Randomizer-Methods.html Method for generating RFC 4122 compliant version 4 Guids. ```APIDOC ## NextGuid() ### Description Generates a version 4 Guid conforming to RFC 4122 using random data. Available since version 3.8. ``` -------------------------------- ### Initialize MethodInfoAdapter Source: https://docs.nunit.org/api/NUnit.Framework.TestContext.MethodInfoAdapter.html Constructor for wrapping an IMethodInfo instance. ```csharp public MethodInfoAdapter(IMethodInfo methodInfo) ``` -------------------------------- ### Examples of Use Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/SamePathOrUnderConstraint.html Examples demonstrating the use of the SamePathOrUnder constraint. ```csharp [Test] public void SamePathOrUnderConstraint_Examples() { Assert.That("/folder1/./junk/../folder2", Is.SamePathOrUnder("/folder1/folder2")); Assert.That("/folder1/junk/../folder2/./folder3", Is.SamePathOrUnder("/folder1/folder2")); Assert.That("/folder1/junk/folder2/folder3", Is.Not.SamePathOrUnder("/folder1/folder2")); Assert.That(@"C:\folder1\folder2\folder3", Is.SamePathOrUnder(@"C:\Folder1\Folder2").IgnoreCase); Assert.That("/folder1/folder2/folder3", Is.Not.SamePathOrUnder("/Folder1/Folder2").RespectCase); } ``` -------------------------------- ### Load and Run Tests via FrameworkController Source: https://docs.nunit.org/articles/nunit/technical-notes/nunit-internals/Framework-Api.html Demonstrates how a driver uses reflection to instantiate the FrameworkController and execute test actions within an AppDomain. ```csharp var myHandler = new MyHandlerClass(); // implements ICallbackEventHandler // Create the controller var args = new object[] { "my.test.assembly.dll", new Hashtable()}; var controller = domain.CreateInstanceAndUnwrap( "nunit.framework", "NUnit.Framework.Api.FrameworkController", false, 0, null, args, null, null, null); // Load the assembly args = new object[] { controller, myHandler }; domain.CreateInstanceAndUnwrap( "nunit.framework", "NUnit.Framework.Api.FrameworkController+LoadTestsAction", false, 0, null, args, null, null, null); // myHandler.GetCallbackResult() should return an Xml string with the result // of the Load, which was passed to it by the framework. // We're not checking this here, as we normally would do. // Run the tests args = new object[] { controller, "", myHandler }; domain.CreateInstanceAndUnwrap( "nunit.framework", "NUnit.Framework.Api.FrameworkController+RunTestsAction", false, 0, null, args, null, null, null); // myHandler.GetCallbackResult() should return an Xml string with the results // of running the test, which was passed to it by the framework. ``` -------------------------------- ### ClassicAssert.NotNull usage example Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit2018.html Example of the classic assertion model that triggers the NUnit2018 analyzer. ```csharp [Test] public void Test() { object obj = null; ClassicAssert.NotNull(obj); } ``` -------------------------------- ### Enable Debugging via Command Line Source: https://docs.nunit.org/articles/vs-test-adapter/Debugging.html Use the dotnet test command to pass debug settings directly to the adapter. ```bash dotnet test -- NUnit.DebugExecution=true ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/WhiteSpaceConstraint.html Provides examples of using the WhiteSpace constraint with Assert.That. ```csharp [Test] public void WhiteSpaceConstraint_Examples() { Assert.That("", Is.WhiteSpace); // Empty string Assert.That(" ", Is.WhiteSpace); // Space Assert.That(" \t\n", Is.WhiteSpace); // Mixed whitespace Assert.That(null, Is.WhiteSpace); // Null Assert.That("Hello", Is.Not.WhiteSpace); Assert.That(" Hello ", Is.Not.WhiteSpace); // Has non-whitespace content } ``` -------------------------------- ### Create NUnit Test Project via Command Line Source: https://docs.nunit.org/articles/nunit/getting-started/installation.html Use this command to create a new NUnit test project in a specified directory. This is a cross-platform solution. ```bash dotnet new nunit -o TestProject1 ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/CollectionSupersetConstraint.html Illustrative examples of using the CollectionSupersetConstraint in NUnit tests. ```csharp [Test] public void CollectionSupersetConstraint_Examples() { int[] actual = { 1, 2, 3, 4, 5 }; Assert.That(actual, Is.SupersetOf(new[] { 1, 3 })); // Passes Assert.That(actual, Is.SupersetOf(new[] { 1, 2, 3, 4, 5 })); // Passes (equal sets) Assert.That(actual, Is.SupersetOf(new int[] { })); // Passes (superset of empty) Assert.That(actual, Is.Not.SupersetOf(new[] { 1, 6 })); // Passes (missing 6) // Case-insensitive string comparison string[] colors = { "Red", "Green", "Blue", "Yellow" }; Assert.That(colors, Is.SupersetOf(new[] { "red", "blue" }).Using((IEqualityComparer)StringComparer.OrdinalIgnoreCase)); } ``` -------------------------------- ### SetUpFixtureAttribute Methods Source: https://docs.nunit.org/api/NUnit.Framework.SetUpFixtureAttribute.html Details of the methods available for the SetUpFixtureAttribute. ```APIDOC ### Methods View Source #### BuildFrom(ITypeInfo) Builds a NUnit.Framework.Internal.SetUpFixture from the specified type. ##### Declaration ```csharp public IEnumerable BuildFrom(ITypeInfo typeInfo) ``` ##### Parameters Type | Name | Description ---|---|--- ITypeInfo | typeInfo | The type info of the fixture to be used. ##### Returns Type | Description ---|--- IEnumerable | ``` -------------------------------- ### NUnit Classic vs. Constraint Model Equivalents Source: https://docs.nunit.org/articles/nunit/writing-tests/assertions/assertions.html Examples showing equivalent assertions between the Classic Model and the Constraint Model in NUnit. ```csharp Assert.AreEqual(4, 2 + 2); ``` ```csharp Assert.That(2 + 2, Is.EqualTo(4)); ``` -------------------------------- ### Example Usage Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/testassemblydirectoryresolve.html Example demonstrating how to verify the TestAssemblyDirectoryResolveAttribute exists and can be instantiated. ```csharp [Test] public void VerifyTestAssemblyDirectoryResolveAttributeExists() { // Verify the attribute type exists and can be instantiated var attribute = new TestAssemblyDirectoryResolveAttribute(); Assert.That(attribute, Is.Not.Null); Assert.That(attribute, Is.InstanceOf()); } ``` -------------------------------- ### WithOptions Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.Compilation.html Creates a new compilation with the specified options. ```csharp public Compilation WithOptions(CompilationOptions options) ``` -------------------------------- ### Global Usings Example (C#) Source: https://docs.nunit.org/articles/nunit/getting-started/installation.html This file typically contains global using directives, making NUnit framework elements available without explicit usings in every test file. ```csharp global using NUnit.Framework; ``` -------------------------------- ### NUnit1004 Violation Example Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit1004.html Example of a test method where the TestCaseAttribute provides more arguments than the method accepts. ```csharp [TestCase("1", "2")] public void NUnit1004SampleTest(string parameter1) { Assert.That(parameter1, Is.EqualTo("1")); } ``` -------------------------------- ### SyntaxTokenList Constructors Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.SyntaxTokenList.html Provides information on how to create instances of SyntaxTokenList. ```APIDOC ## SyntaxTokenList Constructors ### SyntaxTokenList(SyntaxToken) #### Description Initializes a new instance of the `SyntaxTokenList` struct with a single `SyntaxToken`. ### Method `public SyntaxTokenList(SyntaxToken token)` ### Parameters - **token** (SyntaxToken) - The `SyntaxToken` to include in the list. ### SyntaxTokenList(params SyntaxToken[]) #### Description Initializes a new instance of the `SyntaxTokenList` struct with an array of `SyntaxToken` objects. ### Method `public SyntaxTokenList(params SyntaxToken[] tokens)` ### Parameters - **tokens** (SyntaxToken[]) - An array of `SyntaxToken` objects to include in the list. ### SyntaxTokenList(IEnumerable) #### Description Initializes a new instance of the `SyntaxTokenList` struct with a collection of `SyntaxToken` objects. ### Method `public SyntaxTokenList(IEnumerable tokens)` ### Parameters - **tokens** (IEnumerable) - An `IEnumerable` collection of `SyntaxToken` objects to include in the list. ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/CollectionSubsetConstraint.html Illustrative examples of using the CollectionSubset constraint in NUnit tests. ```csharp [Test] public void CollectionSubsetConstraint_Examples() { int[] superset = { 1, 2, 3, 4, 5 }; Assert.That(new[] { 1, 3 }, Is.SubsetOf(superset)); // Passes Assert.That(new[] { 1, 2, 3, 4, 5 }, Is.SubsetOf(superset)); // Passes (equal sets are subsets) Assert.That(new int[] { }, Is.SubsetOf(superset)); // Passes (empty set is subset of any set) Assert.That(new[] { 1, 6 }, Is.Not.SubsetOf(superset)); // Passes (6 not in superset) // Case-insensitive string comparison string[] colors = { "Red", "Green", "Blue" }; Assert.That(new[] { "red", "blue" }, Is.SubsetOf(colors).Using((IEqualityComparer)StringComparer.OrdinalIgnoreCase)); } ``` -------------------------------- ### Initialize TestEngine Source: https://docs.nunit.org/articles/nunit-engine/Test-Engine-API.html Standard sequence for acquiring and configuring the ITestEngine interface. ```csharp ITestEngine engine = TestEngineActivator.CreateInstance(...); engine.WorkDirectory = ...; // Defaults to the current directory engine.InternalTraceLevel = ...; // Defaults to off ``` -------------------------------- ### Define SetUpAttribute Syntax Source: https://docs.nunit.org/api/NUnit.Framework.SetUpAttribute.html The attribute is applied to methods and is not allowed to be used multiple times on the same method. ```csharp [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class SetUpAttribute : NUnitAttribute ``` -------------------------------- ### WithStartQuoteToken for XmlNameAttributeSyntax Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.Syntax.XmlNameAttributeSyntax.html Sets the start quote token for an XmlNameAttributeSyntax. Use this to update only the start quote. ```csharp public XmlNameAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) ``` -------------------------------- ### Get Constant Value Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.CSharpExtensions.html Attempts to get the constant value of an expression. Requires a SemanticModel and ExpressionSyntax. ```csharp public static Optional GetConstantValue(this SemanticModel? semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken = default) ``` -------------------------------- ### Implement a custom project loader Source: https://docs.nunit.org/articles/nunit-engine/extensions/creating-extensions/Project-Loaders.html Use the Extension and ExtensionProperty attributes to define a class that implements IProjectLoader for specific file extensions. ```csharp [Extension] [ExtensionProperty("FileExtension", ".xxx")] [ExtensionProperty("FileExtension", ".yyy")] public class SomeProjectLoader : IProjectLoader { /* ... */ } ``` -------------------------------- ### DesktopStrongNameProvider Constructors Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.DesktopStrongNameProvider.html Initializes a new instance of the DesktopStrongNameProvider class with optional key file search paths and temporary path. ```csharp public DesktopStrongNameProvider(ImmutableArray keyFileSearchPaths) ``` ```csharp public DesktopStrongNameProvider(ImmutableArray keyFileSearchPaths = default, string? tempPath = null) ``` -------------------------------- ### Get Await Expression Info Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.CSharpExtensions.html Gets information about an await expression. Requires a SemanticModel and AwaitExpressionSyntax. ```csharp public static AwaitExpressionInfo GetAwaitExpressionInfo(this SemanticModel? semanticModel, AwaitExpressionSyntax awaitExpression) ``` -------------------------------- ### Constructor: ColorConsole(ColorStyle) Source: https://docs.nunit.org/api/NUnit.Common.ColorConsole.html Initializes a new instance of the ColorConsole class with a specified color style. ```APIDOC ## Constructor: ColorConsole(ColorStyle) ### Description Initializes a new instance of the ColorConsole class. Sets the console color in the constructor. ### Parameters #### Path Parameters - **style** (ColorStyle) - Required - The color style to use. ### Request Example new ColorConsole(ColorStyle.Header); ``` -------------------------------- ### ForEachStatementInfo.GetEnumeratorMethod Property Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.ForEachStatementInfo.html Gets the method symbol used to get the enumerator for the collection. This property is nullable. ```csharp public IMethodSymbol? GetEnumeratorMethod { get; } ``` -------------------------------- ### Example Violation of NUnit1006 Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit1006.html This example shows a test case where ExpectedResult is incorrectly used with a void method. ```csharp [TestCase(1, ExpectedResult = "1")] public void NUnit1006SampleTest(int inputValue) { return; } ``` -------------------------------- ### Implement Option Methods Source: https://docs.nunit.org/api/NUnit.Options.Option.html Methods for retrieving option details, invoking actions, and parsing values. ```csharp public string[] GetNames() ``` ```csharp public string[] GetValueSeparators() ``` ```csharp public void Invoke(OptionContext c) ``` ```csharp protected abstract void OnParseComplete(OptionContext c) ``` ```csharp protected static T Parse(string value, OptionContext c) ``` ```csharp public override string ToString() ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/GreaterThanOrEqualConstraint.html Provides various examples of using the GreaterThanOrEqual constraint with numbers, DateTime, and tolerance. ```csharp [Test] public void GreaterThanOrEqualConstraint_Examples() { Assert.That(7, Is.GreaterThanOrEqualTo(7)); Assert.That(7, Is.GreaterThanOrEqualTo(3)); Assert.That(7, Is.AtLeast(7)); // With DateTime Assert.That(DateTime.Now, Is.GreaterThanOrEqualTo(DateTime.Today)); // With tolerance Assert.That(10.1, Is.GreaterThanOrEqualTo(10.0).Within(0.5)); } ``` -------------------------------- ### ShowHelp Property Declaration Source: https://docs.nunit.org/api/NUnit.Common.CommandLineOptions.html Displays help information. ```csharp public bool ShowHelp { get; } ``` -------------------------------- ### Specify StartupObject for Executable Applications Source: https://docs.nunit.org/articles/nunit/running-tests/NUnitLite-Runner.html When testing an executable application, specify the StartupObject in your project file to resolve conflicts with multiple Main methods. ```xml TestProject.Program ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/NaNConstraint.html Examples demonstrating the NaN constraint with various floating-point values and operations. ```csharp [Test] public void NaNConstraint_Examples() { // NaN results from undefined operations Assert.That(double.NaN, Is.NaN); Assert.That(float.NaN, Is.NaN); Assert.That(0.0 / 0.0, Is.NaN); Assert.That(Math.Sqrt(-1), Is.NaN); // Regular numbers are not NaN Assert.That(42.0, Is.Not.NaN); Assert.That(double.PositiveInfinity, Is.Not.NaN); Assert.That(double.NegativeInfinity, Is.Not.NaN); } ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/EndsWithConstraint.html Provides examples of using the EndsWith constraint with different inputs and modifiers. ```csharp [Test] public void EndsWithConstraint_Examples() { string phrase = "Make your tests fail before passing!"; Assert.That(phrase, Does.EndWith("!")); Assert.That(phrase, Does.EndWith("passing!")); Assert.That(phrase, Does.EndWith("PASSING!").IgnoreCase); Assert.That(phrase, Does.Not.EndWith("failing")); } ``` -------------------------------- ### SetUpFixtureAttribute Constructors Source: https://docs.nunit.org/api/NUnit.Framework.SetUpFixtureAttribute.html Details of the constructors available for the SetUpFixtureAttribute. ```APIDOC ### Constructors View Source #### SetUpFixtureAttribute() ##### Declaration ```csharp public SetUpFixtureAttribute() ``` ``` -------------------------------- ### Example Test with Multiple Output Methods Source: https://docs.nunit.org/articles/nunit/technical-notes/usage/Trace-and-Debug-Output.html Demonstrates various ways to write output during a test, including Debug, Trace, Console, and NUnit-specific TestContext methods. ```csharp [Test] public void Test1() { Debug.WriteLine("This is Debug.WriteLine"); Trace.WriteLine("This is Trace.WriteLine"); Console.WriteLine("This is Console.Writeline"); TestContext.WriteLine("This is TestContext.WriteLine"); TestContext.Out.WriteLine("This is TestContext.Out.WriteLine"); TestContext.Progress.WriteLine("This is TestContext.Progress.WriteLine"); TestContext.Error.WriteLine("This is TestContext.Error.WriteLine"); Assert.Pass(); } ``` -------------------------------- ### LineSpanDirectiveTriviaSyntax WithStart Method Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.Syntax.LineSpanDirectiveTriviaSyntax.html Use this method to create a new LineSpanDirectiveTriviaSyntax with an updated start position. The original object is not modified. ```csharp public LineSpanDirectiveTriviaSyntax WithStart(LineDirectivePositionSyntax start) ``` -------------------------------- ### Check if character is a valid identifier start Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.SyntaxFacts.html Determines if the provided character is a valid starting character for an identifier. ```csharp public static bool IsIdentifierStartCharacter(char ch) ``` -------------------------------- ### Set start CDATA token Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.Syntax.XmlCDataSectionSyntax.html Returns a new CDATA section node with the specified start token. ```csharp public XmlCDataSectionSyntax WithStartCDataToken(SyntaxToken startCDataToken) ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/ThrowsNothingConstraint.html Examples demonstrating how to use the Throws.Nothing constraint to verify that code does not throw exceptions. ```csharp [Test] public void ThrowsNothingConstraint_Examples() { // Test that method completes without throwing Assert.That(() => Add(1, 2), Throws.Nothing); // Verify cleanup doesn't throw var resource = new DisposableResource(); Assert.That(() => resource.Dispose(), Throws.Nothing); } private static int Add(int a, int b) => a + b; private class DisposableResource : IDisposable { public void Dispose() { } } ``` -------------------------------- ### SetUpAttribute Constructor Declaration Source: https://docs.nunit.org/api/NUnit.Framework.SetUpAttribute.html The default constructor for the SetUpAttribute class. ```csharp public SetUpAttribute() ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/LessThanConstraint.html Provides various examples of using the LessThan constraint with numbers, DateTime, and with a tolerance. ```csharp [Test] public void LessThanConstraint_Examples() { Assert.That(3, Is.LessThan(7)); Assert.That(-5, Is.Negative); Assert.That(5, Is.Not.Negative); // With DateTime Assert.That(DateTime.Today, Is.LessThan(DateTime.Now)); // With tolerance Assert.That(9.5, Is.LessThan(10.0).Within(0.1)); } ``` -------------------------------- ### AfterEverySetUpHook Implementation Source: https://docs.nunit.org/api/NUnit.Framework.ExecutionHookMethodsAttribute.html Override this method to implement custom logic that runs immediately after every [SetUp] or [OneTimeSetUp] method is executed. It receives HookData for the current test context. ```csharp public virtual void AfterEverySetUpHook(HookData hookData) ``` -------------------------------- ### Initialize ColorConsole Source: https://docs.nunit.org/api/NUnit.Common.ColorConsole.html Constructor for ColorConsole accepting a ColorStyle parameter. ```csharp public ColorConsole(ColorStyle style) ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/MultipleOfConstraint.html Examples of using the MultipleOf Constraint for testing multiples, even, and odd numbers. ```csharp [Test] public void MultipleOfConstraint_Examples() { // Test for multiples Assert.That(12, Is.MultipleOf(3)); // 12 is a multiple of 3 Assert.That(12, Is.MultipleOf(4)); // 12 is a multiple of 4 Assert.That(12, Is.Not.MultipleOf(5)); // 12 is not a multiple of 5 // Even numbers Assert.That(0, Is.Even); Assert.That(2, Is.Even); Assert.That(100, Is.Even); Assert.That(-4, Is.Even); Assert.That(3, Is.Not.Even); // Odd numbers Assert.That(1, Is.Odd); Assert.That(3, Is.Odd); Assert.That(99, Is.Odd); Assert.That(-7, Is.Odd); Assert.That(4, Is.Not.Odd); } ``` -------------------------------- ### Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/FalseConstraint.html Provides examples of using the False constraint with different boolean expressions and variables. ```csharp [Test] public void FalseConstraint_Examples() { Assert.That(2 + 2 == 5, Is.False); var isDisabled = false; Assert.That(isDisabled, Is.False); ICollection list = new List(); Assert.That(list.IsReadOnly, Is.False); // With nullable booleans bool? isDeleted = false; Assert.That(isDeleted, Is.False); } ``` -------------------------------- ### Run NUnit Tests with CSPROJ Source: https://docs.nunit.org/articles/nunit/technical-notes/usage/Visual-Studio-Support.html This command loads tests from a project file and uses a configuration file with the same name as the project file, located in the same directory. ```bash nunit.exe nunit.tests.csproj ``` -------------------------------- ### Collection Containment Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/ContainsHelper.html Examples demonstrating collection containment assertions using Contains.Item. ```csharp [Test] public void ContainsHelper_Collection_Examples() { int[] numbers = { 1, 2, 3, 4, 5 }; // Test for item in collection Assert.That(numbers, Contains.Item(3)); Assert.That(numbers, Does.Contain(3).And.Contain(5)); // Equivalent forms Assert.That(numbers, Does.Contain(3)); Assert.That(numbers, Has.Member(3)); } ``` -------------------------------- ### SetUpFixtureAttribute Class Source: https://docs.nunit.org/api/NUnit.Framework.SetUpFixtureAttribute.html Information about the SetUpFixtureAttribute class, including its purpose, inheritance, and syntax. ```APIDOC ## Class SetUpFixtureAttribute Identifies a class as containing OneTimeSetUpAttribute or OneTimeTearDownAttribute methods for all the test fixtures under a given namespace. ### Inheritance object Attribute NUnitAttribute SetUpFixtureAttribute ### Implements IFixtureBuilder ### Inherited Members Attribute.GetCustomAttributes(MemberInfo, Type) Attribute.GetCustomAttributes(MemberInfo, Type, bool) Attribute.GetCustomAttributes(MemberInfo) Attribute.GetCustomAttributes(MemberInfo, bool) Attribute.IsDefined(MemberInfo, Type) Attribute.IsDefined(MemberInfo, Type, bool) Attribute.GetCustomAttribute(MemberInfo, Type) Attribute.GetCustomAttribute(MemberInfo, Type, bool) Attribute.GetCustomAttributes(ParameterInfo) Attribute.GetCustomAttributes(ParameterInfo, Type) Attribute.GetCustomAttributes(ParameterInfo, Type, bool) Attribute.GetCustomAttributes(ParameterInfo, bool) Attribute.IsDefined(ParameterInfo, Type) Attribute.IsDefined(ParameterInfo, Type, bool) Attribute.GetCustomAttribute(ParameterInfo, Type) Attribute.GetCustomAttribute(ParameterInfo, Type, bool) Attribute.GetCustomAttributes(Module, Type) Attribute.GetCustomAttributes(Module) Attribute.GetCustomAttributes(Module, bool) Attribute.GetCustomAttributes(Module, Type, bool) Attribute.IsDefined(Module, Type) Attribute.IsDefined(Module, Type, bool) Attribute.GetCustomAttribute(Module, Type) Attribute.GetCustomAttribute(Module, Type, bool) Attribute.GetCustomAttributes(Assembly, Type) Attribute.GetCustomAttributes(Assembly, Type, bool) Attribute.GetCustomAttributes(Assembly) Attribute.GetCustomAttributes(Assembly, bool) Attribute.IsDefined(Assembly, Type) Attribute.IsDefined(Assembly, Type, bool) Attribute.GetCustomAttribute(Assembly, Type) Attribute.GetCustomAttribute(Assembly, Type, bool) Attribute.Equals(object) Attribute.GetHashCode() Attribute.Match(object) Attribute.IsDefaultAttribute() Attribute.TypeId object.GetType() object.MemberwiseClone() object.ToString() object.Equals(object, object) object.ReferenceEquals(object, object) ### Namespace NUnit.Framework ### Assembly nunit.framework.dll ### Syntax ```csharp [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class SetUpFixtureAttribute : NUnitAttribute, IFixtureBuilder ``` ``` -------------------------------- ### String Containment Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/constraints/ContainsHelper.html Examples demonstrating string containment assertions using Contains.Substring. ```csharp [Test] public void ContainsHelper_String_Examples() { string text = "Hello World"; // Test for substring Assert.That(text, Contains.Substring("World")); Assert.That(text, Contains.Substring("WORLD").IgnoreCase); // Equivalent to Does.Contain for strings Assert.That(text, Does.Contain("World")); } ``` -------------------------------- ### Example TestFixture Class Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/testfixture.html A basic example of a C# class marked with the TestFixture attribute. ```csharp namespace NUnit.Tests { using System; using NUnit.Framework; [TestFixture] public class SuccessTests { // ... } } ``` -------------------------------- ### Basic Example Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/values.html A basic example demonstrating the use of the ValuesAttribute with multiple parameters. ```csharp [Test] public void ValuesAttribute_BasicExample([Values(1, 2, 3)] int x, [Values("A", "B")] string s) { Assert.That(x, Is.GreaterThan(0)); Assert.That(s, Is.Not.Null); } ``` -------------------------------- ### Visit Constructor Initializer Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CSharp.CSharpSyntaxVisitor.html Visits a ConstructorInitializerSyntax node. ```APIDOC ## VisitConstructorInitializer(ConstructorInitializerSyntax node) ### Description Visits a ConstructorInitializerSyntax node. ### Method Virtual ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Initialize OperationVisitor Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.Operations.OperationVisitor-2.html Protected constructor for the abstract visitor class. ```csharp protected OperationVisitor() ``` -------------------------------- ### Async Test Example Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/test.html An example of an asynchronous test method using the Test attribute. ```csharp [TestFixture] public sealed class AsyncTests { [Test] public async Task AddAsync() { await Task.Delay(1); Assert.That(2 + 2, Is.EqualTo(4)); } } ``` -------------------------------- ### CreateDefaultWin32Resources Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.Compilation.html Generates default Win32 resources. ```APIDOC ## CreateDefaultWin32Resources ### Description Generates default Win32 resources including version information and manifest. ### Parameters - **versionResource** (bool) - Required - **noManifest** (bool) - Required - **manifestContents** (Stream) - Optional - **iconInIcoFormat** (Stream) - Optional ### Response #### Success Response (200) - **Stream** - The stream containing the generated resources. ``` -------------------------------- ### Example Usage of RangeAttribute Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/range.html An example demonstrating how to use the RangeAttribute with a parameterized test method. ```csharp [Test] public void MyTest( [Values(1, 2, 3)] int x, [Range(0.2, 0.6, 0.2)] double d) { Assert.That(x, Is.GreaterThan(0)); Assert.That(d, Is.GreaterThan(0.0)); } ``` -------------------------------- ### Example in AssemblyInfo.cs Source: https://docs.nunit.org/articles/nunit/writing-tests/attributes/nontestassembly.html An example showing how to apply the NonTestAssembly attribute in the AssemblyInfo.cs file. ```csharp using NUnit.Framework; [assembly: NonTestAssembly] ``` -------------------------------- ### CommandLineAnalyzerReference Constructor Source: https://docs.nunit.org/api/Microsoft.CodeAnalysis.CommandLineAnalyzerReference.html Initializes a new instance of the struct with a file path. ```csharp public CommandLineAnalyzerReference(string path) ``` -------------------------------- ### Enable Microsoft.Testing.Platform in Project Source: https://docs.nunit.org/articles/vs-test-adapter/NUnit-And-Microsoft-Test-Platform.html Add these properties to a top-level PropertyGroup in your csproj file to enable MTP and configure the project as an executable. ```xml true Exe ``` -------------------------------- ### NUnit Assert.True Examples Source: https://docs.nunit.org/articles/nunit/writing-tests/assertions/classic-assertions/Assert.True.html Example test method demonstrating the usage of Assert.True and Assert.IsTrue with various boolean conditions. ```csharp [Test] public void True_Examples() { Assert.True(2 + 2 == 4); Assert.IsTrue(true); Assert.True("Hello".StartsWith("H")); } ``` -------------------------------- ### NUnit1005 Violation Example Source: https://docs.nunit.org/articles/nunit-analyzers/NUnit1005.html An example of a test method where the ExpectedResult type (bool) does not match the method return type (int). ```csharp [TestCase(1, ExpectedResult = true)] public int NUnit1005SampleTest(int inputValue) { return inputValue; } ```