To show the principle, assume we have following classes (note the example is artificial - not real):
AbstractBuilder and TransactionBuilder
1:public abstract class AbstractBuilder {
2: protected Transaction createSimpleFromToTransaction(String from, String to) {
3: // something complex here
4: }
5:}
6:
7:public class TransactionBuilder extends AbstractBuilder {
8: // ... constructor
9: public Transaction buildTransaction() {
10: // i.e. some from and to computing
11: return createSimpleFromToTransaction(from, to);
12: }
13:
14:}
There is common method createSimpleFromToTransaction() implemented in AbstractBuilder. The implementation is quite complex and has a lot of dependencies. Let's assume this method is already well tested using huge mocking in another test. Now we would like to test TransactionBuilder.buildTransaction(), we know this method should use createSimpleFromToTransaction(), so to test it properly by regular way, we need to do that huge mocking (used in predecessor test) again - but in fact it is redundant, because the createSimpleFromToTransaction() is already tested.
That's the case we can do something like "mocking the predecessor". Let's see the code:
1:@Test
2:public void testBuild() {
3: final Transaction transaction = new Transaction();
4: TransactionBuilder underTest = new TransactionBuilder("ME", "THEM") {
5:
6: @Override
7: public Transaction createSimpleFromToTransaction(String from, String to) {
8: assertEquals("ME", from);
9: assertEquals("THEM", from);
10: return transaction;
11: }
12: };
13:
14: assertSame(transaction, underTest.buildTransaction());
15:}
As you can see, we are extending the tested class and overriding method of its predecessor. This allows us to avoid redundant testing of common method (already tested). In addition we can place some asserts into "mocked" method i.e. to check the parameters set.
Žádné komentáře:
Okomentovat