dimanche 25 septembre 2016

Using Groovy StubFor on private fields in Java Classes

Lately I've been playing around with Groovy for testing legacy Java code. I wanted to see how it deals with mocking private fields (yes, I know it should be refactored to DI).

I seem to be getting different results when I use StubFor and .use on Groovy classes vs Java classes. Specifically, the stubbing seems to be working on Groovy classes but not Java.

In a Groovy test file I have:

import com.somejava.SomeDependency
import com.somejava.TestStuff

import groovy.mock.interceptor.StubFor
import org.junit.Test

class FooTest {
    @Test
    public void fooTest() {
        def stub = new StubFor(SomeDependency)
        stub.demand.somePred() { true }

        stub.use {
            def foo = new TestStuff()
            foo.doStuff()     // this does not throw expected ex
        }

        def groovyStub = new StubFor(GroovySomeDependency)
        groovyStub.demand.somePred() { true }

        groovyStub.use {
           def groovyFoo = new GroovyTestStuff()
           groovyFoo.doStuff()    // this does throw expected ex
        }
    }
}

public class GroovyTestStuff {

    public GroovyTestStuff(){}

    public void doStuff(){
        GroovySomeDependency dep = new GroovySomeDependency()
        if(dep.somePred()){
            println("OH NO EXCEPTIONS")
            throw new RuntimeException()
        }else{
            println("WE GOOD")
        }
    }
}

public class GroovySomeDependency {

    public GroovySomeDependency() {}

    public boolean somePred(){
        return false
    }
}

In a separate java package I have the following two classes:

package com.somejava;

public class TestStuff {

    public TestStuff(){}

    public void doStuff(){
        SomeDependency dep = new SomeDependency();
        if(dep.somePred()){
            System.out.println("OH NO EXCEPTIONS");
            throw new RuntimeException();
        }else{
            System.out.println("WE GOOD");
        }
    }
}

package com.somejava;

public class SomeDependency {

    public SomeDependency() {}

    public boolean somePred(){
        return false;
    }
}

Results in:

WE GOOD
OH NO EXCEPTIONS

java.lang.RuntimeException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ...

If not PEBKAC, is there some difference in Groovy stubs/mocks of Groovy classes vs Java classes?

Aucun commentaire:

Enregistrer un commentaire