Mocking up WifiManager for Android Unit Testing

前端 未结 3 891
时光说笑
时光说笑 2021-01-13 08:30

I\'m trying to implement some unit tests for a couple of classes that rely on WifiManager and the returned ScanResults. What I\'d like to do is be able to control the ScanR

3条回答
  •  迷失自我
    2021-01-13 09:04

    You could try to create the ScanResult instances by using reflection to access the private constructors. The code might look something like this:

            try {
                Constructor ctor = ScanResult.class.getDeclaredConstructor(null);
                ctor.setAccessible(true);
                ScanResult sr = ctor.newInstance(null);
                sr.BSSID = "foo";
                sr.SSID = "bar";
                // etc... 
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    

    For other ways of testing, I most of times convert the information from instances like ScanResult and encapsulate only the information I need into my own objects. These I feed to the method doing the hard work. This makes testing easier as you can easily build these intermediate objects without relying on the real ScanResult objects.

提交回复
热议问题