Fixed UnitTest code and bugs found by unit tests