BreadcrumbHomeResourcesBlog Top NUnit Annotations For You To Use July 6, 2021 Top NUnit Annotations for You to UseTest AutomationBy Luis Martinez and Oscar CalderinNUnit is an important framework. In this blog, we break down the basics of NUnit, including how to use NUnit annotations.Table of ContentsWhat Is NUnit?Why Use NUnit?How to Use NUnitTop NUnit Annotations to UseExample: NUnit Test ResultsGet Started With NUnit Annotations and MoreTable of Contents1 - What Is NUnit?2 - Why Use NUnit?3 - How to Use NUnit4 - Top NUnit Annotations to Use5 - Example: NUnit Test Results6 - Get Started With NUnit Annotations and MoreBack to topWhat Is NUnit?NUnit is a test Framework like JUnit. You can use NUnit to define your tests cases, tests suites and assertions. NUnit can run all the tests and show you a report. NUnit, like JUnit, enables test-driven development. You can also run your NUnit tests in Taurus. If you have a new project that uses .NET programming languages and you want to add unit tests, you can use open source NUnit. Back to topWhy Use NUnit?Here are the top seven reasons to use NUnit.NUnit runs very well with .NET programming languages.It is open source and it is free.It is easy to integrate it with testing projects.NUnit works with many integrated runners including Resharper and TestDriven .NET.NUnit has frequent version updates.NUnit has a graphical user interface.Very easy integration with Visual Studio and other IDEs.Back to topHow to Use NUnitNow let’s learn how to use NUnit.1. Download the FrameworkFirst, download the NUnit Framework. You can use various installation approaches.NUnit install via NuGet (If you are using Visual Studio). This is the preferred way. Use the other ways if you don’t have an internet connectionZip file download from NUnitCombined Approach2. Write Your TestsAfter downloading, it’s now time to write your tests. You can write them on your local machine or in the cloud.3. Use NUnit AnnotationsNUnit is basically composed of attributes, or annotations. These indicate to the framework to execute the tests that are implemented in the class, and also how to interpret them. Annotations tell the framework how to interpret the code. After this code is compiled, a dll file is generated that can be executed through a console or using the graphic interface. Tests also include assertions that allow checking and comparing values. Back to topTop NUnit Annotations to UseNow let’s take a look at the annotations and how to use them. The annotations are very easy to use: just add the annotation between brackets before the method declaration. With the annotation you can define the test: behavior (specifying Setup or TearDown method), assertions for example performance assertions like MaxTime method, and information like the Category method. AnnotationUsageCategorySpecifies one or more categories for the testCultureSpecifies cultures for which a test or fixture should be runIndicatesIndicates that a test should be skipped unless explicitly runIgnoreIndicates that a test shouldn't be run for some reasonMaxTimeSpecifies the maximum time in milliseconds for a test case to succeedOneTimeSetUpIdentifies methods to be called once prior to any child testsOneTimeTearDownIdentifies methods to be called once after all child testsPlatformSpecifies platforms for which a test or fixture should be runRandomSpecifies generation of random values as arguments to a parameterized testRepeatSpecifies that the decorated method should be executed multiple timesRetryCauses a test to rerun if it fails, up to a maximum number of timesTearDownIndicates a method of a TestFixture called immediately after each test methodTestMarks a method of a TestFixture that represents a testTestCaseMarks a method with parameters as a test and provides inline argumentsTimeoutProvides a timeout value in milliseconds for test casesSetUpIndicates a method of a TestFixture called immediately before each test method Let’s see some examples of the most common annotationsSetUpWe generally use this for code that needs to be executed before executing a test, with the purpose to not repeat the code in each test.Example: [SetUp] public void Initialize() { //driver = new FirefoxDriver(); browser = ConfigurationManager.AppSettings["browser"]; switch (browser) { case "Chrome": driver = new ChromeDriver(); break; case "Firefox": driver = new FirefoxDriver(); break; } driver.Manage().Window.Maximize(); } In this case, every test inherited in the [SetUp] annotation with the Initialize() method will be used to decide which browser to use, to open the test and to maximize the window.TearDownThis is an annotation that acts the opposite of [SetUp]. It means the code written with this attribute is executed last (after passing other lines of code).Example: [TearDown] public void EndTest() { if (TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Failed) { test.Log(LogStatus.Fail, TestContext.CurrentContext.Result.Message); } if (TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed) { test.Log(LogStatus.Pass, "Test Succesfull. "); } driver.Close(); report.EndTest(test); report.Flush(); report.Close(); }Here we use [TearDown] annotation to close the browser and create a report of the runned tests. This report can be viewed in a log or in GUI modem and can also be integrated into CI (see further down).TestThe declaration of the steps that are going to be executed in the test.Example: [Test] public void testLogin(string user, string message) { HomePage objHomePage = new HomePage(driver); objHomePage.goToLogin(); LoginPage objLoginPage = new LoginPage(driver); objLoginPage.loginWithUser(user); MyAccountPage objAccountPage = new MyAccountPage(driver); objAccountPage.waitForLoad(); Assert.AreEqual(objAccountPage.UserMessage(),message); }This is a simple login method that goes to the login page, sets the user and password in the respective fields, click on the login button and waits for the page to load. After that, it checks if the loaded page is correct with an assertion .NUnit also provides us with several annotations to parametrize our tests. This functionality can be used with the annotations [TestCase ] and [TestCaseSource]TestCaseThis annotation replaces the annotation Test we saw before, and allows creating a set of tests that execute the same code with different data inputs. Example: [TestCase(“user1”, “Welcome user1”)] [TestCase(“user2”, “Invalid User”)] [TestCase(“user3”,”Not Registered User”)] public void testLogin(string user, string pw){}In this example we defined that the test testLogin runs 3 times, and in each execution the data input is specified in the annotation of our Test Case.TestCaseSourceThis annotation is similar to the previous one and it’s used when the list of records is too big. It takes a public static property that it provides in every entry record. This allow us to load our record from a .csv file or from a database.[TestCaseSource("TestCases")] public void testLogin(string user, string pw){} In this case the script testLogin takes as data input every record that is stored in the property TestCases. TestCases method return the data type TestCaseData that can hold any type of data and expected resultsExample:public static List TestCases { get { var testCases = new List(); using (var fs = File.OpenRead(@"C:\users.csv")) using (var sr = new StreamReader(fs)) { string line = string.Empty; while (line != null) { line = sr.ReadLine(); if (line != null) { string[] split = line.Split(new char[] { ',' }, StringSplitOptions.None); string user= split[0]; string expectedMessage = split[1]; var testCase = new TestCaseData(user).Returns(expectedMessage ); testCases.Add(testCase); } } } return testCases; } } Back to topExample: NUnit Test ResultsNUnit provides a console mode, the nunit-console, which facilitates its use in the continuous integration process. In the console, the pass-fail results are provided immediately and no subjective human judgments or interpretations of test results are required. NUnit also has a graphical user interface, similar to the one used in JUnit, which it makes it easy to use for JUnit users. In the GUI you can see the execution of the tests, the test that is running and how many tests succeeded and failed. You can also see the result of each step and each assertion. Back to topGet Started With NUnit Annotations and MoreAfter creating your NUnit tests, you can run them in Taurus. Taurus adds additional options to running your tests, like test failure criteria, and also enables connecting your tests to BlazeMeter with the command -cloud. Read more here on Taurus.Install Taurus and get started today!This blog was originally published on July 5, 2018 and has since been updated for accuracy and relevance.START TESTING NOWBack to top
Luis Martinez Software Engineer Luis is a developer and tester with more than 5 years of experience. He has worked with automation tests and developing automation tools. He also has experience in Continuous integration using tools like Jenkins and Gitlab-Ci. He has participated in projects of performance testing using the JMeter tool and BlazeMeter platform. Currently leading teams in order to promote best practices and help others grow.
Oscar Calderin Computer Sciences Engineer, Abstracta Inc. Oscar Calderin is a Computer Sciences Engineer, with more than 5 years of experience in software development. In the past 3 years, he has worked as an Automation Engineer at Abstracta. Oscar has solid experience in automation testing and development, working with tools like Selenium, Java, CI tools as Jenkins, Maven, Gradle, JUnit and TestNG.