Whenever I begin a new project, the first thing I think about is how I want to set up the architecture. Basically I am looking for the answer to this question: “How will all the stuff know about all the other stuff?”. In the past I usually resorted to a pattern called the Singleton to make it easy for data to be accessible from anywhere. In this case, I don’t want to rely on Singletons because I want my code to be testable, and from what I have read, the two don’t tend to go together well.

If you haven’t already grabbed a copy of the starter project, then go ahead and download a copy and open it. We will be building up on this as we go. I have also prepared an online repository here for those of you familiar with version control.

Aspect Container

For this project I was inspired by Unity’s GameObject to MonoBehaviour relationship. I really like how easy it is for a GameObject to get a reference to any component attached to it. I also like that any component can also get a reference to any other component on the same object since they also hold a connection to the GameObject that holds them. However, I am sure many of you are well aware of the many limitations associated with MonoBehaviour scripts, such as an inability to instantiate them on your own. For example, the code in the snippet below would compile and run, but Unity will compain at us:

public class Foo : MonoBehaviour { } public class Demo : MonoBehaviour { void Start () { var foo = new Foo (); } }

You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all

The Test Runner in Unity supports PlayMode testing, and so it could be used to test MonoBehaviour scripts. However, I think we will want to make a LOT of tests, and will want as much speed and control as possible. Ideally, all of our tests will operate under EditMode instead. Therefore, I will make the code independent of Unity architecture anywhere that I can.

The implementation for my solution was to make my own circular reference system similar to the GameObject pattern provided by Unity. In order to avoid confusion to myself and others, I felt it was important to come up with new names. The GameObject was implemented as an interface, “IContainer” and the Component was implemented as an interface “IAspect”. However, when used in a project even with just some of my own other scripts I found I had already run into a naming conflict. This is because I had also used an “IContainer” interface with my Scripts/Common/UI/TableView. So one thing you might notice that has changed in this new project is the use of namespaces. All of my code in the “Common” folder has been put into a unique namespace. That includes this new Aspect Container code, were I am using namespace TheLiquidFire.AspectContainer to help alleviate naming conflict issues.

Although the aspect container could be used just about anywhere, I only intend to use it as a means of allowing all of my systems to communicate between each other. This means I wont be worried about a container having more than one aspect of any given type. Because of this, I designed something that looks a bit like a dictionary (as opposed to a list), except that in this case, each “value” would know what it was collected by.

public interface IContainer { T AddAspect<T> (string key = null) where T : IAspect, new (); T AddAspect<T> (T aspect, string key = null) where T : IAspect; T GetAspect<T> (string key = null) where T : IAspect; ICollection<IAspect> Aspects (); } public interface IAspect { IContainer container { get; set; } }

I made each interface as simple as possible. The container needs a way to add an aspect, get an aspect that has been added to it, or get all of the aspects it currently holds. The aspect merely needs a property reference to the container that it is held by.

Note that in all of the methods for adding or getting an aspect from a container, that there is an optional parameter for the “key”. In each case, you can specify a custom string to use, or you can allow the implementing system to generate a key for you. The important detail is that if you “add” with a key, then you should be able to “get” with the same key. If you don’t “add” with a key, then you should be able to “get” without a key as well.

You may wonder why I added two methods for adding an aspect. The first will create an instance of the aspect for you. This is possible because of the added generic constraint: new() . The second option allows you to pass along a pre-existing aspect. This could be important for any scenario where it didn’t make sense to support a parameterless constructor, such as if you needed a MonoBehaviour to implement the IAspect interface. It also allows for a kind of dependency injection. For example, if you create all of your aspects according to an interface, then you can easily create an alternate or mock version to use later. That might look something like this:

public interface IFoo : IAspect { } public class Foo : IFoo { public IContainer container { get; set; } } public class Demo : MonoBehaviour { void Start () { var container = new Container (); container.AddAspect<IFoo> (new Foo ()); IFoo foo = container.GetAspect<IFoo> (); Debug.Log ("Got a foo? " + (foo != null).ToString()); } }

Test Driven Development

My own introduction to Test Driven Development (TDD) was kindly provided by this excellent tutorial. Note that this is for Xcode and uses Swift – which is perfect for what I do at work, but may not be as helpful for those of you who are only familiar with Unity and C#. So, I will give my own sort of intro to the idea as I understand it. TDD suggests a certain workflow whereby you begin your work by writing a test – not your actual code. We write this test first because we want to see the test fail. Then, when we add actual code which allows the test to pass, we can have confidence that it was the new code which caused the test to pass, and that it was not simply a poorly written test that might have passed anyway. Afterward we are free to tidy up the code and refactor as necessary. If the test can still pass after refactoring then we know we haven’t lost any expected functionality.

