How can I use PowerMockito to ensure Jenkins static method returns my mocked object?
I see that if I have a test, that Jenkins is the mock. However, if I add what looks like a valid PowerMockito.when for an additional static method, I get the error below. I'm stumped.
error
groovy.lang.MissingMethodException: No signature of method:
static jenkins.model.Jenkins.getItemByFullName() is applicable for argument types:
(java.lang.String) values: [job]
Possible solutions:
getItemByFullName(java.lang.String),
getItemByFullName(java.lang.String, java.lang.Class)
code
@RunWith(PowerMockRunner.class)
@PrepareForTest([Jenkins.class, Job.class])
class MyTest {
def thisScript
@Mock
private Jenkins jenkins
@Mock Job job
MyClass myClass
@Before
void setUp() {
PowerMockito.mockStatic(Jenkins.class)
PowerMockito.when(Jenkins.getInstance()).thenReturn(jenkins)
PowerMockito.when(Jenkins.getItemByFullName("job".toString())).thenReturn(job)
}
A major oops on my part. The getInstance method is static, getItemByFullName is not static. So, here's the fix
@RunWith(PowerMockRunner.class)
@PrepareForTest([Jenkins.class, Job.class])
class MyTest {
def thisScript
@Mock
private Jenkins jenkinsInstance
@Mock Job job
MyClass myClass
@Before
void setUp() {
PowerMockito.mockStatic(Jenkins.class)
PowerMockito.when(Jenkins.getInstance()).thenReturn(jenkins)
PowerMockito.when(jenkinsInstance.getItemByFullName("job".toString())).thenReturn(job)
}
I must mock the instance's method jenkinsInstance.getItemByFullName
and not the Jenkins.class
class's static method.