0
public class SomeClass {
    public void someMethod() {
        final TelephonyManager telephonyManager = (TelephonyManager)
                getContext().getSystemService(Context.TELEPHONY_SERVICE);
             ..... more code
   }
}

I need to test 'someMethod()' which creates instance of telephonymanager. My test code is as below:

@RunWith(RobolectricTestRunner.class)
@Config(cmanifest = Config.NONE)
public class SomeClassTest {

    private TelephonyManager manager;
    private ShadowTelephonyManager shadowManager;

    @Before
    public void setup() {
        manager = newInstanceOf(TelephonyManager.class);
        shadowManager = shadowOf(manager);
    }

    @Test
    public void testSomeMethod() {
        final SomeClass testInstance = new SomeClass();
        testInstance.someMethod();

    }
}

I am getting Null pointer exception where telephony manager instance is being created. I tried different ways but none has worked. Any suggestion ? Please.

apatel
  • 21
  • 4

1 Answers1

0

You can mock the Telephonymanager API's using @Mock Annotation.

Suppose your code is something like this:

public class SomeClass {
    public void someMethod() {
        final TelephonyManager telephonyManager = (TelephonyManager)
                getContext().getSystemService(Context.TELEPHONY_SERVICE);
        int callState = telephonyManager.getCallState();
   }
}

Your Unit Test framework to mock the actual instance of telephonymanager should be:

@RunWith(RobolectricTestRunner.class)
@Config(cmanifest = Config.NONE)
public class SomeClassTest {

    @Mock
    private TelephonyManager telephonyManager;

    @Mock
    private Context mContext = ShadowApplication.getInstance().getApplicationContext();

    @Before
    public void setup() {
        initMocks(this);
        when(mContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(telephonyManager);
    }

    @Test
    public void testSomeMethod() {
        final SomeClass testInstance = new SomeClass();
        when(telephonyManager.getCallState()).thenReturn(2);
        testInstance.someMethod();
    }
}

The callState value will be the value what you set.