- Home /
How to unit test a MonoBehaviour which has RequireComponent attribute ?
using UnityEngine;
[RequireComponent(typeof(Rigidbody), typeof(Collider))]
public class ClassToTest : MonoBehaviour {
public bool TestFunction() { return false; }
}
using NUnit.Framework;
using UnityEngine;
namespace Tests.Editor
{
public class ClassTesterEditMode
{
private ClassToTest _classToTest;
public ClassTesterEditMode()
{
GameObject gameObject = new GameObject();
_classToTest = gameObject.AddComponent<ClassToTest>();
}
[Test]
public void TestOne()
{
Assert.False(_classToTest.TestFunction());
}
}
}
When I remove the RequireComponent attribute, I won't get System.NullReferenceException : Object reference not set to an instance
How can I keep the RequireComponent attribute and bypass the nullreference error?
(by the way, I know I haven't used good names, since I wanted to keep it simple and get the message across)
I really appreciate any help you can provide.
Answer by Hellium · Feb 06, 2021 at 11:06 PM
How can I keep the RequireComponent attribute and bypass the nullreference error?
Simply add the required components in the constructor of your ClassTesterEditMode
the same way you add ClassToTest
Your answer
![](https://koobas.hobune.stream/wayback/20220613024716im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to control MonoBehaviour lifecycle methods in test environment? 0 Answers
How to create custom attribute for auto injecting monobehaviour? 0 Answers
How to mock or skip execution of Awake in playmode unit tests? 2 Answers
Start() is called on Play and on Stop 1 Answer
Public variable containing script 2 Answers