19 October 2021 by jr101dallas
⇠ Back to PostsHookup
We’ve got our Entity, and our Component. Now to hook them together. We’re going to use a Dictionary of IComponents on Entity to do it. I’m not worrying yet about the guts of IComponent yet, I’ve just looked ahead at my plan and I know that this interface is going to be what I pass around and generically examine in my Systems so my Dictionary needs to have that as the type to make things simple.
More Code
Let’s update our EntityTests.cs first. I could just add another Assert to the test I already have, but I like to specifically name tests for what they do and have very small amounts of work in them so that when a test fails, the failed test name points me really tightly into the place in the code where the problem is. It’s true that a lot of the good tools will give you lots more information than the name of the failing test, but we’re purposely putting in a little extra time in order to always save time in the future when things are much more complex. I’ll start by copying my existing test and then mangle it.
[TestMethod]
public void DefaultEntityHasIdZero()
{
var entity = new Entity();
Assert.AreEqual(entity.Id, 0);
}
…becomes…
[TestMethod]
public void DefaultEntityHasZeroComponents()
{
var entity = new Entity();
Assert.AreEqual(1, entity.components.Count());
}
Red Squiggly! Right, create the dictionary on Entity…
public Dictionary<string, IComponent> components;
Red Squiggly on Dictionary, right, we need a using…
using System.Collections.Generic;
Looking at the test again, I notice I still have a red squiggly, this time only on .Count()
but the explaination is easy, the intellisense tells me that .Count
is what I really want because it’s a property, not a method. No more red squigglies, let’s save all the files and run the tests.
dotnet test
No compile errors, good. Four tests now, good. And, the new one failed, good. Why? Because the components property is null on a new instance.
X DefaultEntityHasZeroComponents [71ms]
Error Message:
Test method physics_test.EntityTests.DefaultEntityHasZeroComponents threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
Stack Trace:
at physics_test.EntityTests.DefaultEntityHasZeroComponents() in D:\source\repos\roguelike-tutorial\physics-test\EntityTests.cs:line 20
Test Run Failed.
Total tests: 4
Passed: 3
Failed: 1
Total time: 2.0888 Seconds
PS D:\source\repos\roguelike-tutorial>
Awesome, hook that up, save files, run tests, failure one last time, this time actually the failure I’ve been expecting.
Assert.AreEqual failed. Expected:<1>. Actual:<0>.
Change the test to the actual real expected count and save files, run tests one more time and we’re finished with a passing test scenario where we can check the git status, add files, commit and push.
tags: ecs - component - entity - code - dictionary