I have a Unity (version 2020.2.1f1) project and I've factored out a small utility in C# which I'd like to unit test. Currently in order to compile, the utility class needs to extend MonoBehaviour, but I'd like to avoid this and keep the class pure C#.
I've looked for documentation on unit testing in Unity, but can only find the Unity Test Framework which seems to be geared to game code rather than pure C#. Is there a way to unit test vanilla C# code in Unity?
The following article mentions nothing about a testcase having to include Unity-specific code https://www.raywenderlich.com/9454-introduction-to-unity-unit-testing
Unity IS C# after all. Not everything in your project has to use the Unity API
Why does it need to implement MonoBehaviour?
I would suggest you have e.g.
public class YourClass
{
...
}
and where/if at all needed you wrap it in a
public class YourClassBehaviour : MonoBehaviour
{
public YourClass yourClassInstance;
}
And then only test the internal functionality of the YourClass.
Either way: It doesn't need to be anything Unity specific in order to unit test it.
You can just go ahead and e.g. do
namespace YourThingy.EditorTests
{
public class YourClassTest
{
private YourClass yourClassInstance;
[OneTimeSetup]
public void Setup()
{
yourClassInstance = new YourClass();
}
[Test]
public void SomeTest()
{
yourClassInstance.DoSomething();
Assert.AreEuqual("someValue", yourClassInstance.someValue);
}
[Test]
public void SoemTestThatIsntEvenUsingYourClass()
{
Assert.IsTrue(1f == (2f * 5f / 10f));
}
}
}
As you can see the Unit test are pure c# and don't necessarily use anything from the Unity API (except of course the test framework itself)
In order to not have to enter play mode just make sure you are using Editor Tests.