Fork me on GitHub jcabi

23-Oct-2013 0.11.2

"Mock" Profile for Building of a "-mock.jar" artifact

Profile mock is activated automatically when there is a src/mock/java directory in the project. The profile adds this directory to the list of test directories and compiles and packages its content into a JAR with a mock classifier. Only classes that named as *Mocker.java or *Mocker$*.java are included into the JAR.

This mechanism is very helpful when you develop an API that contains interfaces that have to be mocked in other modules or projects. For example, these are the interfaces from your public API in module example-api:

package com.example;
public interface Document {
  String content();
}
public interface Printer {
  void print(Document doc);
}

Class Printer expects an instance of Document as a single parameter of method print(). In another module, say, example-printer you want to implement a Printer and to mock a Document in order to test it:

import org.junit.Test;
import org.mockito.Mockito;
public PrinterTest {
  @Test
  public void testPrinting() {
    Printer printer = new PrinterImpl();
    Document doc = Mockito.mock(Document.class);
    Mockito.doReturn("some test content").when(document).content();
    printer.print(doc);
    Mockito.verify(doc).content();
  }
}

A more convenient way to do it is to ship a mocker together with an interface:

public DocumentMocker {
  private Document doc = Mockito.mock(Document.class);
  public DocumentMocker withContent(String text) {
    Mockito.doReturn(text).when(this.doc).content();
    return this;
  }
  public Document mock() {
    return this.doc;
  }
}

This mocker will be used as following:

import org.junit.Test;
public PrinterTest {
  @Test
  public void testPrinting() {
    Printer printer = new PrinterImpl();
    Document doc = new DocumentMocker()
      .withContent("some test content")
      .mock();
    printer.print(doc);
    Mockito.verify(doc).content();
  }
}

For complex interfaces such mockers may become a very convenient tool.

Place the mocker into src/mock/java/com/example/DocumentMocker.java file and it will be compiled and packaged into example-api-1.0-SNAPSHOT-mock.jar artifact. Later, in order to add this artifact to the example-core module use this dependency definition:

<dependency>
  <groupId>com.example</groupId>
  <artifactId>example-api</artifactId>
  <version>1.0-SNAPSHOT</version>
  <classifier>mock</classifier> <!-- this is the trick -->
  <scope>test</scope>
</dependency>

Copyright © 2012-2013 jcabi.com, All Rights Reserved. Privacy Policy.

site is built by Apache Maven