2

I am to mock a static function named toBeMockedFunction in Util class. This method is called from toBeUnitTested which is a public static void method. I want toBeMockedFunction to do nothing. I tried many approaches (snippet posted of such 2) of partial mock and stubbing and unable to succeed.

Please suggest what I am doing wrong.

public class Util {
    // Some code
    public static void toBeUnitTested(CustomObject cb, CustomObject1 cb1, List<CustomObject2> rows, boolean delete) {
        // some code

       toBeMockedFunction(cb, "test", "test");
    }

    public static CustomObject toBeMockedFunction(CustomObject cb, String str1) {
        // some code
    }

}

And below is my junit class

@RunWith(PowerMockRunner.class)
 @PrepareForTest({ Util.class})
 public class UtilTest {
    @Test
    public void Test1() {
        PowerMockito.spy(Util.class);            

 //mock toBeMocked function and make it do nothing 
 PowerMockito.when(PowerMockito.spy(Util.toBeMockedFunction((CustomObject)Mockito.anyObject(), Mockito.anyString()))).thenReturn(null);

        Util.toBeUnitTested(cb, "test", "test");
     }
  }
  1. Approach2

      PowerMockito.mockStatic(Util.class);  
      PowerMockito.when(Util.toBeUnitTested((CustomObject)Mockito.anyObject(),Mockito.anyString())).thenCallRealMethod();
        Util.toBeUnitTested(cb, "test", "test");
    
sandy
  • 1,153
  • 7
  • 21
  • 39

1 Answers1

3

This is an example of how can do that:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Util.class})
public class UtilTest {
   @Test
   public void Test1() {

      PowerMockito.spy(Util.class);
      PowerMockito.doReturn(null).when(Util.class, "toBeMockedFunction", Mockito.any(CustomObject.class), Mockito.anyString(), Mockito.anyString());

      List<CustomObject2> customObject2List = new ArrayList<>();
      customObject2List.add(new CustomObject2());

      Util.toBeUnitTested(new CustomObject(), new CustomObject1(), customObject2List, true);
   }
}

Please note that the code of your OP doesn't compile. Method toBeMockedFunction(CustomObject cb, String str1) receives only 2 parameters and you are calling with 3: toBeMockedFunction(cb, "test", "test");. As you could see, I've added the last one to the method signature.

Hope it helps

troig
  • 7,072
  • 4
  • 37
  • 63
  • 2
    PowerMockito.mockStatic(Util.class); will be mocking all static methods of class including toBeUnitTested() function. Its definition would never be called. – sandy May 14 '15 at 09:19