Skip to content

Instantly share code, notes, and snippets.

@tgoossens
Last active December 13, 2015 19:08
Show Gist options
  • Save tgoossens/4960368 to your computer and use it in GitHub Desktop.
Save tgoossens/4960368 to your computer and use it in GitHub Desktop.
A specialised method that creates a mock object. When a mock object's method is invoked information about its arguments is written a string (in bytes) to the outputstream
package meta.nxt;
public interface SampleInterface {
public void singleint (int a);
public void twiceint (int a, int b);
public void singledouble(double a);
}
package meta.nxt;
import static org.mockito.Mockito.mock;
import java.io.OutputStream;
import java.util.Arrays;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class StreamMock {
/**
* Will create a mock object. When one of the methods of this mock object is invoked, it will
* write information about this method to the given outputstream.
*
* @param clazz
* @param out
* @return
*/
static <T> T streammock(final Class<T> clazz, final OutputStream out) {
final T t = mock(clazz, new Answer<T>() {
@Override
public T answer(InvocationOnMock invocation) throws Throwable {
final String methodname = invocation.getMethod().getName();
final String str = new StringBuilder()
.append("mock: ")
.append(invocation.getMethod().getDeclaringClass().getCanonicalName())
.append(".")
.append(methodname)
.append(Arrays.asList(invocation.getArguments()))
.append(";")
.toString();
out.write(str.getBytes());
return null;
}
});
return t;
}
public static void main(String[] args) {
SampleInterface i = StreamMock.streammock(SampleInterface.class,
System.out);
i.twiceint(1, 2);
//prints:
//
// mock: meta.nxt.SampleInterface.twiceint[1, 2];
//
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment