- Home /
How to mock or skip execution of Awake in playmode unit tests?
I am trying to make my game testable, and i've separated as much logic as i could from MonoBehaviours:
At the editor level, i have the RabbitMonoBehaviour, that get's serialized input from editor and creates Rabbit (pure C# class) from that in it's Awake. The Rabbit is exposed as a public readonly property.
This way, i can mock all the dependencies of Rabbit class, but... Turns out i need to test the collisions, and for that i need to work with RabbitMonoBehaviour in my test. I managed to use reflection to insert my rabbit instance with all dependencies mocked into my monobehaviour, but the problem is - no matter what i do, the Awake executes and tries to create a rabbit with 5 real-code objects! I can overwrite it then with my mocked instance, but the creation code crashes or requires me to create the production versions of all the 5 dependencies of Rabbit class...
Can i somehow skip the execution of Awake in Unity? Or maybe use reflection to override the Awake method for the whole class?
You want to skip Awake() entirely on every script? Or are you saying you want to skip Awake() on just one class?
one one class, and only in the test assembly, during test run. But any info on ability to skip awake is welcomed
Answer by TheSmokingGnu · Jun 10, 2018 at 08:16 PM
The best thing i came up with:
Create a mock subclass of the monobehaviour and define an empty Awake() method. Then initialize needed members using reflection.
I am fairly happy with it. Remember, my monobehaviour-to-be-tested was used purely to delegate editor serialized data to my pure C# classes (which were being tested). So this way i eliminated the editor init part altogether, and provided my own mocks through reflection.
The strange reflectionish-way in which unity calls the monobehaviour messages, which made it impossible to mock them in the first place made this workaround usable
Answer by SlowCircuit · Jun 10, 2018 at 09:54 AM
You may be able to accomplish what you want with pre-processor directives.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/
https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
That would be super tedious, and would require to change production code.
Your answer
Follow this Question
Related Questions
Can we create playmode tests outside of the main build assembly? 0 Answers
Is there a method on MonoBehaviour that is called on load even if GameObject is disabled? 3 Answers
Awake not called if class has static member 2 Answers
How to unit test a MonoBehaviour which has RequireComponent attribute ? 1 Answer
Unit Testing Rigidbody2D without polluting scene with gameobjects 1 Answer