Herman,
> (1) Listing : The class under test
>
> class MyClass {
>
> // ----
> public void myMethod () {
> // .. Blah ...
> MyBackEndClass.callStaticMethod () ;
> // ^^^ i want to mock this object
> }
>
> }
>
> What i want to do is to create a mock object, say
> MockMyBackEndClass and call a method (static?) on it,
> thus avoiding actual call to backend. The problem is that
> i cannot override static method. So even if i subclass
> MyBackEndClass to create a MockMyBackEndClass,
> MockMyBackEndClass.callStaticMethod() will always call
> implementation in MyBackEndClass ...
> If the method callStaticMethod were not static, it's quite
> straightforward to substitute actual MyBackEndClass to
> MockMyBackEndClass in the test code... but it isn't ... :-(
I think you are out of luck. In this case, I would try to refactor
MyBackEndClass so I can call an instance method. I suspect MyBackendClass
implements some interface like MyBackendInterface, otherwise you wouldn't be
able to mock it. My approach would be to decouple the retrieval of the
back-end object from the method that uses this object. Something like this:
class MyClass {
// ----
public void myMethod () {
this.myMethod(BackendLookup.getBackendObject());
}
protected void myMethod(MyBackEndInterface backendObject) {
// .. Blah ...
backendObject.callInstanceMethod () ;
// .. More blah ...
}
}
You can then write unit tests for myMethod(MyBackEndInterface) providing the
mock version as an argument. I also assume that you write other unit tests
for the BackendLookup class.
Ringo
|