134

By default nunit tests run alphabetically. Does anyone know of any way to set the execution order? Does an attribute exist for this?

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
Riain McAtamney
  • 6,342
  • 17
  • 49
  • 62
  • This looks like a duplicate but you can see my answer to that [here](http://stackoverflow.com/questions/497699/is-it-bad-form-to-count-on-the-order-of-your-nunit-unit-tests/497741#497741) – Johnno Nolan Jul 03 '09 at 10:44
  • 7
    Why would you want to do this? It sounds like you have a dependency on the run order, which is a bad thing. You need to reconsider why you want this. Unit tests should run in isolation and be totally independent of others. It sounds like you are creating candidates for the test smell [Erratic Tests](http://xunitpatterns.com/Erratic%20Test.html). – RichardOD Jul 03 '09 at 09:56
  • 12
    @RichardOD - should != must. And it really isn't event a should, because actually almost all integration tests are run in order - ask you QA team if they randomise the order of their testing. – tymtam Apr 10 '13 at 01:37
  • 4
    I currently have some tests whose order seems to matter even though it shouldn't. Personally, I'd like a way to randomize the test order specifically to help me ensure that my tests AREN'T somehow order-dependent. Of course, what I'd REALLY like would be a test runner that would run all my tests in random order until it finds a problem, or I say stop. If I ran that overnight, and everything was still green in the morning, then I could be confident that I've eliminated the last of the unintended side effects. – Mel Mar 05 '14 at 13:56
  • 1
    this question would be made more relevant if the question was updated to specify we are talking about integration tests here... We all know the rules about unit testing, at least if you've read XUnit test patterns and followed Uncle Bob etc.. you do.. but frameworks such as NUnit are also really useful for getting integration tests up and running quickly as well.. and you definitely don't want those to be random, especially when an expensive database setup is involved.. – nrjohnstone Apr 23 '17 at 18:29

16 Answers16

194

I just want to point out that while most of the responders assumed these were unit tests, the question did not specify that they were.

nUnit is a great tool that can be used for a variety of testing situations. I can see appropriate reasons for wanting to control test order.

In those situations I have had to resort to incorporating a run order into the test name. It would be great to be able to specify run order using an attribute.

Les
  • 3,150
  • 4
  • 29
  • 41
  • You mean you called your tests, for example, `001_first_test` `002_second_test` and so on? – ashes999 Feb 15 '12 at 20:48
  • Yes, that's right, although I typically use a pattern that allows me to easily insert tests if necessary, so maybe 010_first_test, 020_second_test, etc. – Les Feb 16 '12 at 23:41
  • This is actually a good work-around, albeit NUnit might break it anytime -- it's undocumented. I ended up going with MbUnit, because I can specify test dependencies. – ashes999 Feb 17 '12 at 00:55
  • Also wanted to mention that I would not put an ordinal in the text of the test name. So 010_test_name, 020_test_name, etc. – Les Feb 17 '12 at 16:07
  • 97
    Thank you for the only sane answer here. This is a specific question, yet somehow vague pedantic answers are being upvoted. Yes, we all know what unit tests should be, that's not the question though. – Egor Pavlikhin Jul 05 '12 at 14:34
  • 1
    You should _not_ rely on the run order being alphabetic. Many test runners run your tests simultaneously on many threads or processes and not necessarily in alphabetical order. For instance, NCrunch prioritizes tests based on code you change (impacted tests), then on whether they failed last time, then on whether they run quickly or slowly. If you want a _defined order_, simply create a meta-runner for those tests and exclude them from the regular runs. – Abel Nov 11 '15 at 02:15
  • 4
    Another good reason to specify order is to catch certain problems first before continuing with the rest of the test suite. in other words, if my test to create a user fails then I don't need everything else to run before I find out this result. In my other test I probably mock the user but it's important to me that this be the first test to fail - particularly when the test suite is large. – Bron Davies Feb 04 '16 at 04:07
179

NUnit 3.2.0 added an OrderAttribute, see:

https://github.com/nunit/docs/wiki/Order-Attribute

Example:

public class MyFixture
{
    [Test, Order(1)]
    public void TestA() { ... }


    [Test, Order(2)]
    public void TestB() { ... }

    [Test]
    public void TestC() { ... }
}
Răzvan Flavius Panda
  • 21,730
  • 17
  • 111
  • 169
  • 8
    Thanx, right to the point what I was looking for - and no discussions, why it's good or bad :) – aknoepfel Sep 01 '16 at 14:44
  • 2
    And then they make it an integer , instead of decimal, so if one has to insert test, all tests have to be re-numbered. – epitka Nov 21 '16 at 17:56
  • 1
    You could always start with very large numbers like millions or something if you want to introduce middle items that way - just more typing. Imo there should be an easier way to order things than use numbers for priority like a method dependency tree, but each has it's own dis/advantages. – Răzvan Flavius Panda Nov 22 '16 at 04:18
  • 11
    Good answer, but beware, documentation states tests do not wait for prior tests to finish. – ROX Feb 20 '17 at 18:17
  • Interestingly, in my experience, if we add Test and Order attributes separately, there is no guarantee of ordering of tests. – A.T. Nov 28 '19 at 06:34
  • New link https://docs.nunit.org/articles/nunit/writing-tests/attributes/order.html – Frank Escobar Apr 07 '21 at 17:03
  • Old question, but I would add that if tests are in different classes, the order won't be taken into consideration. If you want to organize the tests in different classes to avoid a long class, you can use the partial class feature. – Suciu Eus Sep 20 '21 at 12:54
51

Your unit tests should each be able to run independently and stand alone. If they satisfy this criterion then the order does not matter.

There are occasions however where you will want to run certain tests first. A typical example is in a Continuous Integration situation where some tests are longer running than others. We use the category attribute so that we can run the tests which use mocking ahead of the tests which use the database.

i.e. put this at the start of your quick tests

[Category("QuickTests")]

Where you have tests which are dependant on certain environmental conditions, consider the TestFixtureSetUp and TestFixtureTearDown attributes, which allow you to mark methods to be executed before and after your tests.

Arion
  • 31,011
  • 10
  • 70
  • 88
NeedHack
  • 2,943
  • 3
  • 30
  • 44
  • 2
    @Chris, I tend not to use these attributes, this is an interesting blog post- http://jamesnewkirk.typepad.com/posts/2007/09/why-you-should-.html. Nice point about category tests though. – RichardOD Jul 03 '09 at 13:43
  • 37
    Another example of order dependent tests is when you want to use your nunit framework to run an Integration Test... – Byron Ross Jul 18 '11 at 07:55
  • 1
    @ByronRoss: I tend to make tests bigger when I do that, and lean on the existing unit tests as much as possible so I can write fewer tests. Then each full run through can fail separately. I also try to design my data so that it can live separately from existing data, rather than *depending* on existing data. – Merlyn Morgan-Graham Dec 15 '11 at 20:58
  • 2
    If you don't run your tests in random order, how can you verify that they actually work when run out of order? What you are saying is analogous to saying "If your software has no bugs, testing is uneccessary". – jforberg Jun 11 '14 at 08:51
  • @jforberg: If you have a failure which occurs randomly, how do you say when you have fixed it? – NeedHack Jun 16 '14 at 14:30
  • @NeedHack See for example how it's done in RSpec. What you do is use a random seed to decide the order. If you have problems with a particular order, write down the seed and then run only with that seed until the problem is fixed. It's not a perfect approach as it relies on randomness to find errors, but it's much better than running tests in the same order every time. – jforberg Jun 16 '14 at 14:37
  • Another example of when test order matters is when the target code is using static classes. A static constructor is created automatically before the first instance is created or any static members are referenced. If e.g. verifying constructor logic, you'd want that test case to be the first to run. – Reyhn Mar 21 '15 at 08:00
  • My reason for specifying the order is run time. If you run 8 in parallel and as the last test queues up the longest running test you have, it'll be running on it's own. Where if you ran the longest running tests in parallel to start, all the shorter tests will fill the dead space. – BradLaney May 26 '16 at 21:55
  • @MerlynMorgan-Graham I don't think making tests bigger should ever be a decision you want to resort to. The more granular your tests are, the faster you will be able to tell what's broken when looking at reports. If I have a test that contains 100 steps and fails somewhere in between, it'll take me a lot longer to find it and trouble shoot it than looking at test #45 out of 100 tests. – Sakamoto Kazuma Apr 05 '17 at 19:15
  • This just goes to show how unit tests per se are useful for a whole lot more than simply unit testing. You can use them for all sorts of things such as data setup, data tear down, scheduled tasks, performance testing, load testing, model based testing... the limits are endless! – Ben Power Aug 02 '18 at 05:31
  • Keep in mind that NUnit has more use cases than pure unit testing, for example I use it in my Selenium E2E tests. If a test takes a long time to run, I want that test case to be executed first, so that it has finished when the other tests are done. If a 5-minute test is executed among the last tests, that will (unnecessarily) increase the suite execution time by 5 minutes. – Agent Shoulder Sep 18 '20 at 09:07
23

Wanting the tests to run in a specific order does not mean that the tests are dependent on each other - I'm working on a TDD project at the moment, and being a good TDDer I've mocked/stubbed everything, but it would make it more readable if I could specify the order which the tests results are displayed - thematically instead of alphabetically. So far the only thing I can think of is to prepend a_ b_ c_ to classes to classes, namespaces and methods. (Not nice) I think a [TestOrderAttribute] attribute would be nice - not stricly followed by the framework, but a hint so we can achieve this

William
  • 231
  • 2
  • 2
10

Regardless of whether or not Tests are order dependent... some of us just want to control everything, in an orderly fashion.

Unit tests are usually created in order of complexity. So, why shouldn't they also be run in order of complexity, or the order in which they were created?

Personally, I like to see the tests run in the order of which I created them. In TDD, each successive test is naturally going to be more complex, and take more time to run. I would rather see the simpler test fail first as it will be a better indicator as to the cause of the failure.

But, I can also see the benefit of running them in random order, especially if you want to test that your tests don't have any dependencies on other tests. How about adding an option to test runners to "Run Tests Randomly Until Stopped"?

Mont Pierce
  • 131
  • 1
  • 3
9

I am testing with Selenium on a fairly complex web site and the whole suite of tests can run for more than a half hour, and I'm not near to covering the entire application yet. If I have to make sure that all previous forms are filled in correctly for each test, this adds a great deal of time, not just a small amount of time, to the overall test. If there's too much overhead to running the tests, people won't run them as often as they should.

So, I put them in order and depend on previous tests to have text boxes and such completed. I use Assert.Ignore() when the pre-conditions are not valid, but I need to have them running in order.

  • @NiklasRingdahl if you are using visual studio with nunit, dump nunit and use MS tests. then you can utilize visual studio's orderedtest file to arrange test cases in the order you want them executed – Rahul Lodha Jun 04 '15 at 18:25
9

I really like the previous answer.

I changed it a little to be able to use an attribute to set the order range:

namespace SmiMobile.Web.Selenium.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using NUnit.Framework;

    public class OrderedTestAttribute : Attribute
    {
        public int Order { get; set; }


        public OrderedTestAttribute(int order)
        {
            Order = order;
        }
    }

    public class TestStructure
    {
        public Action Test;
    }

    class Int
    {
        public int I;
    }

    [TestFixture]
    public class ControllingTestOrder
    {
        private static readonly Int MyInt = new Int();

        [TestFixtureSetUp]
        public void SetUp()
        {
            MyInt.I = 0;
        }

        [OrderedTest(0)]
        public void Test0()
        {
            Console.WriteLine("This is test zero");
            Assert.That(MyInt.I, Is.EqualTo(0));
        }

        [OrderedTest(2)]
        public void ATest0()
        {
            Console.WriteLine("This is test two");
            MyInt.I++; Assert.That(MyInt.I, Is.EqualTo(2));
        }


        [OrderedTest(1)]
        public void BTest0()
        {
            Console.WriteLine("This is test one");
            MyInt.I++; Assert.That(MyInt.I, Is.EqualTo(1));
        }

        [OrderedTest(3)]
        public void AAA()
        {
            Console.WriteLine("This is test three");
            MyInt.I++; Assert.That(MyInt.I, Is.EqualTo(3));
        }


        [TestCaseSource(sourceName: "TestSource")]
        public void MyTest(TestStructure test)
        {
            test.Test();
        }

        public IEnumerable<TestCaseData> TestSource
        {
            get
            {
                var assembly =Assembly.GetExecutingAssembly();
                Dictionary<int, List<MethodInfo>> methods = assembly
                    .GetTypes()
                    .SelectMany(x => x.GetMethods())
                    .Where(y => y.GetCustomAttributes().OfType<OrderedTestAttribute>().Any())
                    .GroupBy(z => z.GetCustomAttribute<OrderedTestAttribute>().Order)
                    .ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());

                foreach (var order in methods.Keys.OrderBy(x => x))
                {
                    foreach (var methodInfo in methods[order])
                    {
                        MethodInfo info = methodInfo;
                        yield return new TestCaseData(
                            new TestStructure
                                {
                                    Test = () =>
                                        {
                                            object classInstance = Activator.CreateInstance(info.DeclaringType, null);
                                            info.Invoke(classInstance, null);
                                        }
                                }).SetName(methodInfo.Name);
                    }
                }

            }
        }
    }
}
Yasel
  • 2,920
  • 4
  • 40
  • 48
