Search Unity

Unit testing collision

Discussion in 'Testing & Automation' started by Erenquin, Jan 8, 2020.

  1. Erenquin


    Apr 9, 2018
    As the title implies, I'd like to unit test collision.

    I do not catch "OnCollisionEnter" in the game script (understand: no variable is set or modified like in a case of "attackDamage").
    I just want to ensure that the collision occurs (that, for example, I do not disable or remove the collider component on one object).

    I searched google but can't find a solution.
    I only found this 3 years old post that says it is not possible:

    So, is it still impossible ? And if it is possible, can someone guide me how to ?

    While writing this I found out the "Rigidbody.SweepTest" API. Could I use an "Assert true SweepTest" ?
    This would not truly test OnCollisionEnter but may do the trick.

    Just made a trial with "Sweep test" and it seems working.
    If I disable the collider the test fails and if I enable it it passes.

    Last edited: Jan 8, 2020
  2. Green-Moon-Moon


    Apr 29, 2016
    Not a solution but just a tip:
    I've recently ran into that exact issue. I tried to find some obscure dynamic c# mojo to try to make it work until I realised that I don't actually need to test the collision of my object only how my script responded to it.
    1. Does the collision you're trying to test affect the object state?
    a. If it does, you might want to expose that state and test it directly.

    2. Create Test scene with scenarios that can reproduce a Use case for the physics engine. You might not test the collision directly but you can use other markers to make you assertions like trigger or collider with special response script.

    Ultimately you don't really need to test that the physics engine works like it supposed too but how your script respond to its input. I often fall into these rabbit holes where I end up testing part of APIs and eventually ended up searching for exactly that, ended up on this post.