简体   繁体   中英

how to mock a method in an object when testing a method in the same object

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?

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
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM