0

I have a mock object which expects that a method on it is called. How do I make sure that the string argument it expects begins with particular prefix?

oneOf(mockObject).methodName(with(any(String.class));
Debajit
  • 46,327
  • 33
  • 91
  • 100

2 Answers2

1

In the case of JMockit, it provides the desired matcher out-of-the-box:

new Expectations() {{
    mockObject.methodName(withPrefix("PREFIX"));
}};
Rogério
  • 16,171
  • 2
  • 50
  • 63
0

I would use a custom matcher. It turns out, the example on the jmock site on how to write a custom matcher covers writing one to match on prefixes. I won't copy the code here, but the link is http://www.jmock.org/custom-matchers.html

Alternatively, a lazier approach would be to just check if the string contains the particular prefix anywhere in the string. You can do that with the existing 'stringContaining' matcher.

oneOf(mockObject).methodName(with(stringContaining("PREFIX"));

Whether that's acceptable in your unit test though would depend on the string, the prefix, and what you're testing.

AndyN
  • 2,075
  • 16
  • 25