Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i mock static method whith juni5 and mockito or easymock?

I need to mock a static method with junit5 (that's is very important) and mockito or easymock. I saw that powermock works only with junit 4. there exists any form to do it with junit5?

like image 939
bbasstyle Avatar asked Oct 27 '22 14:10

bbasstyle


1 Answers

Mocking of static methods is not possible without PowerMock. And when you need PowerMock, it means that the code is not developed correctly, in the way it is testable. I am working on a project with Java 11, JUnit 5 and Mockito. PowerMock does not support this at all. And I doubt it will ever support it.

That being said: the only way to make it testable is to have the class-with-static-method injected into the class you need to test and then replace the implementation of the bean in the test-scope with a mock. When you inject it, you have a live object, so no need for a static method anymore.

It has benefits to change the code and use an injection framework (like Spring). I know there are situations you can't just do this. If you really can't change the implementation, just leave this for what it is and make a lot of unit tests to test the static method by itself with all kind of parameters. Just to make sure this class works as expected.

like image 131
Sven Avatar answered Nov 09 '22 06:11

Sven