PvtVandals
  • 123
  • 1
  • 3
  • I think this approach is great. Do note though that the reflection code is going to pull all methods with the attribute, so if you are trying to run a specific test fixture, you may be surprised to find that it runs more than you thought. You can easily modify the LINQ query if this is not the desired behavior. See the links in my answer for more info. – Chrispy Nov 19 '14 at 22:15
  • ``OrderedTest`` is no longer supported in NUnit 3. – Conrad Feb 19 '16 at 19:51
7

I know this is a relatively old post, but here is another way to keep your test in order WITHOUT making the test names awkward. By using the TestCaseSource attribute and having the object you pass in have a delegate (Action), you can totally not only control the order but also name the test what it is.

This works because, according to the documentation, the items in the collection returned from the test source will always execute in the order they are listed.

Here is a demo from a presentation I'm giving tomorrow:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace NUnitTest
{
    public class TestStructure
    {
        public Action Test;
    }

    class Int
    {
        public int I;
    }

    [TestFixture]
    public class ControllingTestOrder
    {
        private static readonly Int MyInt= new Int();

        [TestFixtureSetUp]
        public void SetUp()
        {
            MyInt.I = 0;
        }

        [TestCaseSource(sourceName: "TestSource")]
        public void MyTest(TestStructure test)
        {
            test.Test();
        }

        public IEnumerable<TestCaseData> TestSource
        {
            get
            {
                yield return new TestCaseData(
                    new TestStructure
                    {
                        Test = () =>
                        {
                            Console.WriteLine("This is test one");
                            MyInt.I++; Assert.That(MyInt.I, Is.EqualTo(1));
                        }
                    }).SetName(@"Test One");
                yield return new TestCaseData(
                    new TestStructure
                    {
                        Test = () =>
                        {
                            Console.WriteLine("This is test two");
                            MyInt.I++; Assert.That(MyInt.I, Is.EqualTo(2));
                        }
                    }).SetName(@"Test Two");
                yield return new TestCaseData(
                    new TestStructure
                    {
                        Test = () =>
                        {
                            Console.WriteLine("This is test three");
                            MyInt.I++; Assert.That(MyInt.I, Is.EqualTo(3));
                        }
                    }).SetName(@"Test Three");
            }
        }
    }
}
Dave Bush
  • 2,382
  • 15
  • 12
  • I use this pattern for paralleled integration tests that would be too time consuming to run linearly. All the tests are on one type so I use an Action, and every Action has a key that says what is does "ShouldBeFoo". This way what the test does will be visible in the test name, and the TestCaseSource can be filtered so different types of tests are grouped together. Ironically, I don't care about execution order, but agree that it would work. – Novaterata Sep 05 '14 at 20:27
  • Using the `TestCaseSource` as a way to run ordered tests is a stroke of genius. Well done. I've taken this approach along with the one below and added a few additional modifications to make it easier to use. See the links in my answer for additional info, but the underlying idea is from this great answer! – Chrispy Nov 19 '14 at 22:17
  • Sadly, with NUnit 3, the source of ``TestCaseSource`` must be static, which precludes using pattern. Bummer. – Conrad Feb 19 '16 at 20:06
  • @Conrad. I don't see what difference making the method static or not makes. The test still return in order either way. – Dave Bush Feb 19 '16 at 22:30
  • It's not the method that needs to be static - the source (variable or property) of ``TestCaseSource`` must be a static object in NUnit 3, or the tests will not execute. And you can't create dynamic objects within a static object. That's why it won't work in v. 3. – Conrad Feb 20 '16 at 15:56
  • @Conrade You tried it? Works for me https://github.com/DaveMBush/NUnit3Samples/blob/master/NUnit3Samples/6.%20Managing%20Tests/A.%20ControllingOrder/OrderingTest.cs – Dave Bush Feb 20 '16 at 17:04
  • My mistake - I was forgetting to make class vars ``static``. When I do that, everything works well. – Conrad Feb 23 '16 at 16:24
