Code sample for BAEL-2085
This commit is contained in:
parent
9bb33102f9
commit
538d2a4ef1
|
@ -0,0 +1,19 @@
|
|||
package org.baeldung.gson.entities;
|
||||
|
||||
public class User {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
private transient String nationality;
|
||||
|
||||
public User(int id, String name, String nationality) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.nationality = nationality;
|
||||
}
|
||||
|
||||
public User(int id, String name) {
|
||||
this(id, name, null);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package org.baeldung.gson.serialization.test;
|
||||
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.baeldung.gson.entities.User;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.junit.runners.Parameterized.Parameter;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
@RunWith(Parameterized.class)
|
||||
public class JsonFileUnitTest {
|
||||
|
||||
@Parameter
|
||||
public Object object;
|
||||
|
||||
@Parameters
|
||||
public static Object[] data() {
|
||||
return new Object[] { 123.45, new User(1, "Tom", "American") };
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProperData_whenStoredInFile_shouldSaveJsonSuccessfully() {
|
||||
String filePath = "target/output.json";
|
||||
try (Writer writer = new FileWriter(filePath)) {
|
||||
Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
gson.toJson(object, writer);
|
||||
Assert.assertTrue(Files.exists(Paths.get(filePath)));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue