Warning: Super-techy post. If you’re interested in Unit Testing, especially in Monogame or any graphics programming, read on.
Last post I talked about what UIEntities are in Mech Retriever and how they help me have stuff appear on the screen. One issue I had when starting out making the code for Mech Retriever was how to test it. I searched to see if someone already had a way, but the ways I found were either over-complicated or inadequate. So I had to come up with my own way.
Luckily I have a lot of experience with the subject, and the answer lied in the Visitor pattern.
Put simply, when I want to render or load a UIEntity in MechRetriever, I could just call the functions the framework gives me to render or load textures, and pass in the information they need. The problem is that is very hard to test. So instead, I created the concept of a Renderer, which is a wrapper around the real rendering code, and pass that to the UIEntity’s Render function.
This is called the Visitor pattern. Put simply, you pass in a class that handles some process, like rendering, to the class that has the data to operate on, instead of passing the data into the class that knows how to do the process.
What this enabled me to do is to pass a TestRenderer, which doesn’t actually render anything, into the UIEntity, and then ask the TestRenderer if it would have rendered correctly. Basically, I can ask it if it would’ve given the right information to the Renderer. Or Loader. Or whatever. This pattern is called a Mock, which is an object that helps you test stuff by pretending to be something it’s not.
Why do it this way? Why not just render it normally and test the output? Because that would take the computer a long time and be freakishly complicated.
“But!” You may interject, “isn’t it complicated to reason about all the stuff you have to information you have to pass in, too?”
Yes and no. That will bring us to the next post, which will talk about EntityStateModels and TestHelper classes.