ProtocolLib/src/test/java/com/comphenix/protocol/reflect/accessors/AccessorsTest.java

77 lines
2.1 KiB
Java
Raw Normal View History

package com.comphenix.protocol.reflect.accessors;
import com.comphenix.protocol.reflect.ExactReflection;
2022-02-20 12:16:11 +01:00
import org.junit.jupiter.api.Test;
2023-06-05 15:42:55 +02:00
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AccessorsTest {
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
@Test
2023-06-05 15:42:55 +02:00
void testField() {
2023-05-12 16:35:34 +02:00
Player player = new Player(123, "ABC");
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
Field id = assertDoesNotThrow(() -> ExactReflection.fromClass(Player.class, true).getField("id"));
Field name = assertDoesNotThrow(() -> ExactReflection.fromClass(Player.class, true).getField("name"));
2023-05-12 16:35:34 +02:00
assertDoesNotThrow(() -> Accessors.getFieldAccessor(id).set(player, 15));
assertDoesNotThrow(() -> Accessors.getFieldAccessor(name).set(player, "MODIFIED"));
2023-05-12 16:35:34 +02:00
assertEquals(15, player.getId());
assertEquals("MODIFIED", player.getName());
}
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
@Test
2023-06-05 15:42:55 +02:00
void testMethod() {
2023-05-12 16:35:34 +02:00
Player player = new Player(123, "ABC");
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
assertDoesNotThrow(() -> Accessors.getMethodAccessor(player.getClass(), "setId", int.class).invoke(player, 0));
assertEquals(0, player.getId());
}
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
@Test
2023-06-05 15:42:55 +02:00
void testConstructor() {
2023-05-12 16:35:34 +02:00
Player player = (Player) assertDoesNotThrow(() -> Accessors
.getConstructorAccessor(Player.class, int.class, String.class)
.invoke(12, "hi"));
assertEquals(12, player.getId());
assertEquals("hi", player.getName());
}
2023-05-12 16:35:34 +02:00
// --- Some classes we can use for testing ---
private static class Entity {
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
private int id;
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
public Entity(int id) {
this.id = id;
}
2023-05-12 16:35:34 +02:00
public int getId() {
return this.id;
}
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
@SuppressWarnings("unused")
private void setId(int value) {
this.id = value;
}
}
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
private static class Player extends Entity {
2022-02-20 12:16:11 +01:00
2023-05-12 16:35:34 +02:00
private final String name;
2023-05-12 16:35:34 +02:00
public Player(int id, String name) {
super(id);
this.name = name;
}
2023-05-12 16:35:34 +02:00
public String getName() {
return this.name;
}
}
}