问题
I have a helper class which contains an public static method getProductHandler(String name)
:
public class ProductHandlerManager {
public static Handler getProductHandler(String name) {
Handler handler = findProductHandler(name);
return handler;
}
}
A CustomerService
class uses the above ProductHandlerManager
:
public class CustomerService {
...
public void handleProduct() {
Handler appleHandler = ProductHandlerManager.getProductHandler("apple");
appleHandler.post(new Runnable() {
@Override
public void run() {
//...
}
});
}
}
I want to unit test handleProduct()
method in CustomerService
class. I tried using mockito to mock the ProductManager.getProductHandler("apple")
part in test, however, mockito doesn't support static method mocking. How can I use Mockito to unit test handleProduct()
function then?
Please don't suggest me to use Powermock, since I read some article which says if I need to mock static method, it indicates a bad design. But I can accept suggestions about code refactoring to make it testable.
回答1:
You can refactor and specify a Handler yourself. These can often be package private, if you put your tests in the same package as your classes-under-test—even if they're in a different source folder (e.g. src vs testsrc). Guava (Google Commons) has a handy @VisibleForTesting documentation annotation, too, though Javadoc tends to work as well.
public class CustomerService {
public void handleProduct() {
handle(ProductHandlerManager.getProductHandler("apple"));
}
/** Visible for testing. */
void handleProduct(Handler handler) {
handler.post(new Runnable() {
@Override
public void run() {
//...
}
});
}
}
At this point, you can test handleProduct(Handler)
intensively as a unit test, then only test handleProduct()
as an integration test to ensure the "apple" product handler interacts correctly.
来源:https://stackoverflow.com/questions/33610230/use-mockito-to-unit-test-a-function-which-contains-static-method-call-async-ta