Search Unity

  1. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Testing void function based on collider2D

Discussion in 'Testing & Automation' started by Darksaq, Jun 8, 2019.

  1. Darksaq


    Jun 8, 2019
    Hi there,

    I would like to do unit tests for my first game and I do not know how to go about the method below

    Code (CSharp):
    1.  public void attackInRange()
    2.     {
    3.         if (timeBtwAttack <= 0)
    4.         {
    6.             if (Input.GetKey(KeyCode.Space))
    7.             {
    8.                 Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPos.position, attackRange, whatIsEnemies);
    9.                 Debug.Log("Dmg enemies");
    10.                for (int i = 0; i < enemiesToDamage.Length; i++)
    11.                 {
    12.                     enemiesToDamage[i].GetComponent<Enemy>().TakeDamage(damage);
    13.                 }
    14.             }
    16.             timeBtwAttack = startTimeBtwAttack;
    17.         }
    18.         else
    19.         {
    20.             timeBtwAttack -= Time.deltaTime;
    21.         }
    22.     }
    I do not know how to simulate that there is an enemy in the player's collider.
    In this case, should I somehow mock this enemy and enter it manually in the array?
  2. Stormy102


    Jan 17, 2014
    From what I can see, you've got two options:
    1. Implement an Interface (let's call it IEnemy) and use that in your enemy script. You can GetComponent with this interface, which makes it more generic. Then, using either a mocking framework or a test script that implements it, you can use that to throw an SuccessException when it takes damage.
    2. Use the actual enemy script. Ideally, you don't want to do this, but you could if the logic isn't dependent on other components.