Showing posts with label powermock. Show all posts
Showing posts with label powermock. Show all posts

Tuesday, 12 July 2011

PowerMock static method replace

I learned something new PowerMock today. Of course I only had to since I did not read the API properly...

So the situation is where you are using a PowerMock to mock a static method from a class. Let's have an example.

I have a class called ProductDAO which has a getInstance() method. And this method is creating a new instance using some database resources which you don't wanna do in your unit test. What you can do is you replace that method with a 'clone' in your unit test class.


replace(method(ProductDAO.class, "getInstance"))
         .with(method(MyTest.class, "getMockInstance"));

And of course you've added: @PrepareForTest(MyTest.class)

Ok. So now when you do the replace? Possibly in a setUp() method annotated with @Before. Which of course mean it will be done for each and every test (performance...).

What i wanted to do is to replace it an a setUpClass annotated with a @BeforeClass. Grr. Wrong.

You can't do that. Here i learned this is not working:
http://stackoverflow.com/questions/4874992/mocking-both-static-and-dynamic-methods-with-powermock

The replace is only working in a dynamic context.

Happy coding!