logo
down
shadow

PowerMock static method mocking isn't taken into account for each @InjectMocks invocation


PowerMock static method mocking isn't taken into account for each @InjectMocks invocation

Content Index :

PowerMock static method mocking isn't taken into account for each @InjectMocks invocation
Tag : java , By : DK.
Date : December 01 2020, 04:47 PM

around this issue As explained in (Mocking behaviour resets after each test with PowerMock) Powermock resets the mocks before each test.
For some reason it works the first time - there exists an unresolved bug report for that issue (https://github.com/powermock/powermock/issues/398).
private SomeClass attribute;
private SomeOtherClass testClass;

@Before
public void setUp() {
    PowerMockito.mockStatic(StaticClass.class);
    Mockito.when(StaticClass.staticMethod(anyString())).thenReturn(new SomeConcreteClass());

    attribute = Mockito.mock(SomeClass.class);      
    testClass = new SomeOtherClass();

    // assign mock manually
    testClass.attribute = attribute;
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Mocking a static final method using PowerMock


Tag : unit-testing , By : WuJanJai
Date : March 29 2020, 07:55 AM
I hope this helps . I have class with all the methods static and final. How do I mock a method which is both static and final in the class.
final UtilityClass util = PowerMockito.mock(UtilityClass.class);
PowerMockito.mockStatic(UtilityClass.class);

Powermock - mocking a super method invocation


Tag : java , By : besn
Date : March 29 2020, 07:55 AM
I wish this help you It seems that jMockit can do what I need. Maybe I will I post this question to the powermock mailing list. Meanwhile below should suffice. package learning_mocking_tools.learning_mocking_tools; package learning_mocking_tools.learning_mocking_tools;
import mockit.*;

import org.junit.Assert;
import org.junit.Test;


class BaseService {
    public int save() {
        validate();
        return 2;
    }

    public static int save2() {
        return 5;
    }

    public void validate() {
        System.out.println("base service save executing...");
    }
}

class ChildService extends BaseService {
    public int save() {
        System.out.println("child service save executing...");
        int x = super.save2();
        int y = super.save();
        System.out.println("super.save returned " + y);
        load();
        return 1 + y;
    }

    public void load() {
        System.out.println("child service load executing...");
    }
}

@MockClass(realClass = BaseService.class)
class MockBase {

    @Mock
    public int save() {
        System.out.println("mocked base");
        return 9;
    }
}

public class PreventSuperInvocation {

    @Test
    public void testSave() throws Exception {
        MockBase mockBase = new MockBase();
        Mockit.setUpMock(BaseService.class, mockBase);

        ChildService childService = new ChildService();
//      int x = childService.save();

        Assert.assertEquals(9 + 1, childService.save());

        Mockit.tearDownMocks();
    }

}

Mocking a Static Method without replayAll() in PowerMock


Tag : java , By : Tim
Date : March 29 2020, 07:55 AM
I wish this help you You can do do this by using the PowerMock.replay([object_name]) so that you don't have to do the replay all. For this example it would look like the following:
public class Dice {
   public int sumOfNumDieRolls (int num) { 
      int sum = 0;
      for (int i=0;   i<num;   ++i) {
         int roll = (int) (6. * Math.random()) + 1;
         sum += roll;
      }
      return sum;
   }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest( {Dice.class} )
public class DiceTest {
   @Test
   public void shouldAddUpDieRollsCorrectly() {
      PowerMock.mockStaticPartial(Math.class, "random");
      EasyMock.expect (Math.random()).andReturn(0.3334).anyTimes();
      Dice die = new Dice();
      PowerMock.replay(Math.class);
      assertEquals (12, die.sumOfNumDieRolls(4));
      assertEquals (30, die.sumOfNumDieRolls(10));
      PowerMock.verify(Math.class);
   }
}

PowerMock: Mocking static method that affect one test only


Tag : java , By : Andrew L.
Date : March 29 2020, 07:55 AM
wish of those help Sure, it is possible! The only time when you could run into problems is if you are trying to test multiple threads at the same time... I put an example of how to do it below. Enjoy.
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;

import static org.easymock.EasyMock.*;

import static org.junit.Assert.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest(IdGenerator.class)
public class TestClass {

    @Test
    public void yourTest()
    {
        ServiceRegistrator serTestObj = new ServiceRegistrator();

        PowerMock.mockStatic(IdGenerator.class);
        expect(IdGenerator.generateNewId()).andReturn(42L);
        PowerMock.replay(IdGenerator.class);
        long actualId = IdGenerator.generateNewId();

        PowerMock.verify(IdGenerator.class);
        assertEquals(42L,actualId);
     }

    @Test
    public void unaffectedTest() {
        long actualId = IdGenerator.generateNewId();

        PowerMock.verify(IdGenerator.class);
        assertEquals(3L,actualId);
    }
}
public class IdGenerator {
     public static long generateNewId()
      {
        return 3L;
      }
}

PowerMock issue when mocking a static method with Java7 construct


Tag : development , By : mtnmuncher
Date : March 29 2020, 07:55 AM
With these it helps That is the thing with PowerMock - welcome to its bizarre errors.
First question would be - are you using an IBM JDK? Because IBM JDK and PowerMock go even more "bizarre" than Oracle/OpenJDK and PowerMock.
Related Posts Related QUESTIONS :
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • Unable to instantiate default tuplizer Exception
  • Multi-tenant migration to work with quarkus
  • Ignite persisting a Set: Cannot find metadata for object with compact footer
  • Maven cannot resolve Jacob dependency using eclipse
  • testcontainers oracle database container starts before database user is created
  • Launching two spring boot apps in integration test
  • Is there a way to add a HashMap's value that is a integer array into a ArrayList?
  • Is there any way that I can get a parameter in paintComponent?
  • Empty stack with one recursive method and one iterative method
  • What's the behavior of onBackpressureBuffer in RxJava2
  • Java regex can only use 1 quantifier in a lookback (need 2)
  • How to fix error in native query : it is showing syntax error near or at
  • How to retrieve nested object from a document and display it in FirestoreRecyclerOptions?
  • Why not use ListIterator for full LinkedList Operation?
  • Android Webview EvaluateJavascript sometimes does not return a response
  • Matcher java doesn't work but regex seems to be good
  • Finding dimensions of a .gif file
  • Java Number format how to change +/- sign to custom text
  • Entity partially saved when using JOINED inheritance strategy and setting spring.jpa.properties.hibernate.jdbc.batch_siz
  • Stored Procedure in Java Spring Boot Project returns null as Output
  • How to solve org.hibernate.MappingException which is causing due to inheriting a class
  • Clean Archtecture. Understanding of scheme
  • Processing 3 triangle not showing in Javafx 8 Window tab
  • How to specify a sequence-based generated value in Hibernate 5 via legacy mapping
  • Spring-boot application not getting auto-deployed on startup
  • How to only pass strings that the user select
  • Is there a way to SELECT using "GREATEST(field1, field2)" where field1 and field2 are aggregate sums in the sa
  • How to handle JSON objects wrapped into one JSON object with retrofit2?
  • Configure Hazelcast CPSubsystem Retries Timeout
  • how to use onBindViewHolder with multiple items in android RecyclerView
  • No ParameterResolver registered for parameter in BeforeAll method
  • Finding the path in a graph with the least casualties according to the lanchester square law
  • MongoWriteException when inserting into Mongodb with composite custom _id
  • Fetch Oracle procedure metadata with Java when multiple procedure signatures
  • Value modification of key-pair in HashMap and impact for a HashCode
  • Migration from solrj to spring-data-solr
  • How to check if you're still connected to the database with jpa
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com