EasyMock and testing Protected Methods

懵懂的女人 提交于 2019-12-02 10:27:15

问题


Trying to use EasyMock to test if a protected method gets called, not sure if this is the best way to do it ... but given the below, how can I tell that didIgetCalled() actually was called when callMe() was called?

public Class testMe(){
    public int callMe(){
        if(true){
            didIgetCalled();
        }
        return 1;
    }
    protected int didIgetCalled(){
        return 2;
    }
}

回答1:


This is a way you can test the method without using EasyMock, however my recommendation is that: If it's not public, don't write a test for it

Method method = testMe.class.getDeclaredMethod("didIgetCalled", new Class[]{});
method.setAccessible(true);
testMe testClass = new testMe();
int invoke = (Integer) method.invoke(testClass);
assertEquals(2,invoke);

I know that this will not entirely solve your problem but it's a start :)




回答2:


How about this:

You could keep the same package name for your test class as that of the class under test. That way if your class under test say MyClass.java is in src directory with package name com.abc.mypackage then you your test class say MyClassTest.java could be in test directory with same package name. See image below:



来源:https://stackoverflow.com/questions/9122339/easymock-and-testing-protected-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!