1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.sf.json.util;
18
19 import java.io.StringWriter;
20
21 import junit.framework.TestCase;
22 import net.sf.json.JSONFunction;
23 import net.sf.json.JSONObject;
24
25
26
27
28 public class TestJSONBuilder extends TestCase {
29 public static void main( String[] args ) {
30 junit.textui.TestRunner.run( TestJSONBuilder.class );
31 }
32
33 public TestJSONBuilder( String testName ) {
34 super( testName );
35 }
36
37 public void testCreateArray() {
38 StringWriter w = new StringWriter();
39 new JSONBuilder( w ).array()
40 .value( true )
41 .value( 1.1d )
42 .value( 2L )
43 .value( "text" )
44 .endArray();
45 assertEquals( "[true,1.1,2,\"text\"]", w.toString() );
46 }
47
48 public void testCreateEmptyArray() {
49 StringWriter w = new StringWriter();
50 new JSONBuilder( w ).array()
51 .endArray();
52 assertEquals( "[]", w.toString() );
53 }
54
55 public void testCreateEmptyArrayWithNullObjects() {
56 StringWriter w = new StringWriter();
57 new JSONBuilder( w ).array()
58 .value( null )
59 .value( null )
60 .endArray();
61 assertEquals( "[null,null]", w.toString() );
62 }
63
64 public void testCreateEmptyObject() {
65 StringWriter w = new StringWriter();
66 new JSONBuilder( w ).object()
67 .endObject();
68 assertEquals( "{}", w.toString() );
69 }
70
71 public void testCreateFunctionArray() {
72 StringWriter w = new StringWriter();
73 new JSONBuilder( w ).array()
74 .value( new JSONFunction( "var a = 1;" ) )
75 .value( new JSONFunction( "var b = 2;" ) )
76 .endArray();
77 assertEquals( "[function(){ var a = 1; },function(){ var b = 2; }]", w.toString() );
78 }
79
80 public void testCreateSimpleObject() {
81 StringWriter w = new StringWriter();
82 new JSONBuilder( w ).object()
83 .key( "bool" )
84 .value( true )
85 .key( "numDouble" )
86 .value( 1.1d )
87 .key( "numInt" )
88 .value( 2 )
89 .key( "text" )
90 .value( "text" )
91 .key( "func" )
92 .value( new JSONFunction( "var a = 1;" ) )
93 .endObject();
94 JSONObject jsonObj = JSONObject.fromObject( w.toString() );
95 assertEquals( Boolean.TRUE, jsonObj.get( "bool" ) );
96 assertEquals( new Double( 1.1d ), jsonObj.get( "numDouble" ) );
97 assertEquals( new Long( 2 ).longValue(), ((Number) jsonObj.get( "numInt" )).longValue() );
98 assertEquals( "text", jsonObj.get( "text" ) );
99 assertTrue( JSONUtils.isFunction( jsonObj.get( "func" ) ) );
100 assertEquals( "function(){ var a = 1; }", jsonObj.get( "func" )
101 .toString() );
102 }
103 }