Friday 23 June 2017

Mock static non-void private methods

In this post, I am going to explain how to mock static non-void private methods.

Following snippet is used to mock the static non-void private method ‘readInputFromUI’.

String message = "Enter a number";
String methodToMock = "readInputFromUI";

PowerMock.mockStaticPartial(InputUtil.class, methodToMock);

PowerMock.expectPrivate(InputUtil.class, methodToMock, message).andReturn(10).times(1);

Following is the complete working application.

InputUtil.java
package com.sample.tests;

import javax.swing.JOptionPane;

public class InputUtil {

 public static int readInput(String message){
  return readInputFromUI(message);
 }
 
 private static int readInputFromUI(String message){
  int number = Integer.parseInt(JOptionPane.showInputDialog(message));
  return number;
 }
 
}


InputUtilTest.java
package com.sample.tests;

import static org.junit.Assert.assertEquals;

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() throws Exception {
  String message = "Enter a number";
  String methodToMock = "readInputFromUI";

  PowerMock.mockStaticPartial(InputUtil.class, methodToMock);

  PowerMock.expectPrivate(InputUtil.class, methodToMock, message).andReturn(10).times(1);

  PowerMock.replayAll();

  int number = InputUtil.readInput(message);

  assertEquals(number, 10);
  PowerMock.verifyAll();

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment