Search Unity

How to add conditions in Unity unit test hooks for test case

Discussion in 'Testing & Automation' started by TotalRequestLive, Feb 9, 2022.

  1. TotalRequestLive

    TotalRequestLive

    Joined:
    Aug 12, 2021
    Posts:
    1
    Similarly to how SpecFlow in web has tag features where one can add a @mytag to a scenario, then in hooks, say for example in the before scenario, I can do a check if scenario contains @mytag, do some specific code.

    Is there a way to have my hooks in unity be conditional depending on what unit test is running and do something before the scene starts?

    And example would be for a specific test, I want to delete this file before the test case starts, but only this test not others.

    Code (CSharp):
    1. [UnitySetUp]
    2. public IEnumerator UnitySetUp()
    3. {
    4.     //if scenario contains this tag, do this code
    5.     if(mytag)
    6.     {
    7.       do some code
    8.     }
    9.     yield return null;
    10. }
    11.  
     
  2. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,659
    The
    TestContext
    class will let you access information about the currently executing test. So for example, you could do this:

    Code (CSharp):
    1.  
    2.     [SetUp]
    3.     public void SetUp()
    4.     {
    5.         if ((string)TestContext.CurrentContext.Test.Properties.Get("tag") == "mytag")
    6.             Assert.Fail();
    7.     }
    8.  
    9.     [Test]
    10.     [NUnit.Framework.Property("tag", "mytag")]
    11.     public void TestWithTag()
    12.     {
    13.        
    14.     }
    15.  
    16.     [Test]
    17.     public void TestWithoutTag()
    18.     {
    19.        
    20.     }
     
    TotalRequestLive likes this.