Merge pull request #143 from graywolf336/more-tests-for-coverage

[WIP] More Unit Tests for Better Code Coverage
This commit is contained in:
Bradley Hilton 2019-04-15 11:11:33 -05:00 committed by GitHub
commit e75e735cef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 159 additions and 368 deletions

View File

@ -169,14 +169,14 @@ public class Util {
msg = msg.replace("%player%", p.getLastKnownName())
.replace("%uuid%", p.getUUID().toString())
.replace("%reason%", p.getReason())
.replace("%jailer", p.getJailer())
.replace("%jailer%", p.getJailer())
.replace("%afktime%", Util.getDurationBreakdown(p.getAFKTime()));
if(p.getRemainingTime() >= 0) {
msg = msg.replace("%timeinminutes%", String.valueOf(p.getRemainingTimeInMinutes()));
msg = msg.replace("%prettytime%", Util.getDurationBreakdown(p.getRemainingTime()));
}else {
msg = msg.replace("%timeinminutes%", Lang.JAILEDFOREVERSIGN.get());
msg = msg.replace("%timeinminutes%", String.valueOf(-1));
msg = msg.replace("%prettytime%", Lang.JAILEDFOREVERSIGN.get());
}

View File

@ -7,6 +7,7 @@ import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.verify;
import org.bukkit.ChatColor;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@ -70,4 +71,15 @@ public class TestJailCommands {
assertTrue("The command failed.", main.onCommand(creator.getCommandSender(), null, "jail", new String[] { "time", "set", creator.getPlayer().getName(), "25m" }));
verify(creator.getCommandSender(), atLeast(1)).sendMessage(ChatColor.DARK_GREEN + "graywolf336 has 25 minutes remaining.");
}
@Test
public void testJailCreateCommands() {
assertTrue("The command jailed.", main.onCommand(creator.getPlayer(), null, "jail", new String[] { "create", "testingUno" }));
verify(creator.getPlayer(), atLeast(1)).sendMessage(ChatColor.AQUA + "----------Jail Zone Creation----------");
verify(creator.getPlayer(), atLeast(1)).sendMessage(ChatColor.GREEN + "First, you must select jail cuboid. Select the first point of the cuboid by right clicking on the block with your clay brick. DO NOT FORGET TO MARK THE FLOOR AND CEILING TOO!");
verify(creator.getPlayer(), atLeast(1)).sendMessage(ChatColor.AQUA + "--------------------------------------");
ItemStack wand = Util.getWand();
verify(creator.getPlayer().getInventory(), atLeast(1)).addItem(wand);
}
}

View File

@ -1,6 +1,7 @@
package test.java.com.graywolf336.jail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@ -19,6 +20,7 @@ import test.java.com.graywolf336.jail.util.TestInstanceCreator;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Lang;
@RunWith(PowerMockRunner.class)
@ -161,6 +163,23 @@ public class TestJailLanguage {
assertEquals(colorize("&aYour handcuffs have been removed."), Lang.UNHANDCUFFED.get());
}
@Test
public void testReplacingAllVariables() {
String template = "%player% (%uuid%) was jailed for %timeinminutes% minutes by %jailer% for \"%reason%\" and has been afk for %afktime%. Pretty time: %prettytime%";
String resultGreaterThanZero = Util.replaceAllVariables(new Prisoner("e7965e93-df29-4440-9960-feeaef3fe772", "graywolf336", true, 60000L, "Notch", "code coverage"), template);
String resultLessThanZero = Util.replaceAllVariables(new Prisoner("e7965e93-df29-4440-9960-feeaef3fe772", "graywolf336", true, -1, "Notch", "code coverage"), template);
String[] resultArray = Util.replaceAllVariables(new Prisoner("e7965e93-df29-4440-9960-feeaef3fe772", "graywolf336", true, -1, "Notch", "code coverage"), new String[] { template });
assertEquals("graywolf336 (e7965e93-df29-4440-9960-feeaef3fe772) was jailed for 1 minutes by Notch for \"code coverage\" and has been afk for 0s. Pretty time: 1m0s", resultGreaterThanZero);
assertEquals("graywolf336 (e7965e93-df29-4440-9960-feeaef3fe772) was jailed for -1 minutes by Notch for \"code coverage\" and has been afk for 0s. Pretty time: §cfor life", resultLessThanZero);
assertArrayEquals(new String[] { "graywolf336 (e7965e93-df29-4440-9960-feeaef3fe772) was jailed for -1 minutes by Notch for \"code coverage\" and has been afk for 0s. Pretty time: §cfor life" }, resultArray);
}
@Test
public void testDurationBreakdownJailedForever() {
assertEquals("§cfor life", Util.getDurationBreakdown(-1));
}
private String colorize(String msg) {
return ChatColor.translateAlternateColorCodes('&', msg);
}

