单元测试如下:
public class JsonDeserializeTest {
@Test
public void test() {
String data = "{\"field1\": null, \"field2\": null, \"field3\": \"1\", \"field4\": \"null\"}";
Model model;
try {
model = JSON.parseObject(data, Model.class);
} catch (Exception e) {
throw new IllegalStateException("parse " + data + " to object failed.", e);
}
Assert.assertEquals(model.field1, 0);
Assert.assertEquals(model.field2, 0F);
Assert.assertEquals(model.field3, "1");
Assert.assertNull(model.field4);
Assert.assertEquals(model.field5, 10000);
}
public static class Model {
public final int field1;
public final float field2;
public final String field3;
public final List<String> field4;
public int field5 = 0;
public Model(int field1, float field2, String field3, List<String> field4) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
this.field4 = field4;
this.field5 = 10000;
}
}
}
报错如下:
java.lang.AssertionError: expected [null] but found [[null]]
Expected :null
Actual :[null]
at org.testng.Assert.fail(Assert.java:96)
at org.testng.Assert.failNotSame(Assert.java:772)
at org.testng.Assert.assertNull(Assert.java:708)
at org.testng.Assert.assertNull(Assert.java:697)
at unittest.gs.framework.JsonDeserializeTest.test5(JsonDeserializeTest.java:100)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)