EventSerializer { @NonNull public JSONArray serializeAsJson(@NonNull List<BaseEvent> events) { Preconditions.checkNotNull(events); JSONArray jsonArray = new JSONArray(); for (BaseEvent event : events) { try { jsonArray.put(serializeAsJson(event)); } catch (JSONException e) { MoPubLog.d("Failed to serialize event \"" + event.getName() + "\" to JSON: ", e); } } return jsonArray; }  @NonNull JSONArray serializeAsJson(@NonNull List<BaseEvent> events); @NonNull JSONObject serializeAsJson(@NonNull BaseEvent event);  }
@Test public void serializeAsJson_withAllEventFieldsPopulated_shouldCorrectJsonRepresentation() throws Exception { ArrayList<BaseEvent> events = new ArrayList<BaseEvent>(); events.add(mockEvent); JSONArray jsonArray = subject.serializeAsJson(events); assertThat(jsonArray.length()).isEqualTo(1); JSONObject jsonObject = jsonArray.getJSONObject(0); validateBaseEventFields(jsonObject); }
@Test public void serializeAsJson_withAllErrorEventFieldsPopulated_shouldCorrectJsonRepresentation() throws Exception { ArrayList<BaseEvent> events = new ArrayList<BaseEvent>(); events.add(mockErrorEvent); JSONArray jsonArray = subject.serializeAsJson(events); assertThat(jsonArray.length()).isEqualTo(1); JSONObject jsonObject = jsonArray.getJSONObject(0); validateBaseEventFields(jsonObject); assertThat(jsonObject.getString("error_exception_class_name")).isEqualTo("error_exception_class_name"); assertThat(jsonObject.getString("error_message")).isEqualTo("error_message"); assertThat(jsonObject.getString("error_stack_trace")).isEqualTo("error_stack_trace"); assertThat(jsonObject.getString("error_file_name")).isEqualTo("error_file_name"); assertThat(jsonObject.getString("error_class_name")).isEqualTo("error_class_name"); assertThat(jsonObject.getString("error_method_name")).isEqualTo("error_method_name"); assertThat(jsonObject.getInt("error_line_number")).isEqualTo(123); }
@Test public void serializeAsJson_shouldReturnJsonArrayOfEvents() throws Exception { when(mockEvent.getName()).thenReturn(BaseEvent.Name.AD_REQUEST); when(mockEvent.getCategory()).thenReturn(BaseEvent.Category.REQUESTS); when(mockErrorEvent.getName()).thenReturn(BaseEvent.Name.IMPRESSION_REQUEST); when(mockErrorEvent.getCategory()).thenReturn(BaseEvent.Category.REQUESTS); ArrayList<BaseEvent> events = new ArrayList<BaseEvent>(); events.add(mockEvent); events.add(mockErrorEvent); JSONArray jsonArray = subject.serializeAsJson(events); assertThat(jsonArray.length()).isEqualTo(2); JSONObject jsonObject1 = jsonArray.getJSONObject(0); assertThat(jsonObject1.getString("name")).isEqualTo(BaseEvent.Name.AD_REQUEST.getName()); assertThat(jsonObject1.getString("name_category")).isEqualTo("requests"); JSONObject jsonObject2 = jsonArray.getJSONObject(1); assertThat(jsonObject2.getString("name")).isEqualTo("impression_request"); assertThat(jsonObject2.getString("name_category")).isEqualTo("requests"); }