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
20 package org.apache.bcel.generic;
21
22 import static org.junit.jupiter.api.Assertions.assertEquals;
23 import static org.junit.jupiter.api.Assertions.assertThrows;
24
25 import org.apache.bcel.util.ByteSequence;
26 import org.junit.jupiter.api.Test;
27
28 /**
29 * Tests {@link IINC}.
30 */
31 class IINCTest {
32
33 /**
34 * {@code dump} emits the wide-form increment with {@code writeShort}, so the constructor and {@link IINC#setIncrement}
35 * must reject an increment outside the signed-short range instead of truncating it to a different value.
36 */
37 @Test
38 void testRejectsIncrementAboveShort() {
39 assertEquals(Short.MAX_VALUE, new IINC(0, Short.MAX_VALUE).getIncrement());
40 assertThrows(ClassGenException.class, () -> new IINC(0, Short.MAX_VALUE + 1));
41 }
42
43 @Test
44 void testRejectsIncrementBelowShort() {
45 assertEquals(Short.MIN_VALUE, new IINC(0, Short.MIN_VALUE).getIncrement());
46 assertThrows(ClassGenException.class, () -> new IINC(0, Short.MIN_VALUE - 1));
47 }
48
49 @Test
50 void testSetIncrementRejectsOutOfRange() {
51 final IINC iinc = new IINC(0, 1);
52 assertThrows(ClassGenException.class, () -> iinc.setIncrement(40000));
53 }
54
55 /**
56 * The increment of a wide {@code iinc} is a signed short, so a value inside that range must round-trip through
57 * {@code dump}.
58 */
59 @Test
60 void testWideIncrementRoundTrips() throws Exception {
61 final IINC iinc = new IINC(0, 30000);
62 try (ByteSequence bytes = new ByteSequence(iinc.dumpToByteArray())) {
63 assertEquals(30000, ((IINC) Instruction.readInstruction(bytes)).getIncrement());
64 }
65 }
66 }