Stubbing a method that takes Class<T> as parameter with Mockito

74,446

Solution 1

The problem is, you cannot mix argument matchers and real arguments in a mocked call. So, rather do this:

when(serviceValidatorStub.validate(
    any(),
    isA(UserCommentRequestValidator.class),
    eq(UserCommentResponse.class),
    eq(UserCommentError.class))
).thenReturn(new UserCommentResponse());

Notice the use of the eq() argument matcher for matching equality.

see: https://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/Matchers.html#eq(T)

Also, you could use the same() argument matcher for Class<?> types - this matches same identity, like the == Java operator.

Solution 2

Just in order to complete on the same thread, if someone want to stubb a method that takes a Class as argument, but don't care of the type, or need many type to be stubbed the same way, here is another solution:

private class AnyClassMatcher extends ArgumentMatcher<Class<?>> {

    @Override
    public boolean matches(final Object argument) {
        // We always return true, because we want to acknowledge all class types
        return true;
    }

}

private Class<?> anyClass() {
    return Mockito.argThat(new AnyClassMatcher());
}

and then call

Mockito.when(mock.doIt(this.anyClass())).thenCallRealMethod();

Solution 3

Nice one @Ash. I used your generic class matcher to prepare below. This can be used if we want to prepare mock of a specific Type.(not instance)

private Class<StreamSource> streamSourceClass() {
    return Mockito.argThat(new ArgumentMatcher<Class<StreamSource>>() {

        @Override
        public boolean matches(Object argument) {
            // TODO Auto-generated method stub
            return false;
        }
    });
}

Usage:

    Mockito.when(restTemplate.getForObject(Mockito.anyString(), 
            **streamSourceClass(),**
            Mockito.anyObject));
Share:
74,446
Peter Perháč
Author by

Peter Perháč

Currently am on a contract, building APIs for the Valuation Office Agency, transforming the way agents interact with the VOA. Coursera certificate - Functional Programming Principles in Scala Coursera certificate - Functional Program Design in Scala Oracle Certified Associate, Java SE 7 Programmer Oracle Certified Professional, Java SE 7 Programmer II Oracle Certified Expert, Java EE6 Web Component Developer github.com/PeterPerhac July 2018 update: Books currently on my desk: (see my goodreads for up-to-date info) Functional and Reactive Domain Modeling Practical Vim, 2nd Edition (Great) books I parked (for now): Reactive Messaging Patterns with the Actor Model: Applications and Integration in Scala and Akka Functional Programming in Scala Learn You a Haskell for Great Good A Practical Guide to Ubuntu Linux Domain-Driven Design: Tackling Complexity in the Heart of Software Plan to look into: Play framework Linux administration Dale Carnegie books (various) Read cover-to-cover: Advanced Scala with Cats Clean Code Release It! - Design and Deploy Production-Ready Software The Phonix Project Spring in Action (3rd edition) Pragmatic Scala - Create Expressive, Concise, and Scalable Applications UML distilled, 2nd edition Pro C# 2010 and the .NET 4 Platform The Art of Unit Testing: With Examples in C# Read selectively: The Well-Grounded Java Developer - Vital Techniques of Java 7 and polyglot programming Switch - how to change things when change is hard Practical Unit Testing with JUnit and Mockito Effective Java, second edition Java Concurrency in Practice Nationality: Slovak

Updated on June 28, 2020

Comments

  • Peter Perháč
    Peter Perháč almost 4 years

    There is a generic method that takes a class as parameter and I have problems stubbing it with Mockito. The method looks like this:

    public <U extends Enum<U> & Error, T extends ServiceResponse<U>> T validate(
        Object target, Validator validator, Class<T> responseClass,
        Class<U> errorEnum);
    

    It's god awful, at least to me... I could imagine living without it, but the rest of the code base happily uses it...

    I was going to, in my unit test, stub this method to return a new empty object. But how do I do this with mockito? I tried:

    when(serviceValidatorStub.validate(
        any(), 
        isA(UserCommentRequestValidator.class), 
        UserCommentResponse.class, 
        UserCommentError.class)
    ).thenReturn(new UserCommentResponse());
    

    but since I am mixing and matching matchers and raw values, I get "org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!"