Skip to content

Commit

Permalink
Migrate all tests to Truth & use assertThrows (#2687)
Browse files Browse the repository at this point in the history
* Use `assertThrows` for expected exceptions in tests

* Use Truth for unit tests in `proto` and `extras` module

* Perform assertions on some currently unused test variables

* Improve tests

* Improve non-finite floating point tests

Because there is only `Gson.toJson(Object)` (and no primitive specific
overloads) the tests were previously testing the adapter for the boxed
object, e.g. Double, twice.

* Improve tests

* Remove explicit type arguments from tests where they can be inferred

This works because unlike the main sources the tests are compiled with Java 11.
  • Loading branch information
Marcono1234 authored Jun 7, 2024
1 parent 7573bf5 commit 99cc4cb
Show file tree
Hide file tree
Showing 65 changed files with 1,370 additions and 2,143 deletions.
5 changes: 5 additions & 0 deletions extras/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<developers>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,8 @@ private RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName, boole
}

/**
* Creates a new runtime type adapter using for {@code baseType} using {@code typeFieldName} as
* the type field name. Type field names are case sensitive.
* Creates a new runtime type adapter for {@code baseType} using {@code typeFieldName} as the type
* field name. Type field names are case sensitive.
*
* @param maintainType true if the type field should be included in deserialized objects
*/
Expand All @@ -184,8 +184,8 @@ public static <T> RuntimeTypeAdapterFactory<T> of(
}

/**
* Creates a new runtime type adapter using for {@code baseType} using {@code typeFieldName} as
* the type field name. Type field names are case sensitive.
* Creates a new runtime type adapter for {@code baseType} using {@code typeFieldName} as the type
* field name. Type field names are case sensitive.
*/
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,13 @@

package com.google.gson.graph;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static com.google.common.truth.Truth.assertThat;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;

Expand All @@ -42,11 +40,11 @@ public void testSerialization() {
new GraphAdapterBuilder().addType(Roshambo.class).registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();

assertEquals(
"{'0x1':{'name':'ROCK','beats':'0x2'},"
+ "'0x2':{'name':'SCISSORS','beats':'0x3'},"
+ "'0x3':{'name':'PAPER','beats':'0x1'}}",
gson.toJson(rock).replace('"', '\''));
assertThat(gson.toJson(rock).replace('"', '\''))
.isEqualTo(
"{'0x1':{'name':'ROCK','beats':'0x2'},"
+ "'0x2':{'name':'SCISSORS','beats':'0x3'},"
+ "'0x3':{'name':'PAPER','beats':'0x1'}}");
}

@Test
Expand All @@ -61,12 +59,12 @@ public void testDeserialization() {
Gson gson = gsonBuilder.create();

Roshambo rock = gson.fromJson(json, Roshambo.class);
assertEquals("ROCK", rock.name);
assertThat(rock.name).isEqualTo("ROCK");
Roshambo scissors = rock.beats;
assertEquals("SCISSORS", scissors.name);
assertThat(scissors.name).isEqualTo("SCISSORS");
Roshambo paper = scissors.beats;
assertEquals("PAPER", paper.name);
assertSame(rock, paper.beats);
assertThat(paper.name).isEqualTo("PAPER");
assertThat(paper.beats).isSameInstanceAs(rock);
}

@Test
Expand All @@ -78,8 +76,8 @@ public void testDeserializationDirectSelfReference() {
Gson gson = gsonBuilder.create();

Roshambo suicide = gson.fromJson(json, Roshambo.class);
assertEquals("SUICIDE", suicide.name);
assertSame(suicide, suicide.beats);
assertThat(suicide.name).isEqualTo("SUICIDE");
assertThat(suicide.beats).isSameInstanceAs(suicide);
}

@Test
Expand All @@ -99,7 +97,7 @@ public void testSerializeListOfLists() {
Gson gson = gsonBuilder.create();

String json = gson.toJson(listOfLists, listOfListsType);
assertEquals("{'0x1':['0x1','0x2'],'0x2':[]}", json.replace('"', '\''));
assertThat(json.replace('"', '\'')).isEqualTo("{'0x1':['0x1','0x2'],'0x2':[]}");
}

