Wednesday, April 24, 2019

Static Methods Junit Test

1. Junit test for static class or methods using PowerMock.
Answer : 





Calculator.java 
package com.shubh.staticJunit.StaticJunitTest;

public class Calculator {

 private int x;
 private int y;

 public Calculator(int x, int y) {
  this.x = x;
  this.y = y;
 }

 public int getX() {
  return x;
 }

 public int getY() {
  return y;
 }
}

CalculatorService.java
package com.shubh.staticJunit.StaticJunitTest;

public class CalculatorService {

 public Calculator geoLocate(Calculator calculator) {
  return new Calculator(calculator.getX(), calculator.getY());
 }

 public Calculator getRandomDistance(Calculator calculator, int distance) {
  return new Calculator(calculator.getX() + Utils.randomDistance(distance),
    calculator.getY() + Utils.randomDistance(distance));
 }

 public int sum(int a, int b) {
  return Utils.sum(a, b);
 }
}


Utils.java
package com.shubh.staticJunit.StaticJunitTest;
import java.util.Random;

public final class Utils {

 private static final Random RAND = new Random();

 private Utils() {
  // Utilities class
 }

 public static int randomDistance(int distance) {
  return RAND.nextInt(distance + distance) - distance;
 }

 public static int sum(int a, int b) {
  int sum = a + b;
  return sum;
 }
}
CalculatorServiceTest.java
package com.shubh.staticJunit.StaticJunitTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Utils.class })
public class CalculatorServiceTest {

 private CalculatorService calculatorService;

 @Before
 public void setUp() {
  PowerMockito.mockStatic(Utils.class);
  calculatorService = new CalculatorService();
 }

 @Test
 public void testGeneratePointWithinDistance() {

  int distance = 222;

  when(Utils.randomDistance(anyInt())).thenReturn(distance);
  Calculator input = new Calculator(21, 10);
  Calculator expOutPut = new Calculator(input.getX() + distance,
    input.getY() + distance);
  assertTrue(isPointsEqual(expOutPut,
    calculatorService.getRandomDistance(input, 1)));
 }

 public void sumTest() {
  int a = 10;
  int b = 5;
  int sum = 15;

  when(Utils.sum(anyInt(), anyInt())).thenReturn(sum);
  Assert.assertEquals(sum, calculatorService.sum(a, b));
 }

 public static boolean isPointsEqual(Calculator p1, Calculator p2) {
  return p1.getX() == p2.getX()
   && p1.getY() == p2.getY();
 }
}



No comments:

Post a Comment