I haven’t ever done a project from scratch using this kind of workflow, and I am not sure I have the patience for it honestly, but a large part of that is because I am already an experienced programmer and I like to get in quick and “doodle” with my code for lack of a better term. Even still, I can see how this pattern would benefit even experienced programmers (myself included) – especially those who are working on large projects and/or with other people, so I want to try it out – maybe not perfectly strictly, but enough to get a good idea about it.

Container

Let’s get started by creating a “Container” class which implements our “IContainer” interface. Here is the least amount of code I can add – actually I let MonoDevelop write the code for me. Once I created the class definition, you can right-click on the name of the interface and choose Refactor -> Implement Interface which gives a result like the following:

public class Container : IContainer { public T AddAspect<T> (string key = null) where T : IAspect, new() { throw new System.NotImplementedException (); } public T AddAspect<T> (T aspect, string key = null) where T : IAspect { throw new System.NotImplementedException (); } public T GetAspect<T> (string key = null) where T : IAspect { throw new System.NotImplementedException (); } public ICollection<IAspect> Aspects () { throw new System.NotImplementedException (); } }

Now, we’re ready to write our first test for the new “Container” class. You can do this easily from the Project Pane inside of Unity. From the Create pulldown menu, choose Testing -> EditMode Test C# Script. I named mine, “AspectContainerTests” and the template looks like this:

