dushyantp
dushyantp

Reputation: 4720

Assert that a test failure is a success

In a nunit test, can we an assert that if the test fails at a certain circumstance then it is a pass (i.e. it is expected to try and fail).

But it should pass under all other circumstances.

Thing is that the test could fall apart before it can reach it's assertions sections.

I mean something in the lines of

[TestSetup]
void init()
{
    if (condition==true)
    {
    Assert.That(this test fails); /*any feature to do this?*/
    }
}

Upvotes: 3

Views: 10571

Answers (3)

Omzig
Omzig

Reputation: 921

You can also use the "Action" object to invoke the code in an action and test that action if it is an exception. Look at FluentAssertions they have lots of examples.

    int number1 = 1;
    int number0 = 0;
    Action someAction = () => { int j = number1 / number0; };
    someAction.ShouldThrow<DivideByZeroException>();

Upvotes: 0

Technetium
Technetium

Reputation: 6158

It's a little hard to understand your question. Are you wanting Assert.Fail() to force a failure? Like so...

[TestSetup]
public void Init()
{
    if (condition==true)
    {
    Assert.Fail();
    }
}

If instead you want to check for failure instead of cause one, you should follow Arran's advice and check for a specific fact about the work you're validating - such as a method's return value.

Upvotes: 0

Arran
Arran

Reputation: 25056

If the test can fail and it's classed as a pass under some circumstances, it sounds a bad test. Split it out into individual tests with clear method names detailing what it's achieving.

So instead of having one test and having a conditional inside it, split it out into each scenario. That way you can have the one scenario, where it is supposed to fail under something like

// do stuff
bool success = DoStuff();
Assert.IsFalse(success);

Upvotes: 3

Related Questions