Next-Gen App & Browser
Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles
Learn about C# asserts including how they work, different types, usage, custom assertions, and best practices for reliable test-driven development.
Published on: September 28, 2025
C# asserts are the statements for verifying expected behavior in automated tests across different points in the workflow of the website or web application. Rather than checking a single method’s output, assertions are used to validate page elements, states, or user interactions.
For example, after submitting a form, you might assert that a success message is displayed, a specific element is visible, or the URL has changed as expected. These checks ensure that the web application responds correctly and help catch regressions or unexpected behavior early in the testing process.
In test automation, a C# assert is a statement provided by a testing framework (like MSTest, NUnit, or xUnit) that checks whether a specific condition is true during a test execution. If the condition evaluates to false, the test fails immediately, and the framework reports this failure.
How Do Assertions Work in C# Test Automation?
Assertions generally require two components: a Boolean expression that represents the condition you want to verify and a message that is displayed if that condition evaluates to false.
For example: Assert.That(condition, "Failure message");
In this case,condition is the Boolean expression under evaluation, and the failure message provides context if the assertion does not hold. When an assertion fails, the current test or method halts immediately, and the failure is recorded. This behavior allows you to quickly pinpoint which expected condition was not satisfied, making it easier to detect logical errors early in the test execution.
How to Create Custom C# Asserts?
Custom assertions in C# simplify tests by encapsulating repetitive validation logic, making test scripts more readable, maintainable, and aligned with domain-specific language concepts.
When performing automation testing with C#, assertions allow you to verify that a specific condition is true at a defined point within your method. They are used to validate preconditions, postconditions, and invariants, ensuring that the assumptions you made while writing the unit test remain valid during test execution.
You can implement assertions using Debug.Assert(condition, message) from the System.Diagnostics namespace. If the condition evaluates to true, execution continues normally. If the condition evaluates to false, the assertion fails and identifies the exact location where the expected condition was not met, providing the message you provided.
Assertions usually take two arguments: a Boolean expression representing the condition to verify, and a message that will be displayed if the condition is false.
Example:
Assert.That(condition, "Failure message");
Here, the condition is the Boolean expression being checked, and a failure message is shown if the condition evaluates to false.
If the assertion fails, the current method or test stops executing at that point, and the failure is reported. It helps you immediately identify which expected condition was not met and helps detect logical errors early.
Note: Run C# automated tests on an online Selenium Grid. Try LambdaTest Now!
If you are not using a unit testing framework, C# provides assertion mechanisms in the System.Diagnostics namespace.
There are three main types of assertions: Debug, Trace, and Contract. Each serves a different purpose and has distinct behavior in Debug and Release builds.
Debug.Assert is evaluated only in Debug builds. If the condition is false, a message box is displayed showing the failure message and the call stack. Execution of the current method continues after dismissing the message box.
You can use Debug.Assert to validate internal logic and catch errors during development without affecting the performance of Release builds.
Syntax:
Debug.Assert(condition, "Failure message");
Trace.Assert behaves similarly to Debug.Assert but is evaluated in both Debug and Release builds. It is useful for identifying critical issues in runtime or production-like environments.
If the assertion fails, a failure message is sent to the configured trace listeners (for example, the Output window or a log file). Execution continues after the failure, allowing you to monitor multiple conditions without halting the software application.
Syntax:
Trace.Assert(condition, "Failure message");
Contract.Assert is part of the Code Contracts library. It is used to validate assumptions about software state, such as invariants or critical conditions. If the condition evaluates to false, an exception is thrown.
Syntax:
Contract.Assert(condition, "Failure message");
Important: Code Contracts, including Contract.Assert, is no longer maintained by Microsoft and should not be used in new projects. Modern alternatives include runtime validation with exceptions or using static analysis tools.
For a deeper comparison of how assertions differ from verifications in Selenium and when to use each approach, you can refer to this blog on assert vs verify in Selenium.
In the following section, we will focus on using assertions for C# testing with frameworks like Selenium. For more information, you can check out this Selenium C# tutorial.
We will cover NUnit and MSTest. Both are free and can be selected at the start of a Visual Studio project:
NUnit is a widely used C# testing framework for testing web applications across most .NET platforms. You can use NUnit asserts to verify that code behaves as expected.
New to NUnit? Visit this NUnit tutorial.
Test Scenario:
Implementation:
Below is the automation script for automating the above test scenario, demonstrating practical implementation, validations, and use of assertions.
namespace NUnitAsserts
{
internal class NUnitExample
{
private static IWebDriver driver;
[SetUp]
public void OpenApplication()
{
driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://ecommerce-playground.lambdatest.io/");
}
[Test]
public void ValidateProductIsAddedToTheCart()
{
// Navigate to the Components page
driver.FindElement(By.XPath("//a[contains(normalize-space(.), 'Shop by Category')]")).Click();
driver.FindElement(By.XPath("//a[.//span[normalize-space(text())='Components']]")).Click();
// Hover the first HTC Touch product HD in the carousel
Actions builder = new Actions(driver);
builder.MoveToElement(driver.FindElement(By.XPath("//div[@class='carousel-item active']/img[@title='HTC Touch HD']")))
.Build().Perform();
// Wait for the product menu to be visible
IWebElement composeButton = driver.FindElement(By.XPath("//button[span[text()='Add to Cart']]"));
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => composeButton.Displayed);
// Click Add to Cart button
composeButton.Click();
// Wait for the notification message to be visible
IWebElement notificationMessage = driver.FindElement(By.XPath("//div[contains(@class, 'toast') and @role='alert']"));
wait.Until(d => notificationMessage.Displayed);
// Validate that the cart contains one item
string expectedText = driver.FindElement(By.XPath("//div[@class='cart-icon']/span")).Text;
Assert.That(expectedText.Equals("1"), "The cart was not updated.");
// Other ways to validate
Assert.IsTrue(expectedText.Equals("1"), "The cart was not updated.");
Assert.AreEqual(expectedText, "1", "The cart was not updated.");
Assert.IsFalse(expectedText.Equals("0"), "The cart was not updated.");
Assert.AreNotEqual(expectedText, "0", "The cart was not updated.");
Assert.IsNotNull(expectedText, "The cart was not updated.");
}
[TearDown]
public void CloseBrowser()
{
driver.Dispose();
}
}
}
Code Walkthrough:
Test Execution:
In Visual Studio, the tests are displayed in the Test Explorer pane after the project is built. You can run them by clicking on the Run icon or by selecting the test you want to run, right-clicking, and pressing Run.
When running the tests locally, you will see the browser window open, and all the defined steps execute. Once the test finishes, you can see the results in the explorer.
MSTest is a built-in C# testing framework provided by Microsoft to test web applications across most .NET platforms efficiently. It provides assertions to validate that the code works as expected.
New to MSTest? Check out this MSTest tutorial.
Test Scenario:
Open the LambdaTest eCommerce Playground. Click ‘Shop by Category’. Select the ‘Software’ category. Validate that the web page has the correct title.
Implementation:
The following automation script implements the above test scenario, showcasing practical execution, element validations, and the use of assertions to verify expected results.
namespace MSTestAsserts
{
[TestClass]
public class MSTestExample
{
private static IWebDriver driver;
[TestInitialize]
public void OpenApplication()
{
driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://ecommerce-playground.lambdatest.io/");
}
[TestMethod]
public void ValidateCorrectCategoryIsSelected()
{
// Navigate to the Components page
driver.FindElement(By.XPath("//a[contains(normalize-space(.), 'Shop by Category')]")).Click();
driver.FindElement(By.XPath("//a[.//span[normalize-space(text())='Software']]")).Click();
// Wait for the filter menu to be displayed
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => driver.FindElement(By.Id("mz-filter-0")));
// Validate the title of the page is correct
Assert.IsTrue(driver.Title.Equals("Software"), "The page was not loaded.");
// Other ways to validate
Assert.AreEqual("Software", driver.Title, "The page was not loaded.");
Assert.IsFalse(driver.Title == "0", "The page was not loaded.");
}
[TestCleanup]
public void CloseBrowser()
{
driver.Quit();
}
}
}
Code Walkthrough:
Test Execution:
To execute tests, select the tests from Visual Studio and click the Run icon (same as above in the NUnit case).
The browser window will open on the local machine, and the steps will be done inside the web pages. After the test is executed, the status will be updated in the Test Explorer.
C# assertions are essential for verifying that your code behaves as expected. Whether you are using Debug.Assert, Trace.Assert, or framework-specific assertions in NUnit or MSTest, they ensure functional correctness within the environment where the test runs.
However, a test passing in one test environment does not ensure that the same logic will hold true across different browsers and operating systems. This is where cloud testing platforms such as LambdaTest become helpful.
LambdaTest allows you to perform C# automation testing online across a wide array of real browsers, operating systems without the need to maintain an in-house testing infrastructure. By running tests on an online Selenium Grid, the assertions you’ve written are validated in real-world conditions, giving you confidence that your web application behaves consistently across different environments.
To get started, visit this guide on Selenium C# testing with LambdaTest.
For demonstration, let’s take an example of NUnit assert. We will use the same test scenario.
To run your C# tests with NUnit assert on the LambdaTest Selenium Grid, you need the LambdaTest Grid URL, which serves as the endpoint for executing your tests remotely. Connecting to LambdaTest requires a username and access key, which you can get from your LambdaTest Account Settings..
For security, it’s best to store these values as environment variables, ensuring they are not exposed in your repository. Once the connection is configured, you can define the browser capabilities that your tests will use.
To generate capabilities, you can use the LambdaTest Automation Capability Generator.
options.BrowserVersion = "latest";
Dictionary<string, object> ltOptions = new Dictionary<string, object>
{
["username"] = LT_USERNAME,
["accessKey"] = LT_ACCESS_KEY,
["platformName"] = platform,
["build"] = build,
["project"] = project,
["w3c"] = true
};
options.AddAdditionalOption("LT:Options", ltOptions);
return new RemoteWebDriver(new Uri($"https://{LT_USERNAME}:{LT_ACCESS_KEY}{gridURL}"), options.ToCapabilities());
}
}
}
Everything else stays the same, like we did for local test execution.
Now run the test through Visual Studio Code and visit the LambdaTest Web Automation dashboard to view your test results.
Custom assertions can clean up your test script by encapsulating repetitive validation logic, expressing intent naturally with domain concepts, and improving overall test maintainability.
You can implement them using the Assert class of MSTest, or with any testing framework, to build clearer and more expressive tests.
Here is an example of how you can build that:
public static class CustomAssert
{
public static void IsPositive(this Assert assert, int value)
{
if (value <= 0)
{
throw new AssertFailedException($"Expected a positive number but got {value}");
}
}
}
And using it in your test:
[TestClass]
public class MathTests
{
[TestMethod]
public void CheckIfNumberIsPositive()
{
int result = -5; // This would typically come from a method you're testing
Assert.That.IsPositive(result);
}
}
If the assertion fails, you should see this test log.
It’s important to remember that well-structured assertions make your tests both reliable and maintainable. By adopting certain best practices, you ensure that each test clearly communicates its intent and generates actionable results when something goes wrong.
In test automation, assertions in C# are critical for validating expected outcomes and ensuring software reliability. By understanding built-in C# assert types, using them correctly in automated tests, and implementing custom assertions where needed, testers can catch errors early and enforce precise behavior. Using C# assertions strategically within test scripts improves detection of failures, enhances test coverage, and ensures automated suites provide accurate, actionable results.
Did you find this page helpful?
More Related Hubs