Skip to content

Commit

Permalink
fix: Video.toString() outputs an illegal json string (#3032)
Browse files Browse the repository at this point in the history
refactor: json string concat

add an extra line at EOF
  • Loading branch information
Xcyq authored Oct 6, 2024
1 parent 8bd3175 commit 24b4586
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
package com.iluwatar.partialresponse;

import java.lang.reflect.Field;
import java.util.StringJoiner;

/**
* Map a video to json.
Expand All @@ -39,18 +40,15 @@ public class FieldJsonMapper {
* @return json of required fields from video
*/
public String toJson(Video video, String[] fields) throws Exception {
var json = new StringBuilder().append("{");
var json = new StringJoiner(",", "{", "}");

var i = 0;
var fieldsLength = fields.length;
while (i < fieldsLength) {
json.append(getString(video, Video.class.getDeclaredField(fields[i])));
if (i != fieldsLength - 1) {
json.append(",");
}
json.add(getString(video, Video.class.getDeclaredField(fields[i])));
i++;
}
json.append("}");

return json.toString();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public String toString() {
+ "\"length\": " + length + ","
+ "\"description\": \"" + description + "\","
+ "\"director\": \"" + director + "\","
+ "\"language\": \"" + language + "\","
+ "\"language\": \"" + language + "\""
+ "}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ void shouldGiveVideoDetailsById() throws Exception {
var actualDetails = resource.getDetails(1);

var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": "
+ "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\",}";
+ "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\"}";
Assertions.assertEquals(expectedDetails, actualDetails);
}

Expand All @@ -78,4 +78,17 @@ void shouldGiveSpecifiedFieldsInformationOfVideo() throws Exception {

Assertions.assertEquals(expectedDetails, actualFieldsDetails);
}
}

@Test
void shouldAllSpecifiedFieldsInformationOfVideo() throws Exception {
var fields = new String[]{"id", "title", "length", "description", "director", "language"};

var expectedDetails = "{\"id\": 1,\"title\": \"Avatar\",\"length\": 178,\"description\": "
+ "\"epic science fiction film\",\"director\": \"James Cameron\",\"language\": \"English\"}";
Mockito.when(fieldJsonMapper.toJson(any(Video.class), eq(fields))).thenReturn(expectedDetails);

var actualFieldsDetails = resource.getDetails(1, fields);

Assertions.assertEquals(expectedDetails, actualFieldsDetails);
}
}

0 comments on commit 24b4586

Please sign in to comment.