0

I have a final class as below

public  class firstclass{

   private String firstmethod(){

       return new secondclass("params").somemethod();

}

}


public final class secondclass{

   secondclass(String params){

        //some code

}

public String somemethod(){

         // some code 
        return somevariable";
}
}

I have to here test first class so I have mocked this as below

secondclass classMock = PowerMockito.mock(secondclass .class);
        PowerMockito.whenNew(secondclass .class).withAnyArguments().thenReturn(classMock);
Mockito.doReturn("test").when(classMock).somemethod();

But it is not mocking as I expected can anyone help me?

Reddevil
  • 682
  • 1
  • 9
  • 22
  • Why would you mock a final class? If it's final, it's not meant to be used that way. – Louis Wasserman Nov 02 '16 at 05:08
  • I have to test firstclass firstmethod. In that there is a call for secondclass somemethod which returns somevariable so I mocked that to return test value – Reddevil Nov 02 '16 at 05:18
  • 1
    Then you should design the first class to accept an interface. If your first class is calling a final class, that's it, you can't change it. – Louis Wasserman Nov 02 '16 at 05:19
  • No i can't change the code. So there is no way to mock that? – Reddevil Nov 02 '16 at 05:21
  • No, there is no way for you to change that unless you change the code. The smallest possible unit under test possible in such a case is `firstclass` **and** `secondclass` as a union. – SpaceTrucker Nov 02 '16 at 07:34

1 Answers1

0
  1. The method firstclass.firstmethod() is private method. So try to test this method through public method in which it is getting called.

  2. You can mock SecondClass and its final method using @RunWith(PowerMockRunner.class) and @PrepareForTest(SecondClass.class) annotations.

Please see below the working code:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(SecondClass.class)
public class FirstClassTest{


    @Before
    public void init() {

    }

    @After
    public void clear() {

    }

    @Test
    public void testfirstmethod() throws Exception{

        SecondClass classMock = PowerMockito.mock(SecondClass.class);
        PowerMockito.whenNew(SecondClass.class).withAnyArguments().thenReturn(classMock);
        Mockito.doReturn("test").when(classMock).somemethod();

        new FirstClass().firstmethod();
    }
}

Libraries used:

enter image description here

Khuzi
  • 2,792
  • 3
  • 15
  • 26