View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.commons.beanutils2.converters;
20  
21  import static org.junit.jupiter.api.Assertions.assertEquals;
22  import static org.junit.jupiter.api.Assertions.assertThrows;
23  
24  import java.net.InetAddress;
25  import java.net.UnknownHostException;
26  
27  import org.apache.commons.beanutils2.ConversionException;
28  import org.junit.jupiter.api.BeforeEach;
29  import org.junit.jupiter.api.Test;
30  
31  /**
32   * Tests {@link InetAddressConverter}.
33   *
34   * @since 2.0.0
35   */
36  public class InetAddressConverterTest {
37  
38      private InetAddressConverter converter;
39  
40      @BeforeEach
41      public void before() {
42          converter = new InetAddressConverter();
43      }
44  
45      @Test
46      public void testConvertingIpv4() throws UnknownHostException {
47          final InetAddress expected = InetAddress.getByName("192.168.0.1");
48          final InetAddress actual = converter.convert(InetAddress.class, "192.168.0.1");
49  
50          assertEquals(expected, actual);
51      }
52  
53      @Test
54      public void testConvertingIpv6() throws UnknownHostException {
55          final InetAddress expected = InetAddress.getByName("2001:db8:0:1234:0:567:8:1");
56          final InetAddress actual = converter.convert(InetAddress.class, "2001:db8:0:1234:0:567:8:1");
57  
58          assertEquals(expected, actual);
59      }
60  
61      @Test
62      public void testConvertingLocalhost() throws UnknownHostException {
63          final InetAddress expected = InetAddress.getByName("127.0.0.1");
64          final InetAddress actual = converter.convert(InetAddress.class, "localhost");
65  
66          assertEquals(expected, actual);
67      }
68  
69      @Test
70      public void testInvalidIp() {
71          assertThrows(ConversionException.class, () -> converter.convert(InetAddress.class, "512.512.512.512"));
72      }
73  
74      @Test
75      public void testText() {
76          assertThrows(ConversionException.class, () -> converter.convert(InetAddress.class, "Hello, world!"));
77      }
78  }