Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write mockito matcher for byte[]?

I need a complex Matcher for byte[]. The code below does not compile since argThat returns Byte[]. Is there a way to write a dedicated Matcher for an array of primitive types?

    verify(communicator).post(Matchers.argThat(new ArgumentMatcher<Byte[]>() {

        @Override
        public boolean matches(Object argument) {
            // do complex investigation of byte array
            return false;
        }
    }));
like image 633
BetaRide Avatar asked Nov 18 '14 11:11

BetaRide


People also ask

What is matcher in Mockito?

What are Matchers? Matchers are like regex or wildcards where instead of a specific input (and or output), you specify a range/type of input/output based on which stubs/spies can be rest and calls to stubs can be verified. All the Mockito matchers are a part of 'Mockito' static class.

What is EQ Mockito?

Mockito Argument Matcher - eq() When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method.

Can the Mockito Matcher methods be used as return values?

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo. class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.


1 Answers

You really can use new ArgumentMatcher<byte[]> { ... } here:

verify(communicator).post(Matchers.argThat(new ArgumentMatcher<byte[]>() {
    @Override
    public boolean matches(Object argument) {
        // do complex investigation of byte array
        return false;
    }
}));

The answers you are referring to say that byte[] is not a valid substitute for T[] (because T[] assumes Object[], which byte[] is not), but in your case there is no T[] involved, and byte[], being a subclass of Object, is a valid substitute for simple T.

like image 69
axtavt Avatar answered Oct 07 '22 09:10

axtavt