public class AspectContainerTests { [Test] public void AspectContainerTestsSimplePasses() { // Use the Assert class to test conditions. } // A UnityTest behaves like a coroutine in PlayMode // and allows you to yield null to skip a frame in EditMode [UnityTest] public IEnumerator AspectContainerTestsWithEnumeratorPasses() { // Use the Assert class to test conditions. // yield to skip a frame yield return null; } }

Note that we use special tags above methods to make the TestRunner work. In this case, they have provided entries for two different kinds of tests, the first is marked with [Test] – this one will run and return immediately. Use assertions to validate “something” and when the assertion fails, your test will be marked as a failure too. The next test is similar to the first but is marked with [UnityTest] and as the comment suggests, it can skip frames to help simulate behavior like you might see in a PlayMode test.

There are several other tags you can mark your methods with, such as [SetUp] – which will be run immediately before each unit test, and [TearDown] – which will be run immediately following each unit test. I learned about these from the NUnit Documentation that Unity built its tools around. Of course you should probably also check out Unity’s TestRunner documentation which has screen grabs from the Unity interface and several suggested options you can try out.

For now let’s clear out all of the template test code and replace it with the following:

using UnityEngine; using UnityEditor; using UnityEngine.TestTools; using NUnit.Framework; using System.Collections; using TheLiquidFire.AspectContainer; public class AspectContainerTests { private class TestAspect : IAspect { public IContainer container { get; set; } } [Test] public void TestContainerCanAddAspect() { var container = new Container (); container.AddAspect<TestAspect> (); Assert.AreEqual (container.Aspects().Count, 1); } }

The Test Runner panel will update to dsiplay our tests as we create them. Currently they won’t be marked as either a pass or a fail. Now, using the TestRunner interface, begin an EditMode test by pressing the “Run All” button. The result will be that our test failed, but don’t worry – this is a good thing – it’s the first thing we want to see in a TDD workflow.

Now, we need to start adding code in order to allow the test to pass. Head back over to the “Container” class. If you follow the TDD pattern strictly, they suggest that you add the least amount of code possible in order to make a test pass – this is true even when you KNOW that the code is terrible. This is the part that really bugs me, but again, there is a method to the madness. The code will become better over time as you add more tests. In this case, I will need to be able to create an aspect, and add it to a collection so that I can return the populated collection in my test. For the first step, I will have my container implement a private Dictionary which can map between string key’s and an IAspect instance. Add the following field to the “Container” class:

Dictionary<string, IAspect> aspects = new Dictionary<string, IAspect> ();

Next, I will want to modify the “AddAspect” method so that it actually creates something and adds it to our collection:

public T AddAspect<T> (string key = null) where T : IAspect, new() { T aspect = new T (); aspects.Add (string.Empty, aspect); return aspect; }

Finally, we need to modify the “Aspects” method so that it returns the collection of aspects:

public ICollection<IAspect> Aspects () { return aspects.Values; }

Save and build your code. Then head back to Unity and run TestRunner again. This time, the test should pass. However, the code currently is pretty bad and wont work for a lot of scenarios. That’s ok. That’s what more tests are for. Let’s write a test to make sure that we can now add more than one aspect to a container. My expectation is that Aspects added to a container will either have unique keys, or unique types. In this case we will test via unique keys. Head back to the “AspectContainerTests” script and add the following:

[Test] public void TestContainerCanAddMultipleAspects() { var container = new Container (); container.AddAspect<TestAspect> ("Test1"); container.AddAspect<TestAspect> ("Test2"); Assert.AreEqual (container.Aspects().Count, 2); }

You can test it by choosing “Run All” again, but since we just ran the previous test and already know it works, we can be a little more efficient by selecting just the new test, and pressing “Run Selected” instead. The result will be a failure, and that failure will propagate up through the hierarchy to make sure you see that something failed.

Now we have to wonder at why our test worked for adding one aspect, but not for adding more than one. The reason is that I have the dictionary add the aspect using an empty string as its key. This was the “least” I could do to make the code run (because adding a null key would result in an System.ArgumentNullException – you can’t add null as a Dictionary key). Because we always use the same key, the Dictionary’s “Add” method will then throw an exception because the key already existed: System.ArgumentException : An element with the same key already exists in the dictionary.

In order to make the new test pass, we need to use a different “key” for each of the aspects which get added. My new test already provides a custom key to use for each aspect, therefore the simplest update to make is to pass along the value as the key for our Dictionary. Update the “Container” method as follows:

public T AddAspect<T> (string key = null) where T : IAspect, new() { T aspect = new T (); aspects.Add (key, aspect); return aspect; }

Save and Build your code, then let’s go ahead and perform a “Run All”. This time, our newest test succeeds, but our first test fails! I already hinted at the reason – you can’t add a null key, and in the first test we leave the optional parameter for the key at its default of null. Update the “Container” method by adding a check for a null key as follows:

public T AddAspect<T> (string key = null) where T : IAspect, new() { key = key ?? ""; T aspect = new T (); aspects.Add (key, aspect); return aspect; }

Let’s run our tests again. They all pass! But… the code still isn’t versatile enough. I mentioned before that my expectation was that aspects should either have unique keys or unique types, so let’s add a test for that too. Let’s add another test that adds different types of aspects – without passing a custom key. Add the following to your “AspectContainerTests” script:

private class AltTestAspect : IAspect { public IContainer container { get; set; } } [Test] public void TestContainerCanAddMultipleTypesOfAspects() { var container = new Container (); container.AddAspect<TestAspect> (); container.AddAspect<AltTestAspect> (); Assert.AreEqual (container.Aspects().Count, 2); }

Save and build, then run the new test. It too will fail. What this will point out is that merely checking for a null key and replacing it with an empty string is not sufficient. Each “Type” that can be passed along will need a unique key. We could force the “IAspect” interface to provide us a default key, but there is another option too. The name of the type is already unique and can be used as our fallback instead. Update our “Container” method’s null check to the following:

key = key ?? typeof(T).Name;

Save, build, and run our tests – they should all pass. However, adding an aspect isn’t very valuable without the ability to get the aspect again later. Let’s add two new tests: first to verify that an aspect added without a key can be obtained later without a key, and second to verify that an aspect added with a custom key can be obtained using that same key.

[Test] public void TestContainerCanGetAspectWithNoKey() { var container = new Container (); var original = container.AddAspect<TestAspect> (); var fetch = container.GetAspect<TestAspect> (); Assert.AreSame (original, fetch); } [Test] public void TestContainerCanGetAspectWithKey() { var container = new Container (); var original = container.AddAspect<TestAspect> ("Foo"); var fetch = container.GetAspect<TestAspect> ("Foo"); Assert.AreSame (original, fetch); }

These tests will both fail. At a minimum, we need to remove the NotImplementedException provided by the default code we generated. Remember, we want to write the least amount of code possible to make our tests pass. Let’s begin with the following attempt:

public T GetAspect<T> (string key = null) where T : IAspect { return aspects [key]; }

This will allow the test “with” a key to pass, but not the test without a key. This may remind us that we forgot to account for a null key. Add the following line to our “GetAspect” method just before the return statement:

key = key ?? typeof(T).Name;

It’s the same code we used to account for null keys when adding an aspect, so it makes sense that we would want to add it here. Run the tests again, and they should all pass.

Sometimes you may not think of all of the tests necessary to bullet-proof your code. If you are lucky, you may have a QA team to test your project. Let’s imagine a scenario where some unexpected order of operations causes code to try and “Get” an Aspect before it has been added to the container. Using a stack trace you identify the source of the problem as a “KeyNotFoundException” and can pinpoint it to your codes “GetAspect” method. Whoops. We will need to add another test:

[Test] public void TestContainerCanTryGetMissingAspect() { var container = new Container (); var fetch = container.GetAspect<TestAspect> ("Foo"); Assert.IsNull (fetch); }

Save, build and run the new test. This test fails AND triggers the same exception that our QA team had stumbled upon, and so it will be perfect to verify whether or not we have successfully fixed the bug. Head back over to the “Container” and update our method to the following version. This time we check to make sure that a key exists in the dictionary before we try to use it. Whenever the key is missing, we can return the default of the type we want – for a class it will be null.

public T GetAspect<T> (string key = null) where T : IAspect { key = key ?? typeof(T).Name; T aspect = aspects.ContainsKey (key) ? (T)aspects [key] : default (T); return aspect; }

Success! Our tests pass once again. Now we need to add something to test the final feature of our Container – the ability to add a pre-existing aspect. Add the following tests:

[Test] public void TestContainerCanAddPreCreatedAspect() { var container = new Container (); var aspect = new TestAspect (); container.AddAspect<TestAspect> (aspect); Assert.IsNotEmpty (container.Aspects()); } [Test] public void TestContainerCanGetPreCreatedAspect() { var container = new Container (); var original = new TestAspect (); container.AddAspect<TestAspect> (original); var fetch = container.GetAspect<TestAspect> (); Assert.AreSame(original, fetch); }

Running the tests now will fail, of course, because we still haven’t implemented anything and we throw the same NotImplementedException as before. Feel free to test that for yourself if you wish, otherwise, let’s make the simplest “change” we can by copying the implementation we used for the first version of AddAspect. Of course, a straight copy of the method body wont work because we would get an error: error CS0128: A local variable named `aspect’ is already defined in this scope, so we will need to delete the line where we create the new aspect. The end result should look like the following:

public T AddAspect<T> (T aspect, string key = null) where T : IAspect { key = key ?? typeof(T).Name; aspects.Add (key, aspect); return aspect; }

At this point, we have a fully validated class. We can proceed with a high level of confidence that our class will work as expected when we begin using it in our project! But… we aren’t done yet. There are three steps to properly practice TDD:

Write a failing test Write as little code as possible to make the test pass Polish your code

We have only performed the first two steps. The final step is to take another look over our code and see if there is anything we should do to improve on it. If so, we should make the changes, and then run the tests yet again to verify that we haven’t lost any of our expected functionality in the process. The first thing that jumps out to me is that code should be DRY (this stands for “Don’t repeat yourself”) yet that is exactly what we did to implement the second “AddAspect” method. We can clean this up by causing the first method to call the second, and then we will only need one version. That would look something like this:

public T AddAspect<T> (string key = null) where T : IAspect, new() { return AddAspect<T> (new T (), key); } public T AddAspect<T> (T aspect, string key = null) where T : IAspect { key = key ?? typeof(T).Name; aspects.Add (key, aspect); return aspect; }

Aspect

Just a little more and we will be done. First things first, we will need to provide a class which implements the IAspect interface:

public class Aspect : IAspect { public IContainer container { get; set; } }

Couldn’t be much simpler than that. Next, let’s write a test. We will want to make sure that an Aspect instance will know what it is contained by. Let’s add the following test (hopefully you will remember to verify on your own that it fails):

[Test] public void TestAspectTracksItsContainer() { var container = new Container (); var aspect = container.AddAspect<TestAspect> (); Assert.IsNotNull (aspect.container); }

Even though the aspect is created and is actually added to a collection, the reverse reference from an aspect to its container has not been configured anywhere. We can do this during the Container’s “AddAspect” method by assigning the reference before we return. Make sure to add this to the version which accepts both an aspect and a key as parameters so that it will work the same for either version.

public T AddAspect<T> (T aspect, string key = null) where T : IAspect { key = key ?? typeof(T).Name; aspects.Add (key, aspect); aspect.container = this; return aspect; }

Summary

Whew, this was a long lesson – and we didn’t even write a large or complex class! We did cover a lot though. In the beginning I discussed a new architectural design pattern that I wanted to implement in order to let my systems work together, but without the need of having a bunch of singletons. Next, we actually implemented the new class that would support the pattern, but did so via Test Driven Development, while learning all about Unity’s new Test Runner feature.

Hopefully you understand the process of implementing good unit tests, because I don’t plan on writing all of my future lessons with the same style of back and forth as I did here. My main concern is the time requirement – not just to write the code and tests in the first place, but to write the tutorial as well. I would love to hear your feedback on this though – was one TDD lesson enough or should I continue to write that way for a little longer? Note that either way I plan to include the test code which will likely serve as a demo so you know things are working – especially before we get around to adding “visible” content via Unity.

You can grab the project with this lesson fully implemented right here. If you are familiar with version control, you can also grab a copy of the project from my repository.

If you find value in my blog, you can support its continued development by becoming my patron. Visit my Patreon page here. Thanks!