01: /*
02: * Copyright (C) 2006 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 07. July 2006 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.extended;
13:
14: import com.thoughtworks.xstream.converters.ConversionException;
15: import com.thoughtworks.xstream.converters.SingleValueConverter;
16:
17: import junit.framework.TestCase;
18:
19: import java.util.Map;
20:
21: /**
22: *
23: * @author Paul Hammant
24: */
25: public class ToStringConverterTest extends TestCase {
26:
27: public void testClaimsCanConvertRightType()
28: throws NoSuchMethodException {
29: SingleValueConverter converter = new ToStringConverter(
30: Foo.class);
31: assertTrue(converter.canConvert(Foo.class));
32: }
33:
34: public void testClaimsCantConvertWrongType()
35: throws NoSuchMethodException {
36: SingleValueConverter converter = new ToStringConverter(
37: Foo.class);
38: assertFalse(converter.canConvert(Map.class));
39: }
40:
41: public void testClaimsCantConvertWrongType2() {
42: try {
43: new ToStringConverter(Map.class);
44: fail("shoulda barfed");
45: } catch (NoSuchMethodException e) {
46: // expected.
47: }
48: }
49:
50: public void testCanConvertRightType() throws NoSuchMethodException {
51: SingleValueConverter converter = new ToStringConverter(
52: Foo.class);
53: assertTrue(converter.fromString("hello") instanceof Foo);
54: assertEquals("hello", ((Foo) converter.fromString("hello")).foo);
55: }
56:
57: public void testCanInnocentlyConvertWrongTypeToString()
58: throws NoSuchMethodException {
59: SingleValueConverter converter = new ToStringConverter(
60: Foo.class);
61: assertEquals("whoa", converter.toString("whoa"));
62: }
63:
64: public void testCantConvertWrongType() throws NoSuchMethodException {
65: SingleValueConverter converter = new ToStringConverter(
66: BadFoo1.class);
67: try {
68: converter.fromString("whoa");
69: fail("shoulda barfed");
70: } catch (ConversionException e) {
71: assertTrue(e.getMessage().startsWith(
72: "Unable to target single String param constructor"));
73: assertTrue(e.getCause() instanceof NullPointerException);
74: }
75: }
76:
77: public static class Foo {
78: final String foo;
79:
80: public Foo(String foo) {
81: this .foo = foo;
82: }
83:
84: public String toString() {
85: return foo;
86: }
87: }
88:
89: public static class BadFoo1 {
90: public BadFoo1(String string) {
91: throw new NullPointerException("abc");
92: }
93: }
94:
95: }
|