How to mock/stub a collaborator's getter and make it return a stub

(Jan W.) #1


I’m writing a test with Gradle and wonder how to stub an interface that is a collaborator’s collaborator (from my class under test (CUT) point-of-view).

project.logger would return an instance of the interface org.gradle.api.Project.Logger, and logger is the getter I’d need to mock.

Any ideas how to create a Logger without implementing the Logger interface and make my cut instance return it?
I guess I’m missing something as I’m quite new to mock testing.


The TestCase:

import org.gradle.api.Project

class MyClassUnderTestTestCase{
    void testDoSomething(){
        StubFor projectStub = new StubFor(Project)
        projectStub.demand.getLogger { } // create a Logger stub here?
        projectStub.use {
            def project = { } as Project
            MyClassUnderTest cut = new MyClassUnderTest(project)
            //Further assertions


import org.gradle.api.Project

class MyClassUnderTest{
    private Project project
    MyClassUnderTest(Project project){
        this.project = project

    void doSomething(){ "Start doing something..."    // project.logger should now return a stubbed instance of Logger
        //Do some stuff