Extract and override call

We will apply the already introduced refactoring technique extract and override call. For this, we create a failing specification, as shown here:

@Test 
public void add_one_book() throws IOException { 
    addBook(TDD_IN_JAVA); 
 
    Book tddInJava = new Book(TITLE_BOOK_1, 
      AUTHOR_BOOK_1, 
       States.fromValue(1)); 
 
    verify(booksRepository).add(tddInJava); 
} 

To pass this red specification, also known as a failing specificiation, we will first extract the dependency creation to a protected method in the BookRepository class:

@Path("books") 
@Component 
public class BooksEndpoint { 
 
    private BooksRepository books = 
      getBooksRepository(); 
 
    [...] 
 
     protected BooksRepository 
       getBooksRepository() { 
        return new BooksRepository(); 
    } 
 
    [...] 

We copy the MyApplication launcher to this:

public class TestApplication 
    extends ResourceConfig { 
 
    public TestApplication 
      (BooksEndpoint booksEndpoint) { 
        register(booksEndpoint); 
        register(RequestContextFilter.class); 
        register(JacksonJaxbJsonProvider.class); 
        register(CustomExceptionMapper.class); 
    } 
 
    public TestApplication() { 
        this(new BooksEndpoint( 
          new BooksRepository())); 
    } 
} 

This allows us to inject any BooksEndpoint. In this case, in the test BooksEndpointInteractionTest, we will override the dependency getter with a mock. In this way, we can check that the necessary calls are being made (fragment from BooksEndpointInteractionTest):

@Test 
public void add_one_book() throws IOException { 
    addBook(TDD_IN_JAVA); 
    verify(booksRepository) 
      .add(new Book(TITLE_BOOK_1, 
          AUTHOR_BOOK_1, 1)); 
} 

Run the tests; everything is green. Even though the specifications are successful, we have introduced a piece of design only for test purposes, and the production code is not executing this new launcher, TestApplication, but is still executing the old MyApplication. To solve this, we have to unify both launchers into one. This can be solved with the refactor parametrize constructor, also explained in Roy Osherove's book, The Art of Unit Testing (http://artofunittesting.com).

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

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