tags:

views:

24

answers:

3

I have a method that invokes other method in the same class such as:

Class MyClass{
   public int methodA(){
      ...
      methodB()
      ...
   }

   public int methodB(){
      ...
   }
}

And I just wanna test methodA(), so how can I isolate methodB() using EasyMock. My damn way is to create a fake instance of MyClass and inject it into the methodA() like this:

public int methodA(MyClass fake){
   ...
   fake.methodB();
   ...
}

and expect it in my testcase:

MyClass fake = EasyMock.createMock(MyClass.class);    
EasyMock.expect(fake.methodB()).andReturn(...);

Is there any better solution for this situation?

+2  A: 

Yes: Don't use EasyMock but an anonymous local class. Example:

public void testXyz throws Exception() {
    MyClass fake = new MyClass() {
        public int methodB(){
            return 12;
        }
    };

    fake.methodA();
}
Aaron Digulla
that's what I've expected!
Truong Ha
A: 

I think you should consider refactoring MyClass.
If the both methods use the same logic in methodB() then extracting the logic to a private method will enable you to test for the isolated scenario of calling each of these methods.

Bivas
A: 

well...it is so simple :-)

YourClass instance = mock(YourClass.class);

when(instance.methodB(args)).thenReturn(aFakeAnswer);
when(instance.methodA(args)).thenCallRealMethod();

I'm sorry for not exact code but in general it does it work like that and you can unit test abstract classes as well using this.

Vitek