@Test
Expand All @@ -115,9 +113,9 @@ public void testDeserializeListOfLists() {
Gson gson = gsonBuilder.create();

List<List<?>> listOfLists = gson.fromJson("{'0x1':['0x1','0x2'],'0x2':[]}", listOfListsType);
assertEquals(2, listOfLists.size());
assertSame(listOfLists, listOfLists.get(0));
assertEquals(Collections.emptyList(), listOfLists.get(1));
assertThat(listOfLists).hasSize(2);
assertThat(listOfLists.get(0)).isSameInstanceAs(listOfLists);
assertThat(listOfLists.get(1)).isEmpty();
}

@Test
Expand All @@ -134,11 +132,11 @@ public void testSerializationWithMultipleTypes() {
.registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();

assertEquals(
"{'0x1':{'name':'Google','employees':['0x2','0x3']},"
+ "'0x2':{'name':'Jesse','company':'0x1'},"
+ "'0x3':{'name':'Joel','company':'0x1'}}",
gson.toJson(google).replace('"', '\''));
assertThat(gson.toJson(google).replace('"', '\''))
.isEqualTo(
"{'0x1':{'name':'Google','employees':['0x2','0x3']},"
+ "'0x2':{'name':'Jesse','company':'0x1'},"
+ "'0x3':{'name':'Joel','company':'0x1'}}");
}

@Test
Expand All @@ -155,13 +153,13 @@ public void testDeserializationWithMultipleTypes() {
+ "'0x2':{'name':'Jesse','company':'0x1'},"
+ "'0x3':{'name':'Joel','company':'0x1'}}";
Company company = gson.fromJson(json, Company.class);
assertEquals("Google", company.name);
assertThat(company.name).isEqualTo("Google");
Employee jesse = company.employees.get(0);
assertEquals("Jesse", jesse.name);
assertEquals(company, jesse.company);
assertThat(jesse.name).isEqualTo("Jesse");
assertThat(jesse.company).isEqualTo(company);
Employee joel = company.employees.get(1);
assertEquals("Joel", joel.name);
assertEquals(company, joel.company);
assertThat(joel.name).isEqualTo("Joel");
assertThat(joel.company).isEqualTo(company);
}

static class Roshambo {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
*/
package com.google.gson.interceptors;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Expand Down Expand Up @@ -55,25 +55,22 @@ public void setUp() throws Exception {

@Test
public void testExceptionsPropagated() {
try {
gson.fromJson("{}", User.class);
fail();
} catch (JsonParseException expected) {
}
var e = assertThrows(JsonParseException.class, () -> gson.fromJson("{}", User.class));
assertThat(e).hasMessageThat().isEqualTo("name and password are required fields.");
}

@Test
public void testTopLevelClass() {
User user = gson.fromJson("{name:'bob',password:'pwd'}", User.class);
assertEquals(User.DEFAULT_EMAIL, user.email);
assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL);
}

@Test
public void testList() {
List<User> list =
gson.fromJson("[{name:'bob',password:'pwd'}]", new TypeToken<List<User>>() {}.getType());
User user = list.get(0);
assertEquals(User.DEFAULT_EMAIL, user.email);
assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL);
}

@Test
Expand All @@ -82,30 +79,31 @@ public void testCollection() {
gson.fromJson(
"[{name:'bob',password:'pwd'}]", new TypeToken<Collection<User>>() {}.getType());
User user = list.iterator().next();
assertEquals(User.DEFAULT_EMAIL, user.email);
assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL);
}

@Test
public void testMapKeyAndValues() {
Type mapType = new TypeToken<Map<User, Address>>() {}.getType();
try {
gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType);
fail();
} catch (JsonSyntaxException expected) {
}
var e =
assertThrows(
JsonSyntaxException.class,
() -> gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType));
assertThat(e).hasMessageThat().isEqualTo("Address city, state and zip are required fields.");

