如何嘲笑私人最终成员


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

现在我的问题是,当我创建myclass对象时,它正在调用android.os.Binder的本机方法。

我想要的是模拟IBinder.class并用我的模拟对象抑制新对象创建。

如何模拟这个?

easymock中有一个示例用于模拟天然方法。希望能帮助到你。源代码可以在GitHub存储库中找到。

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);
    }
}

这应该做技巧:

@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
  }
}

相关内容

  • 没有找到相关文章

最新更新