Sunday, 15 June 2014

java - PowerMock: Mocking static method that affect one test only -


My status:

I would like to add a new test. And I must have a static method X of the service class duplicate. Unfortunately the current tests are using this statutory method in any way.

And when I copy the X method using the powermock, the other test fails. What's more I do not want to touch other tests.

Is there a chance to just copy static methods for a test?

Sure, this is possible! At the same time when you could run into problems, if you are trying to test multiple threads at the same time ... I have put an example of how to do it below Enjoy it import org.junit.Test; Import org.junit.runner.RunWith; Import org.powermock.api.easymock.PowerMock; Import org.powermock.core.classloader.annotations.PrepareForTest; Import org.powermock.modules.junit4.PowerMockRunner; Static org.easymock import. EasyMock. *; Import static org.junit.Assert. *; @RunWith (PowerMockRunner.class) @PrepareForTest (Idgenerator.class) Public Class Test Class {@Test Public void yourTest () {ServiceRegistrator serTestObj = New ServiceRegistrator (); PowerMock.mockStatic (IdGenerator.class); . Hope (IdGenerator.generateNewId ()) andReturn (42L); PowerMock.replay (IdGenerator.class); Long real id = idGenerator.generateNewId (); PowerMock.verify (IdGenerator.class); AssertEquals (42L, actualId); } @Test Public Zero Undefined () {long real id = IdGenerator.generateNewId (); PowerMock.verify (IdGenerator.class); AssertEquals (3L, actualId); }}

test class

  public class idgenerator {public static long time generated (new) () {3L return; }}    

No comments:

Post a Comment