5

i have such java codes:

public class A {
    public int get() {
        // many codes
        String s = new String();
        //...
        int n = 5;
        return isEmpty(s) ? n : -1;
    }
    public boolean isEmpty(String s) {
        return s.isEmpty();
    }
}

now i want to just test get(), i don't want to test isEmpty() at the same, so i want to mock isEmpty(), just test a method, if it invokes another method of the class, can easymock mock the method?

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
celix
  • 63
  • 2
  • To mock IsEmpty without get you are going to have to delegate the function to another class, and then inject that into A. Hope your real world example is less trivial than this.... – Tony Hopkinson Dec 03 '12 at 13:31

1 Answers1

3

A workable approach is to not mock A and do something like

public class TestableA extends A
{
    @Override
    public boolean isEmpty( String s )
    {
         // "mock" impl goes here, eg.:
         return s;
    }
}

and write your unit test in terms of TestableA instead. You can even create this in a @Before method:

public class UnitTest
{
    private A a; // note: A, not TestableA!

    @Before
    public void setUp()
    {
        this.a = new A() 
        {
            @Override
            public boolean isEmpty( String s )
            ...
        }
    }

    @Test
    ...
}
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55