2015-12-09 2 views
3

Я дорабатываю UnitTests до существующего приложения. Когда я запускаю этот простой тест блокRoboelectric дает мне java.lang.IllegalArgumentException: требуется разрешение INTERNET

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.robolectric.RobolectricGradleTestRunner; 
import org.robolectric.annotation.Config; 
import static junit.framework.Assert.assertTrue; 

@RunWith(RobolectricGradleTestRunner.class) 
@Config(constants = BuildConfig.class, packageName = "com.blah.blah") 
public class TestThis { 

@Test 
public void blah(){ 
    assertTrue(true); 
    } 
} 

Я получаю эту ошибку

java.lang.IllegalArgumentException: INTERNET permission is required. 
at com.segment.analytics.Analytics$Builder.<init>(Analytics.java:585) 
at com.segment.analytics.Analytics.with(Analytics.java:115) 
at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:140) 
at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:433) 
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:240) 
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188) 
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54) 
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152) 
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) 
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) 
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) 
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:497) 
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) 

java.lang.RuntimeException: java.lang.IllegalArgumentException: INTERNET permission is required. 
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:244) 
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188) 
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54) 
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152) 
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) 
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) 
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) 
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) 
Caused by: java.lang.IllegalArgumentException: INTERNET permission is required. 
at com.segment.analytics.Analytics$Builder.<init>(Analytics.java:585) 
at com.segment.analytics.Analytics.with(Analytics.java:115) 
at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:140) 
at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:433) 
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:240) 

Мой первый предположение, что robolectric не получал манифест, но это, кажется, есть. Есть ли что-то фундаментальное, что мне не хватает?

К сожалению, я был в спешке, когда я писал это и следовало бы добавить еще несколько деталей

У меня есть это в явном

<uses-permission android:name="android.permission.INTERNET" /> 

Я попытался явно устанавливая манифест после прочтения эта страница Robolectric junit test - missing internet permission

Еще одно обновление, проблема является HTTP вызов инициируется в OnCreate()

public class TestApp extends Application { 

@Override 
public final void onCreate() { 
    super.onCreate(); 
    singleton = this; 
    if (!BuildConfig.DEBUG) { Fabric.with(this, new Crashlytics()); } 
    loadData(); 
    // The next line makes the http call 
    Analytics.with(getApplicationContext()).identify("userId", null, null); 
    RequestQueues.initInstance(singleton); 
} 
} 

Любые мысли? Я мог бы добавить

if (notTest) 
{ 
    com.segment.analytics.Analytics.with(getApplicationContext()).identify("userId",  
} 

, но предпочел бы не

+0

Я считаю, что у вас нет определенного разрешения на использование в вашем манифесте – 3kings

+0

http://stackoverflow.com/questions/32740070/robolectric-junit-test-missing-internet-permission –

+0

Я видел это и имею попробовал его с и без явной установки места манифеста в тестовом классе. Хорошая мысль. –

ответ

7

Видимо при выполнении модульных тестов с использованием robolectric, разрешения не будет включено. Проверка сегмента LIB, он проверяет наличие разрешения интернет, как показано ниже:

/** Returns true if the application has the given permission. */ 
    public static boolean hasPermission(Context context, String permission) { 
    return context.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED; 
    } 

Но, как сказал, эм запуска тестов ваше приложение не будет иметь разрешение в Интернет (однако вы будете иметь возможность делать звонки через Интернет) вас может решить это, предоставив разрешение на доступ к теневому приложению, а затем используя этот контекст в сегменте lib.

Добавить этот метод в ваш TestApp

protected Context instance() { 
     ShadowApplication shadowApp = Shadows.shadowOf(this); 
     shadowApp.grantPermissions("android.permission.INTERNET"); 

     return shadowApp.getApplicationContext(); 
    } 

И изменить код этого

Analytics.with(instance()).identify("userId", null, null); 

Надежда это поможет вам.

+0

Извините, отвлекся и только что вернулся к этому. Работает как шарм. благодаря! –

-2

Добавить

<uses-permission android:name="android.permission.INTERNET" /> 

вне тега приложения в вашем AndroidManifest.xml

+0

У меня есть это в манифесте. Вот почему я смущен –

Смежные вопросы