Tuesday 20 June 2017

PowerMock, EasyMock : Mock static void method

In this post, I am going to show how to mock static void methods. Sometimes you don’t want to call void methods, while testing a function (which in turn calling this void method). By using ‘expectLastCall’ method of PowerMock class, you can mock static void methods.


Following snippet mock the void method readInputFromUI of the class Number for 5 times.

PowerMock.mockStaticPartial(Number.class, "readInputFromUI");

Number.readInputFromUI();
PowerMock.expectLastCall().times(5);

PowerMock.replayAll();

Find the following working application.

Number.java
package com.sample.tests;

import javax.swing.JOptionPane;

public class Number {

 public static void readInput(){
  readInputFromUI();
 }
 
 public static void readInputFromUI(){
  JOptionPane.showInputDialog("Enter a number");
 }
 
}


NumberTest.java
package com.sample.tests;

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;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Number.class })
public class NumberTest {

 @Test
 public void mockVoidEvenMethod() {

  PowerMock.mockStaticPartial(Number.class, "readInputFromUI");

  Number.readInputFromUI();
  PowerMock.expectLastCall().times(5);

  PowerMock.replayAll();

  for (int i = 0; i < 5; i++) {
   Number.readInput();
  }
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment