I have been using the Unity Test Tools but I am having an issue where I am creating a gameObject in the test script, attaching a component that I want to test, but Awake is not being called. Is there any way to ensure Awake gets called when the component is added via my test script? I really don’t want to muddy up my component and add a public method that calls Awake or anything.
Thank you!
Unit testing are about testing things in isolation. Having a test rely on the fact that there are callbacks that should be called by the Unity engine makes the unit test complex and some would say that it is not a unit test at all.
You have a few options:
- Define the Awake() method as public, so it can be called from the outside.
- Define the Awake() method as internal, and use the InternalsVisibleToAttribute. This allows you to set a specific assembly that internals will be visible to. See this link for more info: InternalsVisibleTo. If your tests are defined in the editor assembly, allow internals to be visible to the editor assembly.
- Call Awake() using reflection (ugly!!)
Your better option would be to use the Unity Test Tools and create an Integration test. This allows you to create a real game object with a real component on it. The engine will run it as part of a test scene and will call the Awake() method on your component.
You would only need to define the passing criteria for this test (by calling Testing.Pass() for example when the test passes).
For more info on the Test Tools, check out this blog post: Introduction to Unity Test ToolsRandom Bits
As of Unity 5.5, you can have Awake()
run in an EditMode
unit test by setting the runInEditMode flag to true on your behaviour.