简体   繁体   中英

Power Mock unit tests for Static methods of local scope

Is there a good way to use power mockito for mocking the static method shown below in the code?

@Singleton
public class AnimalWorks {

    public void verifyAnimal(Protocol proto, Set<Animal> successAnimals, Set<AnimalRule> rules, String zookeeper,OtherParams additionalParams) throws AnimalException, DAOException {
        ...

        // Static method call to fromAnimalId(arg1,arg2) below:
        // How to mock this method call with PowerMockito so I can have a custom aniSet?

        Set<Animal> aniSet = AnimalGenerator.fromAnimalId(dbtool, additionalParams); 

        ...

    }

} 

Mocking static methods using PowerMock is explained here for example.

But please keep in mind: when talking about your own production code, then this is only the second best solution! Because: that static call is actually a design problem.

Yes, static methods are convenient, but they also lead to direct/tight coupling of your code. And of course, they break ordinary unit testing with EasyMock or Mockito ...

So, the alternative answer is: don't use PowerMock. Instead step back, and remove that static dependency from your code. For example by creating an interface that denotes the required functionality; and then instead of making that static call within your code, you use dependency injection to acquire some object implementing that interface.

And all of a sudden, you don't need PowerMock any more.

Final word of warning: many people use PowerMock without much problems. But when you do some research, you will also find a lot of people having all kinds of weird problems with PowerMock. So, don't just pick that tool because it seems more convenient. Understand that improving your design completely kills the need for using that tool!

EDIT:

The point is: you should never do things because somebody says "make it so". Ideally, you learn about pros and cons of the different approaches, and then you decide which way to turn; depending on that analysis. Of course, static was available in Java since the very first day; thus there are many people showing nice use cases for it.

But that doesn't change the downsides I mentioned (direct, tight coupling). Thing is: I completely stopped using statics - in ways that prevent from unit testing. And I never regretted that.

And you see, there are people that claim that static prevents you from creating testable code - like here (watching those videos is worth each minute!). It is not like I came up with that idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM