Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking lombok @Getter fields with Mockito

I am using @Getter notation with Lombok on some of my static fields as such:

public class A {

    @Getter protected static MyClass myClass;
}

While unit testing, I have to mock the value of these static fields for a section of code that does:

MyClass.getMyClass();

To mock, I'm doing:

mock(MyClass.class);
when(MyClass.getMyClass()).thenReturn(...);

However, such mock gives below error.

 [testng] org.mockito.exceptions.misusing.MissingMethodInvocationException:
 [testng] when() requires an argument which has to be 'a method call on a mock'.
 [testng] For example:
 [testng]     when(mock.getArticles()).thenReturn(articles);
 [testng]
 [testng] Also, this error might show up because:
 [testng] 1. you stub either of: final/private/equals()/hashCode() methods.
 [testng]    Those methods *cannot* be stubbed/verified.
 [testng]    Mocking methods declared on non-public parent classes is not supported.
 [testng] 2. inside when() you don't call method on mock but on some other object.

I must be hitting condition 2, but I'm not understanding how I am not "calling method on mock".

Has anyone successfully mocked Lombok getters?

Thanks!

like image 360
Jenna Kwon Avatar asked Nov 18 '25 11:11

Jenna Kwon


1 Answers

As I said in comment above, Mockito do not support mocking static methods.

Use Powermock

Example:

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class YourTestClass{
    PowerMockito.mockStatic(A.class);

    when(A.getMyClass()()).thenReturn(...);

}

Also,

MyClass.getMyClass();


getMyClass() belongs to class A or class Myclass ?
like image 147
VeKe Avatar answered Nov 21 '25 02:11

VeKe