kingbow (1) [Avatar] Offline
#1
Hi, Vincent,

How do you test the method which depends on the utility class like this?

public void method() {

// Business logic
....

// Use other utility class which consists of static methods
XXXUtil.do();

}


Thanks.
vmassol (51) [Avatar] Offline
#2
Re: Unit test problem?
Hi,

Do you mean you wish to unit test the method() method in isolation from the XXXUtil.do() one, i.e. replace the XXXUTil.do() by some mock value?

There are several refactoring possibilities as described in the book in chapter 12. The best solution is to refactor the code to not use static, possibly something like:

private static util = XXXUtil.do(); // This is step 1 to preserve compatiblity with existing calling classes

setXXXUtil(XXXUtil u)
{
util = u;
}

getXXXUtil() { return util; }

public void method()
{
[...]
getXXXUtil().do();
}

Another solution (less good but less intrusive):

public class A
{

public void method()
{
[...]
doSomeUtilStuff();
}

protected void doSomeUtilStuff()
{
return XXXUtil.do();
}

Then you create another class that extends A:

public class TestableA extends A
{
Object v;

public void setExpectedDoSomeUtilStuff(Object v)
{
value = v;
}

public void doSomeUtilStuff()
{
return value;
}
}

then you instantiate TestableA in your test.

The first option should be preferred as it is cleaner. It requires more refactoring though.

-Vincent