Search code examples
testingexceptionseleniumnunitautomated-tests

Throw an exception or Assert.Fail if prerequisite to tests are not met


I have a few NUnit tests that run Selenium.

There are some prerequisite to some tests. An example for this would be logging in to our website.

We use a standard test user for test A, but if that user doesn't exist for whatever reason, we'll get a test failure with nothing useful (Selenium will just report it couldn't find the element at line 50). So I planned to check for the user's existence before we try to run the test - in the TextFixtureSetUp method.

I have a check to ensure the user exists, and if not, throw a helpful error message. For example:

    [TestFixtureSetUp]
    public void SetUp()
    {
        bool userExists = userManager.GetUserByEmailAddress("someuser@fish.com") != null;
        if (!userExists)
        {
            throw new Exception("Test user someuser@fish.com doesn't exist.");
        }
    }

vs

    [TestFixtureSetUp]
    public void SetUp()
    {
        bool userExists = userManager.GetUserByEmailAddress("someuser@fish.com") != null;
        if (!userExists)
        {
            Assert.Fail("Test user someuser@fish.com doesn't exist.");
        }
    }

My question is this a good idea? Should I throw an exception or use Assert.Fail()? Am I thinking about this in the wrong way, or is it something doesn't matter really.


Solution

  • Reason to throw exception - you can catch it later on and try to use another user.

    Reason to fail asserrt - when user is not found, it means end to the testmodel.

    If you go the exception way - think about GetUserByEmailAddress will be throwing it if it does not find the right user...