GoogleAnalytics extends ServiceImpl implements EventTrackingService { String createPayloadData(String event){ String payload = null; try { String androidId = utils.getAndroidId(context); UUID deviceUUID = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")); Map<String, String> data = new LinkedHashMap<String, String>(); data.put("v", "1"); data.put("tid", this.trackingId); data.put("cid", deviceUUID.toString()); data.put("t", "screenview"); data.put("an", utils.getApplicationName(context)); data.put("av", utils.getVersionName(context)); data.put("aid", utils.getApplicationPackageName(context)); data.put("cd", event); StringBuilder sb = new StringBuilder(8192); for (Map.Entry<String, String> entry : data.entrySet()) { sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); sb.append("&"); } sb.deleteCharAt(sb.length() - 1); payload = new String(sb.toString().getBytes(), "UTF-8"); } catch (UnsupportedEncodingException ex) { utils.logIssue("Encoding exception", ex); } catch(Exception ex){ utils.logIssue("Error creating google analytics payload data", ex); } return payload; } GoogleAnalytics(Context context); @Override void enable(String trackingId); @Override boolean isEnabled(); @Override ServiceType getServiceType(); void logEvent(Context context, String event);  }
@Test public void testCreatePayloadData() { GoogleAnalytics googleAnalytics = new GoogleAnalytics(null); googleAnalytics.trackingId = "tracking_id"; googleAnalytics.utils = UnitTestUtils.mockUtils(); String response = googleAnalytics.createPayloadData("test_event"); String expected = "v=1&" + "tid=tracking_id&" + "cid=25f9e794-323b-3538-85f5-181f1b624d0b&" + "t=screenview&" + "an=UnitTesting Application&" + "av=1.1.1&" + "aid=com.percolate.foam.unit.testing" + "&cd=test_event"; assertEquals(expected, response); }
@Test public void testCreatePayloadDataErrors(){ GoogleAnalytics googleAnalytics = new GoogleAnalytics(null); Utils mockUtils = UnitTestUtils.mockUtils(); doThrow(RuntimeException.class).when(mockUtils).getAndroidId(any(Context.class)); googleAnalytics.utils = mockUtils; googleAnalytics.createPayloadData("testing_exception"); verify(mockUtils).logIssue(eq("Error creating google analytics payload data"), any(RuntimeException.class)); }