Search code examples
c#seleniumselenium-webdrivermstestassert

which approach is good to for assert


First Approach : Using try-catch block as well as Asset.Fail too.

I am using this technique to print few messages in loggers before and after execution starts

[TestMethod]
public void abcButton()
    {
want to print messages so many Logger signs are here

                Utility.Logger.Write("** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is started  *****");
    Utility.Logger.Write("***********************");
    try
    {
        Assert.IsTrue(LoginPage.CheckBtn());
        Utility.Logger.Write("********************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Passed  *****");
        Utility.Logger.Write("******************************************************");
    }
    catch
    {
        Utility.Logger.Write("*************************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Failed  *****");
        Utility.Logger.Write("*********************");
        Assert.Fail();
    }

}

OR Second Approach : Using if-else condition, involved one more extra var I just want to see if there is a short approach can get from experts

[TestMethod]

public void abcButton()
{

    Utility.Logger.Write("** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is started  *****");
    Utility.Logger.Write("***********************");
    var val = LoginPage.CheckBtn() ;
    if(val)){
        Assert.IsTrue(val);
        Utility.Logger.Write("********************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Passed  *****");
        Utility.Logger.Write("**************************************");
    }
    else
    {
        Utility.Logger.Write("*************************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Failed  *****");
        Utility.Logger.Write("*********************");
    }
}

Please let me know if we can handle such scenario in less code


Solution

  • I would write the tests like this:

    [TestMethod]
    public void abcButtonTest()
    {
        Assert.IsTrue(LoginPage.CheckBtn(), "Checking return value");
    }
    

    Basic example:

    [TestMethod]
    public void TestMethod1()
    {
        Assert.IsTrue(false, "Assert failed");
    }
    

    enter image description here