关于:
例如,我在几乎每个 Activity 类的 onCreate 方法中都有 Crashlytics、Google Analytics 代码。当遇到这些行时,Robolectric 会抛出错误。ShadowActivity 能解决这些类型的问题吗?
您可以将对库的调用包装在实现某种 AnalyticsFacade 的 Facade 实现中,并创建一个封装所有实现的类,并将常见行为委托给它们。
public interface Analytics{
void sendEvent(String category, String action, Map<String,String> params);
void log(String msg);
}
public class AnalyticsFacade implements Analytics{
private List<Analytics> analyticsServices;
public AnalyticsFacade()
{
this.analyticsServices = new ArrayList<Analytics>();
}
public void addAnalyticsService(Analytics analytics){
analyticsServices.add(analytics);
}
@Override
public void sendEvent(String category, String action, Map<String, String> params)
{
for(Analytics service: analyticsServices){
service.sendEvent(category,action,params);
}
}
@Override
public void log(String msg)
{
for(Analytics service: analyticsServices){
service.log(msg);
}
}
}
public class GoogleAnalytics implements Analytics{
private Tracker tracker;
public GoogleAnalytics(Tracker tracker)
{
this.tracker = tracker;
}
@Override
public void sendEvent(String category, String action, Map<String, String> params)
{
//Note that this method signature has changed since GA v2 , now you pass a Map and
//it has a builder in order to create it
tracker.send(category,action,params);
}
@Override
public void log(String msg)
{
throw new RuntimeException("Not implemented");
}
}