jenkinsjenkins-pipelinejenkins-pipeline-unit

JenkinsPipelineUnit mock RunWrapper for shared library


I've written Jenkins shared library with helpers contained code like

def foo() {
    ...
    return steps.build(job: jobName, wait: true, propagate: true, parameters: parameters)
}

class RunConfig implements Serializable {
    ...
    RunWrapper runWrapper
}

and I want to write unit tests for them.

It requires RunWrapper mocking. And it is a problem, because RunWrapper is declared as:

public RunWrapper(Run<?,?> build, boolean currentBuild) {
    this.externalizableId = build.getExternalizableId();
    ...

so I have to create instance of hudson.model.Run to avoid NPE.

I don't find way to get some "dummy" Run. But call constructor of it is also hard way (sources) because it need in Job instance.

Last point which I reached it is implementing class MockJob extends Job, class MockItemGroup<T extends Item> implements ItemGroup and runtime NPE from hudson.model.Job.saveNextBuildNumber where Job tries to create "nextBuildNumber" file in job root dir (mocked class returns null as root dir).

Maybe I am missing something and there is another way to test RunWrapper?


Solution

  • You can use any avaliable mocking framework (for example mockito). And then create a mock of RunWrapper

    import org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper
    import static org.mockito.Mockito.*; 
    //.. 
    RunWrapper runWrapperMock = mock(RunWrapper.class);