views:

126

answers:

4

I'd like to know how do you test your methods if the libs you are using don't use Interfaces
My class is like

private ThirdParyClass thirdPartyClass;

void myMethod() { 
AnotherThirdPartyClass param = "abc";
...
thirdPartyClass.execute(param);
}

I want to test that execute is called with the "abc" param.

I was thinking in creating MyInterface with an implementation that wraps the ThirdPartyClass and then change the class attribute to refer MyInterface. Quite boring stuff but I don't see any other way to be able to successfully test my class.
If ThirdParyClass was an Interface I could mock it, but in this case how do you procede?

A: 

As long as the third party class you're using isn't final and you don't need to mock final methods you can use JMock and the ClassImposteriser to mock it and carry on as normal.

private Mockery context = new Mockery() {{
    setImposteriser(ClassImposteriser.INSTANCE);
}};

AnotherThirdPartyClass mockThirdParty = context.mock(AnotherThirdPartyClass.class);

Note you'll need to add some additional dependencies (jmock-legacy-2.5.1.jar, cglib-nodep-2.1_3.jar and objenesis-1.0.jar)

Rich Seller
+1  A: 

Hi, i do not know which mock implementation you use it. But EasyMock has an extension available at the EasyMock home page that generate mock Objects for classes. See your mock implementation whether it does not support mock Objects for classes.

regards,

Arthur Ronald F D Garcia
EasyMock 2.4 Class Extension, that's what I was looking for! Thank you very much :)
al nik
regards, I also use EasyMock and TestNG together. It is very powerful.
Arthur Ronald F D Garcia
A: 

Why not just use AspectJ (AOP) for the unit testing.

By using an around aspect you can then control what gets passed into the method and better monitor it.

If you need to have it extend an interface, you can modify the class through aspects to give it more functionality, such as turning logging on/off or getting performance information.

Then, when you are done, you remove the aspects before putting this into production by just not including the aspect class files in the build.

James Black
+1  A: 

You can use JMockit. It goes far beyond what is possible with EasyMock Class Extension or with jMock and its ClassImposteriser. You actually get all the power of AspectJ, but with a much easier to use, mocking-specific, API.

Rogerio