//member of some class example "myclass"
private final IBinder mICallBack = new Binder();
现在我的问题是,当我创建myclass
对象时,它正在调用android.os.Binder
的本机方法。
我想要的是模拟IBinder.class
并使用我的模拟对象来抑制新对象的创建。
如何嘲笑这个?
答案 0 :(得分:1)
EasyMock中有一个用于模拟本机方法的示例。希望能帮助到你。 可以在github存储库中找到源代码here。
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);
}
}
答案 1 :(得分:0)
这应该可以解决问题:
@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
}
}