I have a component I want to unit test. I wrote two unit tests, they get run and fail. Debugging them seems to show that adding the component to a game object does not trigger the component’s Start() method (where the logic I’m testing is). How do I test my Start() method (making Start() public and calling it manually is not an option)?
This is my component:
public class CameraAspectRatioLockScr : MonoBehaviour
{
public Camera ParentCamera { get; private set; }
void Start ()
{
this.ParentCamera = this.gameObject.GetComponentInParent<Camera>();
if (this.ParentCamera == null)
{
throw new MissingComponentException("CameraAspectRatioLockScr failed to find a Camera component in its parent.");
}
}
}
These are my unit tests
namespace UnityTest
{
[TestFixture]
public class CameraAspectRatioLockTests
{
private GameObject SetUpCamera()
{
var parentCamera = new GameObject();
parentCamera.AddComponent<Camera>();
return parentCamera;
}
[Test]
public void ComponentFindsParentCamera()
{
var parentCamera = this.SetUpCamera();
var subject = parentCamera.AddComponent<CameraAspectRatioLockScr>();
Assert.IsNotNull(subject.ParentCamera);
}
[Test]
public void ComponentThrowsExceptionWhenParentCameraNotFound()
{
var parentObject = new GameObject();
Assert.Throws<MissingComponentException> (()=>parentObject.AddComponent<CameraAspectRatioLockScr>());
}
}
}