Wednesday, July 20, 2016

Dependency Injection for Unity Statics


Back when I worked for InContext Solutions, one thing I was asked to do was make our Unity code fit into a SOLID framework.  But how do you get a system dependent on static method calls to support Dependency Injection and be testable?  Simple, you write a wrapper and interface for all the static methods you want to use.

But since that is a lot of work, and since these methods change between releases, I've written some code to automatically extract the interfaces and wrappers by finding all the static methods and properties.  It wrote most of the code for me, in fact it wrote two hundred and seventy files.   They weren't perfect, I had to fix about 60 minor bugs for special cases I hadn't programmed it to deal with.
But now I have a fully wrapped Unity asset available for free for anyone wanting to get to develop for DI frameworks like Zenject, or get some mocks made up so unit testing doesn't require unity up and running, but can be included as part of a Continuous Build environment via means of NUnit, MS Test or the like.

I've proved out part of it, but there is a lot of code here.  If anyone runs into issues with it, I appreciate the feed back and will complete this.

In-Component Unit Testing

I've also introduced what I think is an interesting concept.  Unit Tests directly associated with the component's Custom Inspectors.  The value, is that the test cases can then use the state as used directly in the game.  Including pausing a live game and triggering a unit test for an object at any given state (accept destruction for obvious reasons).

I think I'll turn that into a separate asset next, and enhance the appearance, as well as making it easier to work apply to any given behaviour.  The current code, as it was a proof for the interfaces and wrappers, is more just a hard coded grouping of test cases.  Plenty of room to improve.

Download the code here.  Full source included.  https://www.assetstore.unity3d.com/en/#!/content/66012

1 comment:

  1. Hello!
    I am a noob Unity Developer. This article is very well described on Dependency Injection for Unity Statics. Thanks for sharing.

    ReplyDelete