View File

@ -1,6 +1,7 @@
package test.java.com.graywolf336.jail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -18,6 +19,7 @@ import com.graywolf336.jail.Util;
public class TestUtilClass {
private static List<String> list;
private static String[] array;
private static Vector bottomCorner;
private static Vector topCorner;
@ -27,6 +29,7 @@ public class TestUtilClass {
list.add(Material.WHEAT_SEEDS.toString());
list.add("coal_ore");
list.add("torch");
array = new String[] { Material.SEEDS.toString(), "coal_ore", "torch" };
bottomCorner = new Vector(-10.50, 50.25, 100.00);
topCorner = new Vector(50, 100, 250);
}
@ -56,6 +59,26 @@ public class TestUtilClass {
assertFalse(Util.isInsideAB(halfAndHalf, bottomCorner, topCorner));
}
@Test
public void testFirstGreaterThanSecond() {
Vector greaterFirst = new Vector(10, 86, -104);
assertFalse(Util.isInsideAB(greaterFirst, topCorner, bottomCorner));
}
@Test
public void testInArray() {
assertTrue(Util.isStringInsideArray("seeds", array));
assertTrue(Util.isStringInsideArray(Material.COAL_ORE.toString(), array));
assertTrue(Util.isStringInsideArray("tOrCh", array));
}
@Test
public void testNotInArray() {
assertFalse(Util.isStringInsideArray("dirt", array));
assertFalse(Util.isStringInsideArray("SAND", array));
assertFalse(Util.isStringInsideArray(Material.BEDROCK.toString(), array));
}
@Test
public void testInList() {
assertTrue(Util.isStringInsideList("wheat_seeds", list));
@ -70,6 +93,21 @@ public class TestUtilClass {
assertFalse(Util.isStringInsideList(Material.BEDROCK.toString(), list));
}
@Test
public void testCorrectStringFromArray() {
assertEquals("SEEDS,coal_ore,torch", Util.getStringFromArray(",", array));
}
@Test
public void testCorrectStringFromList() {
assertEquals("SEEDS,coal_ore,torch", Util.getStringFromList(",", list));
}
@Test
public void testColorfulMessage() {
assertEquals("§4Col§lor§fful §1messages", Util.getColorfulMessage("&4Col&lor&fful &1messages"));
}
@Test
public void testNoFormat() throws Exception {
assertEquals(60000L, Util.getTime("1"), 0);
@ -118,4 +156,21 @@ public class TestUtilClass {
assertEquals("1d0h0m0s", Util.getDurationBreakdown(86400000));
assertEquals("1d1h1m1s", Util.getDurationBreakdown(90061000));
}
@Test(expected = Exception.class)
public void testInvalidDateFormat() throws Exception {
Util.getTime("abcdefg");
}
@Test(expected = Exception.class)
public void testInvalidUpdateSigns() throws Exception {
Util.updateSignLinesCache(new String[] {});
}
@Test
public void testUpdateSignsCache() throws Exception {
String[] lines = new String[] { "test1", "test2", "test3", "test4" };
Util.updateSignLinesCache(lines);
assertArrayEquals(lines, Util.getSignLines());
}
}

View File

@ -1,305 +0,0 @@
package test.java.com.graywolf336.jail.util;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
public class MockPlayerInventory implements PlayerInventory {
private int armorSize = 4, inventorySize = 36;
private ItemStack[] armorContents = new ItemStack[armorSize];
private ItemStack[] inventoryContents = new ItemStack[inventorySize];
@Override
public ItemStack[] getArmorContents() {
return armorContents;
}
@Override
public ItemStack getHelmet() {
return armorContents[0];
}
@Override
public ItemStack getChestplate() {
return armorContents[1];
}
@Override
public ItemStack getLeggings() {
return armorContents[2];
}
@Override
public ItemStack getBoots() {
return armorContents[3];
}
@Override
public void setArmorContents(ItemStack[] itemStacks) {
this.armorContents = itemStacks;
}
@Override
public void setHelmet(ItemStack itemStack) {
this.armorContents[0] = itemStack;
}
@Override
public void setChestplate(ItemStack itemStack) {
this.armorContents[1] = itemStack;
}
@Override
public void setLeggings(ItemStack itemStack) {
this.armorContents[2] = itemStack;
}
@Override
public void setBoots(ItemStack itemStack) {
this.armorContents[3] = itemStack;
}
@Override
public ItemStack getItemInHand() {
return null;
}
@Override
public void setItemInHand(ItemStack itemStack) {
}
@Override
public int getHeldItemSlot() {
return 0;
}
@Override
public HumanEntity getHolder() {
return null;
}
@Override
public int getSize() {
return inventoryContents.length + armorContents.length;
}
@Override
public String getName() {
return null;
}
@Override
public ItemStack getItem(int i) {
if (i >= 0 && i < inventorySize) {
return inventoryContents[i];
} else if (i >= inventorySize
&& i < inventorySize + armorSize) {
return armorContents[i - inventorySize];
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
@Override
public void setItem(int i, ItemStack itemStack) {
if (i >= 0 && i < inventorySize) {
inventoryContents[i] = itemStack;
} else if (i >= inventorySize
&& i < inventorySize + armorSize) {
armorContents[i - inventorySize] = itemStack;
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
@Override
public HashMap<Integer, ItemStack> addItem(ItemStack... itemStacks) {
return null;
}
@Override
public HashMap<Integer, ItemStack> removeItem(ItemStack... itemStacks) {
return null;
}
@Override
public ItemStack[] getContents() {
return this.inventoryContents;
}
@Override
public void setContents(ItemStack[] itemStacks) {
this.inventoryContents = itemStacks;
}
@Override
public boolean contains(Material material) {
return false;
}
@Override
public boolean contains(ItemStack itemStack) {
return false;
}
@Override
public boolean contains(Material material, int i) {
return false;
}
@Override
public boolean contains(ItemStack itemStack, int i) {
return false;
}
@Override
public HashMap<Integer, ? extends ItemStack> all(Material material) {
return null;
}
@Override
public HashMap<Integer, ? extends ItemStack> all(ItemStack itemStack) {
return null;
}
@Override
public int first(Material material) {
return 0;
}
@Override
public int first(ItemStack itemStack) {
return 0;
}
@Override
public int firstEmpty() {
return 0;
}
@Override
public void remove(Material material) {
}
@Override
public void remove(ItemStack itemStack) {
}
@Override
public void clear(int i) {
inventoryContents[i] = null;
}
@Override
public void clear() {
}
@Override
public List<HumanEntity> getViewers() {
return null;
}
@Override
public String getTitle() {
return null;
}
@Override
public InventoryType getType() {
return null;
}
@Override
public ListIterator<ItemStack> iterator() {
return null;
}
@Override
public int getMaxStackSize() {
return 0;
}
@Override
public void setMaxStackSize(int i) {
}
@Override
public ListIterator<ItemStack> iterator(int i) {
return null;
}
@Override
public boolean containsAtLeast(final ItemStack itemStack, final int i) {
return false;
}
private static Map<String, Object> makeMap(ItemStack[] items) {
Map<String, Object> contents = new LinkedHashMap<String, Object>(
items.length);
for (int i = 0; i < items.length; i++) {
if (items[i] != null && items[i].getType() != Material.AIR) {
contents.put(Integer.valueOf(i).toString(), items[i]);
}
}
return contents;
}
public String toString() {
return "{\"inventoryContents\":" + makeMap(getContents())
+ ",\"armorContents\":" + makeMap(getArmorContents()) + "}";
}
public void setHeldItemSlot(int slot) {
}
public Location getLocation() {
return null;
}
public ItemStack getItemInMainHand() {
return null;
}
public ItemStack getItemInOffHand() {
return null;
}
public void setItemInMainHand(ItemStack item) {
}
public void setItemInOffHand(ItemStack item) {
}
public void setExtraContents(ItemStack[] contents) {
}
public ItemStack[] getExtraContents() {
return null;
}
public void setStorageContents(ItemStack[] contents) {
}
public ItemStack[] getStorageContents() {
return null;
}
}

View File

@ -14,6 +14,7 @@ import static org.powermock.api.support.membermodification.MemberModifier.suppre
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;
@ -32,6 +33,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemFactory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
@ -57,6 +60,7 @@ public class TestInstanceCreator {
private JailMain main;
private Server mockServer;
private Player mockPlayer;
private PlayerInventory mockPlayerInventory;
private World mockWorld;
private CommandSender mockSender, mockPlayerSender;
private ConsoleCommandSender consoleSender;
@ -161,8 +165,7 @@ public class TestInstanceCreator {
when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer(
new Answer<World>() {
when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer(new Answer<World>() {
public World answer(InvocationOnMock invocation) throws Throwable {
WorldCreator arg;
try {
@ -171,10 +174,10 @@ public class TestInstanceCreator {
return null;
}
// Add special case for creating null worlds.
// Not sure I like doing it this way, but this is a special case
if (arg.name().equalsIgnoreCase("nullworld")) {
// Not sure I like doing it this way, but this is a special
// case
if (arg.name().equalsIgnoreCase("nullworld"))
return MockWorldFactory.makeNewNullMockWorld(arg.name(), arg.environment(), arg.type());
}
return MockWorldFactory.makeNewMockWorld(arg.name(), arg.environment(), arg.type());
}
});
@ -188,8 +191,7 @@ public class TestInstanceCreator {
when(bt.isSync()).thenReturn(false);
BukkitScheduler mockScheduler = mock(BukkitScheduler.class);
when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong())).
thenAnswer(new Answer<BukkitTask>() {
when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong())).thenAnswer(new Answer<BukkitTask>() {
public BukkitTask answer(InvocationOnMock invocation) throws Throwable {
Runnable arg;
try {
@ -199,9 +201,9 @@ public class TestInstanceCreator {
}
arg.run();
return bt;
}});
when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class))).
thenAnswer(new Answer<BukkitTask>() {
}
});
when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class))).thenAnswer(new Answer<BukkitTask>() {
public BukkitTask answer(InvocationOnMock invocation) throws Throwable {
Runnable arg;
try {
@ -211,9 +213,9 @@ public class TestInstanceCreator {
}
arg.run();
return bt;
}});
when(mockScheduler.runTaskTimerAsynchronously(any(Plugin.class), any(Runnable.class), anyLong(), anyLong())).
thenAnswer(new Answer<BukkitTask>() {
}
});
when(mockScheduler.runTaskTimerAsynchronously(any(Plugin.class), any(Runnable.class), anyLong(), anyLong())).thenAnswer(new Answer<BukkitTask>() {
public BukkitTask answer(InvocationOnMock invocation) throws Throwable {
Runnable arg;
try {
@ -223,7 +225,8 @@ public class TestInstanceCreator {
}
arg.run();
return bt;
}});
}
});
when(mockServer.getScheduler()).thenReturn(mockScheduler);
// Set server
@ -270,7 +273,13 @@ public class TestInstanceCreator {
when(mockSender.addAttachment(main)).thenReturn(null);
when(mockSender.isOp()).thenReturn(true);
// Init our player, who is op and who has all permissions (with name of graywolf336)
// Mock the player's inventory
// TODO: Mock the methods when needed
mockPlayerInventory = mock(PlayerInventory.class);
when(mockPlayerInventory.addItem(Matchers.isA(ItemStack.class))).thenReturn(new HashMap<Integer, ItemStack>());
// Init our player, who is op and who has all permissions (with name
// of graywolf336)
mockPlayer = mock(Player.class);
UUID playerId = UUID.fromString("062c14ba-4c47-4757-911b-bbf9a60dab7b");
when(mockPlayer.getUniqueId()).thenReturn(playerId);
@ -281,13 +290,14 @@ public class TestInstanceCreator {
when(mockPlayer.hasPermission(anyString())).thenReturn(true);
when(mockPlayer.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(mockPlayer.isOp()).thenReturn(true);
when(mockPlayer.getInventory()).thenReturn(new MockPlayerInventory());
when(mockPlayer.getInventory()).thenReturn(mockPlayerInventory);
when(mockPlayer.getLocation()).thenReturn(new Location(mockWorld, 23, 70, -242));
when(mockServer.getPlayer("graywolf336")).thenReturn(mockPlayer);
when(mockServer.getPlayer(playerId)).thenReturn(mockPlayer);
players.add(playerId);
// Init our second command sender, but this time is an instance of a player
// Init our second command sender, but this time is an instance of a
// player
mockPlayerSender = mockPlayer;
when(mockPlayerSender.getServer()).thenReturn(mockServer);
when(mockPlayerSender.getName()).thenReturn("graywolf336");
@ -339,9 +349,9 @@ public class TestInstanceCreator {
@SuppressWarnings("deprecation")
public boolean addMockPlayer(String name, UUID id) {
if(players.contains(id)) {
if (players.contains(id))
return false;
}else {
else {
Player anotherPlayer = mock(Player.class);
when(anotherPlayer.getUniqueId()).thenReturn(id);
when(anotherPlayer.getName()).thenReturn(name);
@ -351,7 +361,7 @@ public class TestInstanceCreator {
when(anotherPlayer.hasPermission(anyString())).thenReturn(true);
when(anotherPlayer.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(anotherPlayer.isOp()).thenReturn(true);
when(anotherPlayer.getInventory()).thenReturn(new MockPlayerInventory());
when(anotherPlayer.getInventory()).thenReturn(mockPlayerInventory);
when(anotherPlayer.getLocation()).thenReturn(new Location(mockWorld, 56, 85, -2420));
when(mockServer.getPlayer(name)).thenReturn(anotherPlayer);
when(mockServer.getPlayer(id)).thenReturn(anotherPlayer);
@ -361,9 +371,9 @@ public class TestInstanceCreator {
}
public boolean addJail(String name) {
if(main.getJailManager().isValidJail(name)) {
if (main.getJailManager().isValidJail(name))
return false;
}else {
else {
Jail j = new Jail(main, name);
j.setWorld("world");
j.setMaxPoint(new int[] { r.nextInt(), r.nextInt(256), r.nextInt() });
@ -376,27 +386,27 @@ public class TestInstanceCreator {
}
public JailMain getMain() {
return this.main;
return main;
}
public Server getServer() {
return this.mockServer;
return mockServer;
}
public CommandSender getCommandSender() {
return this.mockSender;
return mockSender;
}
public Player getPlayer() {
return this.mockPlayer;
return mockPlayer;
}
public CommandSender getPlayerCommandSender() {
return this.mockPlayerSender;
return mockPlayerSender;
}
public ConsoleCommandSender getConsoleSender() {
return this.consoleSender;
return consoleSender;
}
private void deleteFolder(File folder) {