5

I am working with Selenium WebDriver end-to-end UI test cases written in C#, which are run using NUnit framework. (Not unit cases as such)

These UI tests certainly depend on order of execution, as other test needs to add some data as a precondition. (It is not feasible to do the steps in every test)

Now, after adding the 10th test case, i see NUnit wants to run in this order: Test_1 Test_10 Test_2 Test_3 ..

So i guess i have to too alphabetisize the test case names for now, but it would be good to have this small feature of controlling execution order added to NUnit.

Hexa
  • 51
  • 1
  • 1
  • 9
    Disagree to Arran : UI tests are inherently sequences of small steps. Each step shoud be a test (Reason - if it fails, I need to know which step) . Sequences can be independent, but within a sequence, order matters & stop on failure is necessary. – Zasz Aug 02 '12 at 19:29
3

There are very good reasons to utilise a Test Ordering mechanism. Most of my own tests use good practice such as setup/teardown. Others require huge amounts of data setup, which can then be used to test a range of features. Up till now, I have used large tests to handle these (Selenium Webdriver) integration tests. However, I think the above suggested post on https://github.com/nunit/docs/wiki/Order-Attribute has a lot of merit. Here is an example of why ordering would be extremely valuable:

  • Using Selenium Webdriver to run a test to download a report
  • The state of the report (whether it's downloadable or not) is cached for 10 minutes
  • That means, before every test I need to reset the report state and then wait up to 10 minutes before the state is confirmed to have changed, and then verify the report downloads correctly.
  • The reports cannot be generated in a practical / timely fashion through mocking or any other mechanism within the test framework due to their complexity.

This 10 minute wait time slows down the test suite. When you multiply similar caching delays across a multitude of tests, it consumes a lot of time. Ordering tests could allow data setup to be done as a "Test" right at the beginning of the test suite, with tests relying on the cache to bust being executed toward the end of the test run.

2

This question is really old now, but for people who may reach this from searching, I took the excellent answers from user3275462 and PvtVandals / Rico and added them to a GitHub repository along with some of my own updates. I also created an associated blog post with some additional info you can look at for more info.

Hope this is helpful for you all. Also, I often like to use the Category attribute to differentiate my integration tests or other end-to-end tests from my actual unit tests. Others have pointed out that unit tests should not have an order dependency, but other test types often do, so this provides a nice way to only run the category of tests you want and also order those end-to-end tests.

Chrispy
  • 81
  • 3
  • can you help me with an issue I have, here is the link:http://stackoverflow.com/questions/31281395/run-testfixtures-in-order-with-nunit – Morgan Soren Jul 08 '15 at 17:29
2

If you are using [TestCase], the argument TestName provides a name for the test.

If not specified, a name is generated based on the method name and the arguments provided.

You can control the order of test execution as given below:

[Test]
[TestCase("value1", TestName = "ExpressionTest_1")]
[TestCase("value2", TestName = "ExpressionTest_2")]
[TestCase("value3", TestName = "ExpressionTest_3")]
public void ExpressionTest(string  v)
{
    //do your stuff
}

Here I used the method name "ExpressionTest" suffix with a number.

You can use any names ordered alphabetical see TestCase Attribute

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
M.Hassan
  • 10,282
  • 5
  • 65
  • 84
2

Usually Unit Test should be independent, but if you must, then you can name your methods in alphabetical order ex:

[Test]
public void Add_Users(){}

[Test]
public void Add_UsersB(){}

[Test]
public void Process_Users(){}

or you can do..

        private void Add_Users(){}

        private void Add_UsersB(){}

        [Test]
        public void Process_Users()
        {
           Add_Users();
           Add_UsersB();
           // more code
        }
Sebastian Castaldi
  • 8,580
  • 3
  • 32
  • 24
  • 3
    Except now the names must be made alphabetical, which is an awful solutions. :( –  Feb 17 '13 at 08:11
  • @user166390 - not it is not awful. It works and depends on documented behaviour of NUnit. – tymtam Apr 10 '13 at 01:42
  • 1
    ➕1 good enough for me, much easier if you start your tests with `a_` `b_` `t1_`, `t2_` instead or relying on easy to miss trailing characters – Chris Marisic Sep 17 '15 at 22:44
1

I'm suprised the NUnit community hasn't come up with anything, so I went to create something like this myself.

I'm currently developing an open-source library that allows you to order your tests with NUnit. You can order test fixtures and ordering "ordered test specifications" alike.

The library offers the following features:

  • Build complex test ordering hierarchies
  • Skip subsequent tests if an test in order fails
  • Order your test methods by dependency instead of integer order
  • Supports usage side-by-side with unordered tests. Unordered tests are executed first.

The library is actually inspired in how MSTest does test ordering with .orderedtest files. Please look at an example below.

[OrderedTestFixture]
public sealed class MyOrderedTestFixture : TestOrderingSpecification {
    protected override void DefineTestOrdering() {
        TestFixture<Fixture1>();

        OrderedTestSpecification<MyOtherOrderedTestFixture>();

        TestFixture<Fixture2>();
        TestFixture<Fixture3>();
    }

    protected override bool ContinueOnError => false; // Or true, if you want to continue even if a child test fails
}
Sebazzz
  • 1,205
  • 2
  • 15
  • 33
0

You should not depend on the order in which the test framework picks tests for execution. Tests should be isolated and independent. In that they should not depend on some other test setting the stage for them or cleaning up after them. They should also produce the same result irrespective of the order of the execution of tests (for a given snapshot of the SUT)

I did a bit of googling. As usual, some people have resorted to sneaky tricks (instead of solving the underlying testability/design issue

  • naming the tests in an alphabetically ordered manner such that tests appear in the order they 'need' to be executed. However NUnit may choose to change this behavior with a later release and then your tests would be hosed. Better check in the current NUnit binaries to Source Control.
  • VS (IMHO encouraging the wrong behavior with their 'agile tools') has something called as "Ordered tests" in their MS testing framework. I didn't waste any time reading up but it seems to be targeted towards the same audience

See Also: characteristics of a good test

Community
  • 1
  • 1
Gishu
  • 134,492
  • 47
  • 225
  • 308
  • There are occasions where you'd like to have faster running tests execute before long running tests, specifically in integration and acceptance tests. For example, in a blogging app: you test the login first, because if that feature doesn't work, posting won't work either so there's no point in executing that test (you can stop the runner manually). But if you try to keep running tests, then it'll take more time. – Marcel Valdez Orozco Aug 26 '12 at 00:19
  • @MarcelValdezOrozco - you can achieve that goal by partitioning your tests either via different physical dll or by using tags/categories. You can create your build scripts to run dlls/categories in order. In general, allowing ordering of tests usually leads to coupled tests that develop dependencies on the neighbouring tests (over time of course). AFAIR in the next big release of NUnit, it's going to support different ordering of tests, e.g. random etc. – Gishu Aug 26 '12 at 04:05
  • 2
    Partitioning further the same type of tests (acceptance tests, for example) makes no sense, and separating them into another DLL unnecessarily increases complexity everywhere: source code, build scripts, test scripts, project structure, etc. Just to make a simple reordering of the tests. – Marcel Valdez Orozco Aug 26 '12 at 04:58
  • Emitting(so basically all mocking libs) are a reason why order would be important. You can't unload your app domain, and the nunit runner(if running all tests in an assembly) keeps that domain for all tests in at least that 'fixure'. If one test creates a types to test something, and another test conflicts with that created type, because of order, that's not a faulty test. They are isolated logically, it's just that nUnit doesn't provide proper isolation between each 'test' itself. – Kelly Elton Mar 15 '13 at 20:39
  • @kelton52 - IMHO it is a faulty test because it does not leave the field as it found it. You may have some constraints in 'your situation' but for the general case, the advice applies - tests should be isolated and thereby order agnostic. – Gishu Mar 16 '13 at 02:55
  • @Gishu Unfortunately there are some things you can't clean up. – Kelly Elton Mar 16 '13 at 03:00
  • 7
    This is quite a patronising answer and it makes it funny because it really only apply to unit tests and completely ignores being pragmatic. – tymtam Apr 10 '13 at 01:40
  • Nothing stops you from writing such tests - however it does create a lot of potential issues - e.g. hidden setup or cleanup (e.g. removing one test from the sequence messes up the rest). You can't speed up these test suites e.g. running each test on different machine. Dependency on current tool behavior which might change. In essence, it's just an amorphous blob composed of multiple (possibly intertwined) physical Nunit tests. Might as well compress it into one BIG test – Gishu Jan 08 '15 at 05:48
  • blah blah blah. should you follow this behavior as a standard practice? no, of course not. Are you really testing sequenced iteration where state matters and this makes your life much better? sure go ahead. – Chris Marisic Sep 17 '15 at 22:41
  • Unit testing by definition tests units. Each unit by definition is unitarian, atomic and independent of the rest. Sequential testing, integration testing or acceptance testing where this premise is not followed is not unit testing. The question is specifically talking about NUnit, a framework designed for _unit_ testing, and how to twist it into something it is not. So this reply is correct, not patronizing. To do what you want to do, you either need another framework or you have to build something on top of NUnit because NUnit is only for unit testing. – Isaac Llopis Feb 09 '16 at 08:52
0

In case of using TestCaseSource the key is to override string ToString method, How that works:

Assume you have TestCase class

public class TestCase
{
    public string Name { get; set; }
    public int Input { get; set; }
    public int Expected { get; set; }
}

And a list of TestCases:

private static IEnumerable<TestCase> TestSource()
{
    return new List<TestCase>
    {
        new TestCase()
        {
           Name = "Test 1",
           Input = 2,
           Expected = 4
        },
        new TestCase()
        {
            Name = "Test 2",
            Input = 4,
            Expected = 16
        },
        new TestCase()
        {
            Name = "Test 3",
            Input = 10,
            Expected = 100
        }
    };
}

Now lets use it with a Test method and see what happen:

[TestCaseSource(nameof(TestSource))]
public void MethodXTest(TestCase testCase)
{
    var x = Power(testCase.Input);
    x.ShouldBe(testCase.Expected);
}

This will not test in order and the output will be like this:

enter image description here

So if we added override string ToString to our class like:

public class TestCase
{
    public string Name { get; set; }
    public int Input { get; set; }
    public int Expected { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

The result will change and we get the order and name of test like:

enter image description here

Note:

  1. This is just example to illustrate how to get name and order in test, the order is taken numerically/alphabetically so if you have more than ten test I suggest making Test 01, Test 02.... Test 10, Test 11 etc because if you make Test 1 and at some point Test 10 than the order will be Test 1, Test 10, Test 2 .. etc.
  2. The input and Expected can be any type, string, object or custom class.
  3. Beside order, the good thing here is that you see the test name which is more important.
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137