tom
tom

Reputation: 1223

How to force fail a test in C# with MSTest

I am trying to port some of my WebDriver tests from JAVA to C#. What I'm stuck on is the situation when the driver cannot find some element on the page, in JAVA I do :

if (second >= 10) fail("timeout - " + list);

so if something takes more than 10 seconds the test fails with the timeout message. I tried a similar approach in C# with

if (sec >= 10) Debug.Fail("timeout : " + vList);

but this actually did not fail the test, but gave me an option to do so with the exception message box. That was a no no, I need my automatic test to fail outright on its own. Then I tried

if (sec >= 10) Assert.Fail("timeout : " + vList);

but this is throwing an unhandled exception error. Should I enclose the Assert.Fail in try/catch block? Or should I use something completely different to fail the test?

I am using MSTest, as mentioned in the topic.

EDIT: The exact message is :

AssertFailedException was unhandled by user code. Assert.Fail failed. timeout : someField.

on

Assert.Fail("timeout : " + vList);

Upvotes: 2

Views: 12046

Answers (3)

tomfanning
tomfanning

Reputation: 9660

I think you're seeing that behaviour because you've got the debugger attached to the running test - Assert.Fail throws AssertFailedException, your debugger sees the exception and breaks - and you don't get test results.

On the Debug menu, go into Exceptions, find AssertFailedException (or create an entry for it if it's not there) and make sure break on throw is turned off for that exception type.

Alternatively, run your tests without the debugger attached.

Upvotes: 6

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

You must use appropriate syntax for mstest

[TestMethod]
public void IsSecondsGreaterOrEqualThanTen()
{
    Assert.IsTrue(second >= 10);
}

Upvotes: 0

Brett Veenstra
Brett Veenstra

Reputation: 48474

Assert.Fail should be what you want to "force" a failure. Internally, it will throw an AssertFailedException. Something else could be going on if this doesn't work...

a quick dotPeek shows this gets called:

internal static void HandleFail(string assertionName, string message, params object[] parameters)
{
  string str = string.Empty;
  if (!string.IsNullOrEmpty(message))
    str = parameters != null ? string.Format((IFormatProvider) CultureInfo.CurrentCulture, Assert.ReplaceNulls((object) message), parameters) : Assert.ReplaceNulls((object) message);
  if (Assert.AssertionFailure != null)
    Assert.AssertionFailure((object) null, EventArgs.Empty);
  throw new AssertFailedException(FrameworkMessages.AssertionFailed((object) assertionName, (object) str));
}

Upvotes: 1

Related Questions