Implementation

To better understand the specification we just wrote, let us do only a partial implementation. We'll create an empty method, saveMove. This will allow our code to compile without implementing the specification yet:

public void saveMove(TicTacToeBean bean) { 
} 

When we run our specifications (gradle test), the result is the following:

Wanted but not invoked: 
mongoCollection.save(Turn: 3; X: 2; Y: 1; Player: Y); 

Mockito tells us that, according to our specification, we expect the mongoCollection.save method to be invoked, and that the expectation was not fulfilled. Since the test is still failing, we need to go back and finish the implementation. One of the biggest sins in TDD is to have a failing test and move onto something else.

All tests should pass before a new test is written. The benefits of this are that the focus is maintained on a small unit of work, and implementation code is (almost) always in a working condition.

It is sometimes tempting to write multiple tests before the actual implementation. In other cases, developers ignore problems detected by the existing tests and move towards new features. This should be avoided whenever possible. In most cases, breaking this rule will only introduce technical debt that will need to be paid with interest. One of the goals of TDD is ensuring that the implementation code is (almost) always working as expected. Some projects, due to pressures to reach the delivery date or maintain the budget, break this rule and dedicate time to new features, leaving the fixing of the code associated with failed tests for later. Those projects usually end up postponing the inevitable.

Let's modify the implementation too, for example, the following:

public void saveMove(TicTacToeBean bean) { 
  getMongoCollection().save(null); 
} 

If we run our specifications again, the result is the following:

Argument(s) are different! Wanted: 
mongoCollection.save(Turn: 3; X: 2; Y: 1; Player: Y); 

This time we are invoking the expected method, but the arguments we are passing to it are not what we hoped for. In the specification, we set the expectation to a bean (new TicTacToeBean(3, 2, 1, 'Y')) and in the implementation, we passed null. Not only that, Mockito verifications can tell us whether a correct method was invoked, and also whether the arguments passed to that method are correct.

The correct implementation of the specification is the following:

public void saveMove(TicTacToeBean bean) { 
  getMongoCollection().save(bean); 
} 

This time all specifications should pass, and we can, happily, proceed to the next one.

..................Content has been hidden....................

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