1. Spy
@Spy
when(mockedClass).invokingSomeOtherMethod().thenReturn("xyz");
   
@Spy
ClassToBTested classToBTested= new ClassToBTested();
2. Call RealMethod
@Mock mockedClass
when(mockedClass).doSomething(<AnyArg>).thenCallRealMethod.
3. Argument capturing:
ArgumentCaptor< ArgumentClass1 > captor1= ArgumentCaptor.forClass(ArgumentClass1.class);
ArgumentCaptor< ArgumentClass2> captor2 =ArgumentCaptor.forClass(ArgumentClass2.class);
classToBTested.testSomeMethod(someArgument);
  Mockito.verify(classToBTested).doSometing(captor1.capture(), captor2.capture()));
  ArgumentClass1 argumentObj1 = captor1.getValue();
  ArgumentClass2 argumentObj2 = captor2.getValue();
//Assert argumentObj1 data here
4. Avoid Spy Objects from invocation during mocking:
doReturn("xyz").when(mockedClass).invokingSomeOtherMethod().
5. Mocking new instance creation:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassToBeTested.class)
public class ClassToBeTested Test {
    private ClassToBeTested classToBeTested;
    @Before
    public void setUp() {
        classToBeTested = new ClassToBeTested();
    }
    @Test
    public void testSomeBehaviour() throws Exception {
        InternalClass internalClassObj = mock(InternalClass.class);//new InternalClass();
        PowerMockito.whenNew(InternalClass.class)
            .withAnyArguments().thenReturn(internalClassObj);
      classToBeTested.invokeBehaviourToBeTested();
 //verify the argument is internalClassObj
 assert captor.getValue() equalsTo internalClassObj
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
No comments:
Post a Comment