There's a method with several parameters that returns a String. In many conditions the method throws an exception. When it does return, the contents of the String are dependent on both the parameters and on the configuration of a certain USB dongle plugged into the computer. The length of the returned String is entirely dependent on the parameters though.
What I'm wondering is how to unit test this using Mockito (which I'm new to). One of the test methods should complete successfully when the returned String is of a certain length.
Let me know if you need more info.
Tomasz's Answer is perfectly fine if you want to stick with Hamcrest. Plus he used a method that describe what is the intention instead of inserting the anonymous class in your verification code. +1 for his answer :)
But there's an alternative with FESTAssert library and ArgumentCaptor
that could offer many more simple assertions without having to write one, and in a fluent way. When you have many assertions, it becomes kind of uneasy with Hamcrest. So here's what I'm using most of the time :
@RunWith(MockitoJUnitRunner.class)
public class MyTypeTest {
@Mock MyType myType;
@Captor ArgumentCaptor<String> stringCaptor;
@Test public void ensure_method_receive_String_that_has_32_chars() {
// given
...
// when
...
// then
verify(myType).method(stringCaptor.capture());
assertThat(stringCaptor.getValue()).isNotNull().hasSize(32);
}
Hope that helps.
Having such interface:
interface Foo {
void method(String s);
}
One idea is to use regular expression matching:
final Foo mock = mock(Foo.class);
mock.method("abc");
verify(mock).method(matches(".{3}"));
Unfortunately there is no built-in matcher for string length (there should be!), but it's easy to write custom one:
private static String hasSize(final int size) {
return argThat(new ArgumentMatcher<String>() {
@Override
public boolean matches(Object argument) {
return argument.toString().length() == size;
}
});
}
Now simply call static method:
verify(mock).method(hasSize(4));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With