【问题标题】:Create GoogleApiClient shadow with Robolectric使用 Robolectric 创建 GoogleApiClient 影子
【发布时间】:2015-09-18 16:48:27
【问题描述】:

我正在使用 Robolectric 并尝试创建 GoogleApiClient 的 Shadow 对象,但未成功。 Shadow 类中的方法永远不会被调用。 GoogleApiClient 是接口 - 这可能是个问题吗?有什么方法可以“隐藏” GoogleApiClient 接口(或在测试中模拟 GoogleApiClient)?

实施:

@Implements(GoogleApiClient.class)
public class ShadowGoogleApiClient {

public void __constructor__ (){
    System.out.println("__constructor____constructor__");
}

@Implementation
void connect() {
    System.out.println("connectconnectconnect");
}

@Implementation
boolean isConnected() {
    System.out.println("isConnectedisConnected");
    return false;
}

@Implementation
boolean isConnecting() {
    System.out.println("isConnectingisConnecting");
    return false;
}

}

我已经在我的测试中定义了 Shadow 类:

@Config(shadows = {ShadowGoogleApiClient.class},
    constants = BuildConfig.class)
@RunWith(CustomRobolectricRunner.class)
public class ApiTest {
 ...
}

【问题讨论】:

  • 您必须注册您的课程才能进行跟踪。见stackoverflow.com/questions/29629786/…
  • 其实还是不行。我将类 (GoogleApiClient) 添加到 InstrumentationConfiguration.Builder 但没有任何更改。
  • GoogleApiClient 是一个接口。不确定,但你只能隐藏具体类是有道理的。调试应用程序时应该显示真正的实现类。您可以使用 @Implements 中的 className 属性隐藏无法访问的类
  • @nenick 我认为你是对的。我已经测试了这个假设,它需要是具体的类。问题是 GoogleApiClient 的具体类具有包私有可见性,我无法“隐藏”它(它的名称类似于“com.google.android.gms.common.api.c”,它是来自库的反编译名称)。
  • 您可以通过编写完整的限定类名 (package.ClassName) 来隐藏“包私有”类。请参阅 @Implements 中的 className 属性。当 com.google.android.gms.common.api.c 稳定后,再使用它。这来自仅仅显示实现类还是来自调试?也许你会得到一个不同的类名

标签: java android unit-testing robolectric


【解决方案1】:

您是否尝试过使用 Mockito 来模拟 GoogleApiClient 的实现?

doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                myCallback.onConnected();
                return null;
            }
        }).when(mGoogleApiClient).connect();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多