How to create an NUnit test project that is also a self-running console app .exe

  1. Create your NUnit Test project as a Windows Console Application, not as a Class Library.
  2. Then make your main Program look like this:
    [TestFixture]
    public class Program
    {
        static void Main(string[] args)
        {
            NUnit.ConsoleRunner.Runner.Main(
                new[]{Assembly.GetExecutingAssembly().Location }
                );
        }
    
        [TestCase("Aa - Bb")]
        public void WhenValidatingForename_should_accept_valid_characters(string validInput)
        {
            var result= new ClassUnderTest().Validate(validInput);
            Assert.IsTrue(result);
        }
    
        [TestCase("X<")]
        public void WhenValidatingForename_should_reject_invalid_characters(string invalidInput)
        {
            var result= new ClassUnderTest().Validate(invalidInput);
            Assert.IsFalse(result);
        }
    }
  3. Then, add a reference not only to nunit.framework.dll but also to nunit-console-runner.dll

You now have a self-running executable that runs all your tests, but still behaves in the usual way in a build script, or when running tests inside Visual Studio with TestRunner or Resharper or similar.
NB You may need to check if your build scripts are hard-coded to expect a Test project to be a .dll.

5 thoughts on “How to create an NUnit test project that is also a self-running console app .exe”

  1. I am in the process of figuring this part out I am using VS2019 Community Edition and I can tell the coding is different now then back in 2012.
    I have about 70 NUnit test classes set up for Selenium Automated testing on a website using
    Chrome, IE and Mozilla. Could you please help update me on what I need to do?

    1. Sorry I haven’t used selenium in NUnit for a few years, but if you got to this page from googling, add ‘selenium’ to your search?

  2. Hi Chris,

    Is it possible to create standalone executable tests. I am having one solution with two projects where project 1 has all required classes used by Nunit test which are placed Project 2.

    Thanks in advance!

    Thanks,
    Swapnil

    1. Hi Swapnil, that’s pretty much what this blog post does? Although with dotnet core there is no need anymore since `dotnet test …` will do it.

  3. Hi Chris,

    I’m looking for the right way to run specific NUnit tests from the NUnit console. I’ve created in VS a Console Application that contains all the tests classes, but it seems that I can run only one file (in this case – the .csproj file) which runs all the tests in the project at once. What CLI command should I use in order to select and run a specific test in the project?

    Thanks!
    Adam

Comments are closed.

How to create an NUnit test project that…

by Chris F Carroll read it in 1 min
5