Unit test with mock objects

Classes usually interact with a number of other collaborating classes. Mocking frameworks allow you to replace these collaborators in a controlled fashion so that you can isolate the class being tested.

Verifier does not include a built-in mocking library, but you are free to choose one that suits your purposes. However, to illustrate their utility we include a simple example that uses Mock4JS (for full documentation see the Mock4JS website).

The LocalizedValueUnavailableFormatter builds on other examples and uses the Caplin internationalisation library to translate the "unavailable" message into the locale of the currently logged in user.

novox.LocalizedValueUnavailableFormatter = function(){
  this.sMessage = ct.i18n("value.not.supplied");
};

caplin.implement(novox. LocalizedValueUnavailableFormatter, caplin.core.Formatter);

novox.LocalizedValueUnavailableFormatter.prototype.format = function(vValue) {
  if(vValue === null || vValue === undefined) {
    return this.sMessage;
  } else {
    return vValue;
  }
};

The  setUp() method uses Mock4JS to create a mock instance of the caplin.i18n.Translator class.  It is configured to return the value  "No Value Supplied" when called with the key "value.not.supplied".  This mock instance is used in the constructor of  the LocalizedValueUnavailableFormatter class.

LocalizedValueUnavailableFormatterTest = TestCase("LocalizedValueUnavailableFormatterTest");

LocalizedValueUnavailableFormatterTest.prototype.setUp = function() {
  var sMessageKey = "value.not.supplied";
  this.m_sMessageValue = "No value supplied";
  
  Mock4JS.addMockSupport(window);
  Mock4JS.clearMocksToVerify();
  var oMockTranslator = mock(caplin.i18n.Translator);
  oMockTranslator.stubs().i18n(sMessageKey).will(returnValue(this.m_sMessageValue));
  window.ct = oMockTranslator.proxy();
  this.m_oFormatter = new novox.ValueUnavailableFormatter();
};

LocalizedValueUnavailableFormatterTest.prototype.test_NullReturnsNotSuppliedMessage = function() {
  var sResult = this.m_oFormatter.format(null);
  assertEquals(this.m_sMessageValue, sResult);
};

LocalizedValueUnavailableFormatterTest.prototype.tearDown = function() {
  this.m_oFormatter = undefined;
};