带有PowerMock和Jenkins的groovy.lang.MissingMethodException getItemByFullName

时间:2019-04-18 22:11:16

标签: mockito jenkins-pipeline powermockito jenkins-shared-libraries

如何使用PowerMockito确保Jenkins静态方法返回我的模拟对象?

我看到,如果我进行测试,那么詹金斯就是模拟对象。但是,如果我添加了看起来像有效的PowerMockito.when作为其他静态方法,则会收到以下错误。我很困惑。

错误

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)

代码

@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)

    }

1 个答案:

答案 0 :(得分:0)

我的主要任务。 getInstance方法是静态的,getItemByFullName不是静态的。所以,这是解决方法


@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)

    }

我必须模拟实例的方法jenkinsInstance.getItemByFullName,而不是Jenkins.class类的静态方法。