Wednesday 21 June 2017

PowerMock, EasyMock: Mock static void parameterized method

In my previous post, I explained how to mock a static void method. In this post, I am going to explain how to mock static void parameterized method.

InputUtil.java
package com.sample.tests;

import javax.swing.JOptionPane;

public class InputUtil {

 public static void readInput(String message){
  readInputFromUI(message.toUpperCase());
 }
 
 public static void readInputFromUI(String message){
  JOptionPane.showInputDialog(message);
 }
 
}

Suppose, I want to test whether readInput method calls the readInputFromUI method and pass the argument in upper case or not.

Following snippet tests, whether ‘readInputFromUI’ is called with the string in upper case or not.

String message = "Enter Your Name";

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

InputUtil.readInputFromUI(message.toUpperCase());
PowerMock.expectLastCall().times(5);

PowerMock.replayAll();


InputUtilTest.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({ InputUtil.class })
public class InputUtilTest {

 @Test
 public void mockVoidEvenMethod() {
  String message = "Enter Your Name";

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

  InputUtil.readInputFromUI(message.toUpperCase());
  PowerMock.expectLastCall().times(5);

  PowerMock.replayAll();

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



Previous                                                 Next                                                 Home

No comments:

Post a Comment