Add unit tests for Command Gateway

And fix some bugs risen up in the process.