- Home /
Is there a way to ensure Awake is called in Unit tests?
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!
You could make Awake a public method as well. Otherwise you could also use reflection:
$$anonymous$$ethodInfo method = scriptToTest.GetType().Get$$anonymous$$ethod("Awake", BindingFlags.NonPublic | BindingFlags.Instance);
method.Invoke(this, new object[] { });
Or something to this effect, I forget the exact syntax, but google can help you there.
Answer by liortal · May 20, 2014 at 08:44 PM
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: http://wp.me/p4kypp-6s
Thanks for the answer. I understand the isolation aspect of unit tests in theory, but in practicality pure isolation is almost impossible. This is especially true in Unity, given that most Unity objects are not mockable.
Answer by Dissolute · May 01, 2018 at 07:35 PM
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.
I'm using this approach in my edit mode unit tests, but finding that Start is not being invoked on my runInEdit$$anonymous$$ode component UNLESS I have the Rider debugger attached, which is quite baffling. Anyone else seen this..?