简体   繁体   中英

Android unit testing: how to mock a beacon device

Is any way to mock a beacon when testing an Android app?

My Android app uses the AltBeacon library and the location API.
I can mock the location provider to inject GPS coordinates, but I also need to mock "beacons API" (I use the AltBeacon library) to inject beacon proximity.
Is this possible? or use some mocking framework to emulate the parts I use of the AltBeacon API?

In my case I needed to mock just the beacon, and I just used the same approach as the library tests . They use AltBeaconParser on a series of bytes that represent the beacon transmission:

public class AltBeaconTest {

  public static byte[] hexStringToByteArray(String s) {
      int len = s.length();
      byte[] data = new byte[len / 2];
      for (int i = 0; i < len; i += 2) {
          data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                               + Character.digit(s.charAt(i+1), 16));
      }
      return data;
  }

  @Test
  public void testRecognizeBeacon() {
    byte[] bytes = hexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509");
    AltBeaconParser parser = new AltBeaconParser();
    Beacon beacon = parser.fromScanData(bytes, -55, null);
    assertEquals("manData should be parsed", 9, ((AltBeacon) beacon).getMfgReserved() );
  }

  ... more tests
}

I'm not sure from your question if that's sufficient for your needs or not, but it worked for my needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM