View Javadoc

1   /*
2    * $Id: JsonLibHandlerTest.java 651946 2008-04-27 13:41:38Z apetrelli $
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  package org.apache.struts2.rest.handler;
23  
24  import junit.framework.TestCase;
25  
26  import java.io.StringWriter;
27  import java.io.IOException;
28  import java.io.StringReader;
29  import java.util.Arrays;
30  
31  public class JsonLibHandlerTest extends TestCase {
32  
33      public void testFromObject() throws IOException {
34          Contact contact = new Contact("bob", true, 44);
35  
36          StringWriter writer = new StringWriter();
37          JsonLibHandler handler = new JsonLibHandler();
38          handler.fromObject(contact, "success", writer);
39          String data = writer.toString();
40          assertTrue(data.startsWith("{"));
41          assertTrue(data.contains("\"age\":44"));
42          assertTrue(data.contains("\"important\":true"));
43          assertTrue(data.contains("\"name\":\"bob\""));
44      }
45  
46      public void testFromObjectArray() throws IOException {
47          Contact contact = new Contact("bob", true, 44);
48  
49          StringWriter writer = new StringWriter();
50          JsonLibHandler handler = new JsonLibHandler();
51          handler.fromObject(Arrays.asList(contact), "success", writer);
52  
53          String data = writer.toString();
54          assertTrue(data.startsWith("[{"));
55          assertTrue(data.contains("\"age\":44"));
56          assertTrue(data.contains("\"important\":true"));
57          assertTrue(data.contains("\"name\":\"bob\""));
58      }
59  
60      public void testToObject() throws IOException {
61          Contact contact = new Contact("bob", true, 44);
62  
63          Contact target = new Contact();
64          StringReader reader = new StringReader("{\"age\":44,\"important\":true,\"name\":\"bob\"}");
65          JsonLibHandler handler = new JsonLibHandler();
66          handler.toObject(reader, target);
67  
68          assertEquals(contact, target);
69      }
70  }