Map<User, Address> map =
gson.fromJson(
"[[{name:'bob',password:'pwd'},{city:'Mountain View',state:'CA',zip:'94043'}]]",
mapType);
Entry<User, Address> entry = map.entrySet().iterator().next();
assertEquals(User.DEFAULT_EMAIL, entry.getKey().email);
assertEquals(Address.DEFAULT_FIRST_LINE, entry.getValue().firstLine);
assertThat(entry.getKey().email).isEqualTo(User.DEFAULT_EMAIL);
assertThat(entry.getValue().firstLine).isEqualTo(Address.DEFAULT_FIRST_LINE);
}

@Test
public void testField() {
UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class);
assertEquals(User.DEFAULT_EMAIL, userGroup.user.email);
assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_EMAIL);
}

@Test
Expand All @@ -123,9 +121,9 @@ public void write(JsonWriter out, User value) throws IOException {
@Override
public User read(JsonReader in) throws IOException {
in.beginObject();
String unused1 = in.nextName();
assertThat(in.nextName()).isEqualTo("name");
String name = in.nextString();
String unused2 = in.nextName();
assertThat(in.nextName()).isEqualTo("password");
String password = in.nextString();
in.endObject();
return new User(name, password);
Expand All @@ -134,14 +132,14 @@ public User read(JsonReader in) throws IOException {
.registerTypeAdapterFactory(new InterceptorFactory())
.create();
UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class);
assertEquals(User.DEFAULT_EMAIL, userGroup.user.email);
assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_EMAIL);
}

@Test
public void testDirectInvocationOfTypeAdapter() throws Exception {
TypeAdapter<UserGroup> adapter = gson.getAdapter(UserGroup.class);
UserGroup userGroup = adapter.fromJson("{\"user\":{\"name\":\"bob\",\"password\":\"pwd\"}}");
assertEquals(User.DEFAULT_EMAIL, userGroup.user.email);
assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_EMAIL);
}

@SuppressWarnings("unused")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

package com.google.gson.typeadapters;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Expand All @@ -33,12 +33,14 @@ public void test() throws Exception {
new GsonBuilder().registerTypeAdapterFactory(new PostConstructAdapterFactory()).create();
Sandwich unused =
gson.fromJson("{\"bread\": \"white\", \"cheese\": \"cheddar\"}", Sandwich.class);
try {
gson.fromJson("{\"bread\": \"cheesey bread\", \"cheese\": \"swiss\"}", Sandwich.class);
fail();
} catch (IllegalArgumentException expected) {
assertEquals("too cheesey", expected.getMessage());
}

var e =
assertThrows(
IllegalArgumentException.class,
() ->
gson.fromJson(
"{\"bread\": \"cheesey bread\", \"cheese\": \"swiss\"}", Sandwich.class));
assertThat(e).hasMessageThat().isEqualTo("too cheesey");
}

@Test
Expand All @@ -52,13 +54,13 @@ public void testList() {

// Throws NullPointerException without the fix in https://github.com/google/gson/pull/1103
String json = gson.toJson(sandwiches);
assertEquals(
"{\"sandwiches\":[{\"bread\":\"white\",\"cheese\":\"cheddar\"},"
+ "{\"bread\":\"whole wheat\",\"cheese\":\"swiss\"}]}",
json);
assertThat(json)
.isEqualTo(
"{\"sandwiches\":[{\"bread\":\"white\",\"cheese\":\"cheddar\"},"
+ "{\"bread\":\"whole wheat\",\"cheese\":\"swiss\"}]}");

MultipleSandwiches sandwichesFromJson = gson.fromJson(json, MultipleSandwiches.class);
assertEquals(sandwiches, sandwichesFromJson);
assertThat(sandwichesFromJson).isEqualTo(sandwiches);
}

@SuppressWarnings({"overrides", "EqualsHashCode"}) // for missing hashCode() override
Expand Down
Loading

0 comments on commit 99cc4cb

Please sign in to comment.