Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Unit Testing a MonoBehaviour in Unity

Discussion in 'Testing & Automation' started by knightcube, Apr 24, 2020.

  1. knightcube

    knightcube

    Joined:
    Oct 16, 2018
    Posts:
    15
    Hi. I am learning how to do Unit Testing in Unity and got stuck here.

    I have a MonoBehaviour class -

    Code (CSharp):
    1.  public class ShowResults : MonoBehaviour
    2.     {
    3.         [SerializeField]
    4.         private TextMeshProUGUI resultTxt;
    5.  
    6.         public void UpdateResultText(string result)
    7.         {
    8.             resultTxt.text = result;
    9.         }
    10.     }

    And I have a corresponding Test class -

    Code (CSharp):
    1. public class ShowResultsTest
    2.     {
    3.         [Test]
    4.         public void ResultStringShouldBeValid()
    5.         {
    6.  
    7.         }
    8.     }
    I am having difficulty in writing the Arrange and the Act part for this specific example. How do I access the "result" variable from that MonoBehaviour so that I can check whether it is null or not?
     
  2. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,649
    If your test is an EditorTest, then one option would be to use the SerializedObject API to serialize your MonoBehaviour and check the field that way.

    However, this sort of thing is one of the classic cases where you should consider adjusting your code to 'make it testable.' For example, you could add a read-only property to the ShowResults class which returns the resultTxt field (or even resultTxt.text if you want). This property could be public, or - if you want to avoid the API being public - you could make it internal, and use the InternalsVisibleTo attribute to make the API accessible to code in your tests assembly.
     
    liortal likes this.