Mock

The final type of fake object is a mock. The difference between a mock and a stub is where the verification is done. With a stub, our test must check if the state is correct after the act. With a mock object, the responsibility for testing the asserts falls to the mock itself. Mocks are another place where it is useful to leverage a mocking library. We can, however, build the same sort of thing, simply, ourselves:

class MockCredentialFactory {
  constructor() {
    this.timesCalled = 0;
  }
  Create() {
    this.timesCalled++;
  }
  Verify() {
    assert(this.timesCalled == 3);
  }
}

This mockCredentialsFactory class takes on the responsibility of verifying the correct functions were called. This is a very simple sort of approach to mocking and can be used as such:

var credentialFactory = new MockCredentialFactory();
var knight = new Knight(credentialFactory);
var credentials = knight.presentCredentials("Lord Snow");
credentials = knight.presentCredentials("Queen Cersei");
credentials = knight.presentCredentials("Lord Stark");
credentialFactory.Verify();

This is a static mock that keeps the same behavior every time it is used. It is possible to build mocks that act as recording devices. You can instruct the mock object to expect certain behaviors and then have it automatically play them back.

The syntax for this is taken from the documentation for the mocking library; Sinon. It looks like the following:

var mock = sinon.mock(myAPI);
mock.expects("method").once().throws();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset