Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Should I mock this?

Discussion in 'Scripting' started by turbosheep, Feb 11, 2016.

  1. turbosheep

    turbosheep

    Joined:
    Jul 19, 2013
    Posts:
    25
    So, I'm attempting TDD in a small try-out project...
    I have written a test for a Player's Shoot() method, and now I want to test whether the bullet has a certain speed upon its creation:

    Code (CSharp):
    1. using Assets.Scripts;
    2. using NUnit.Framework;
    3.  
    4. namespace TDDShootingGame.Tests
    5. {
    6.     [TestFixture]
    7.     class BulletTests
    8.     {
    9.         private BulletPoolManager bulletPoolManager;
    10.         private Player player;
    11.  
    12.         [SetUp]
    13.         public void SetUp()
    14.         {
    15.             bulletPoolManager = new BulletPoolManager();
    16.             player = new Player(bulletPoolManager);
    17.         }
    18.  
    19.         [Test]
    20.         public void SetSpeed_UponBulletCreation_BulletSpeedEquals1()
    21.         {
    22.             //Arrange... not necessary
    23.  
    24.             //Act
    25.             player.Shoot();
    26.  
    27.             //Assert that the fired bullet has a specific speed
    28.             Assert.AreEqual(1, bulletPoolManager.BulletList[0].Speed); //Accessing a Bullet object, which relies UnityEngine... mock it?
    29.         }
    30.     }
    31. }
    However, this gives me an 'Ecall methods should be package into a system module' error in Nunit.
    This is because the Bullet object, accessed in "bulletPoolManager.BulletList[0]", relies on the UnityEngine in order to instantiate a Bullet prefab in the game scene:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. namespace Assets.Scripts
    4. {
    5.     public class Bullet
    6.     {
    7.         private float speed;
    8.         public float Speed
    9.         {
    10.             get
    11.             {
    12.                 return speed;
    13.             }
    14.         }
    15.  
    16.         public Bullet()
    17.         {
    18.             Object.Instantiate(Resources.Load("Prefabs/Bullet"), Vector3.zero, Quaternion.identity);
    19.         }
    20.  
    21.         private void SetSpeed(float value)
    22.         {
    23.             speed = value;
    24.         }
    25.     }
    26. }
    27.  
    I thought the only way to test the Bullet's speed was to mock Bullet.
    A fake Bullet that does the exact same thing, except Instantiate the prefab.
    Is this the right approach, or are there major design issues here?
    If anyone could educate me, I'd be grateful. :)