0
//member of some class example "myclass"
private final IBinder mICallBack = new Binder();

Now my problem is that when I am creating myclass object it is calling native methods of android.os.Binder.

What I want is mock IBinder.class and suppress new object creation with my mock object.

How to mock this?

Neil
  • 14,063
  • 3
  • 30
  • 51
Ameer ali khan
  • 965
  • 7
  • 10
  • 1
    Possible duplicate of [How to mock final field? mockito/powermock](http://stackoverflow.com/questions/23629766/how-to-mock-final-field-mockito-powermock) – SpaceTrucker Mar 14 '17 at 12:06

2 Answers2

1

There is an example in EasyMock for mocking native methods. Hope it helps. The source code could be found here in github repository.

package samples.nativemocking;

/**
 * The purpose of this class is to demonstrate that it's possible to mock native
 * methods using plain EasyMock class extensions.
 */
public class NativeService {

    public native String invokeNative(String nativeParameter);

}


package samples.nativemocking;

/**
 * The purpose of this class is to invoke a native method in a collaborator.
 */
public class NativeMockingSample {

    private final NativeService nativeService;

    public NativeMockingSample(NativeService nativeService) {
        this.nativeService = nativeService;
    }

    public String invokeNativeMethod(String param) {
        return nativeService.invokeNative(param);
    }
}

package samples.junit4.nativemocking;

import org.junit.Test;
import samples.nativemocking.NativeMockingSample;
import samples.nativemocking.NativeService;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;

/**
 * This test demonstrates that it's possible to mock native methods using plain
 * EasyMock class extensions.
 */
public class NativeMockingSampleTest {

    @Test
    public void testMockNative() throws Exception {
        NativeService nativeServiceMock = createMock(NativeService.class);
        NativeMockingSample tested = new NativeMockingSample(nativeServiceMock);

        final String expectedParameter = "question";
        final String expectedReturnValue = "answer";
        expect(nativeServiceMock.invokeNative(expectedParameter)).andReturn(expectedReturnValue);

        replay(nativeServiceMock);

        assertEquals(expectedReturnValue, tested.invokeNativeMethod(expectedParameter));

        verify(nativeServiceMock);
    }
}
Vanguard
  • 1,336
  • 1
  • 15
  • 30
0

This should do the trick:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Binder.class)
public class ClassTest {
  @Mock
  private Binder binderMock;

  @Before
  public void init(){
     MockitoAnnotations.initMocks(this);
  }

  @Test
  public void doSomething() throws Exception {
      // Arrange    
      PowerMockito.whenNew(Binder.class).withNoArguments()
         .thenReturn(binderMock);

      //.. rest of set-up and invocation
  }

}
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63