Start work on getting more code coverage in the unit tests

This commit is contained in:
Bradley Hilton 2017-01-04 19:05:36 -02:00
parent f0057a2079
commit 4b26ddf382
No known key found for this signature in database
GPG Key ID: 0666B2C24C43C358
6 changed files with 159 additions and 399 deletions

View File

@ -169,14 +169,14 @@ public class Util {
msg = msg.replace("%player%", p.getLastKnownName()) msg = msg.replace("%player%", p.getLastKnownName())
.replace("%uuid%", p.getUUID().toString()) .replace("%uuid%", p.getUUID().toString())
.replace("%reason%", p.getReason()) .replace("%reason%", p.getReason())
.replace("%jailer", p.getJailer()) .replace("%jailer%", p.getJailer())
.replace("%afktime%", Util.getDurationBreakdown(p.getAFKTime())); .replace("%afktime%", Util.getDurationBreakdown(p.getAFKTime()));
if(p.getRemainingTime() >= 0) { if(p.getRemainingTime() >= 0) {
msg = msg.replace("%timeinminutes%", String.valueOf(p.getRemainingTimeInMinutes())); msg = msg.replace("%timeinminutes%", String.valueOf(p.getRemainingTimeInMinutes()));
msg = msg.replace("%prettytime%", Util.getDurationBreakdown(p.getRemainingTime())); msg = msg.replace("%prettytime%", Util.getDurationBreakdown(p.getRemainingTime()));
}else { }else {
msg = msg.replace("%timeinminutes%", Lang.JAILEDFOREVERSIGN.get()); msg = msg.replace("%timeinminutes%", String.valueOf(-1));
msg = msg.replace("%prettytime%", Lang.JAILEDFOREVERSIGN.get()); 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 static org.mockito.Mockito.verify;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -27,7 +28,7 @@ public class TestJailCommands {
private static TestInstanceCreator creator; private static TestInstanceCreator creator;
private static JailMain main; private static JailMain main;
private static final String name = "TestJailCommands"; private static final String name = "TestJailCommands";
@BeforeClass @BeforeClass
public static void setUp() throws Exception { public static void setUp() throws Exception {
creator = new TestInstanceCreator(); creator = new TestInstanceCreator();
@ -44,7 +45,7 @@ public class TestJailCommands {
creator.tearDown(); creator.tearDown();
main = null; main = null;
} }
@Test @Test
public void testJailTimeCommand() throws Exception { public void testJailTimeCommand() throws Exception {
Long time = Util.getTime("30m"); Long time = Util.getTime("30m");
@ -53,21 +54,32 @@ public class TestJailCommands {
main.getPrisonerManager().prepareJail(main.getJailManager().getJail(name), null, creator.getPlayer(), p); main.getPrisonerManager().prepareJail(main.getJailManager().getJail(name), null, creator.getPlayer(), p);
assertTrue("The player " + creator.getPlayer().getName() + " is not jailed, checked by UUID.", main.getJailManager().isPlayerJailed(creator.getPlayer().getUniqueId())); assertTrue("The player " + creator.getPlayer().getName() + " is not jailed, checked by UUID.", main.getJailManager().isPlayerJailed(creator.getPlayer().getUniqueId()));
assertTrue("The player " + creator.getPlayer().getName() + " is not jailed, checked by username.", main.getJailManager().isPlayerJailedByLastKnownUsername(creator.getPlayer().getName())); assertTrue("The player " + creator.getPlayer().getName() + " is not jailed, checked by username.", main.getJailManager().isPlayerJailedByLastKnownUsername(creator.getPlayer().getName()));
//jail time show graywolf336 // jail time show graywolf336
assertTrue("The command failed.", main.onCommand(creator.getCommandSender(), null, "jail", new String[] { "time", "show", creator.getPlayer().getName() })); assertTrue("The command failed.", main.onCommand(creator.getCommandSender(), null, "jail", new String[] { "time", "show", creator.getPlayer().getName() }));
verify(creator.getCommandSender(), atLeast(1)).sendMessage(ChatColor.DARK_GREEN + "graywolf336 has 30 minutes remaining."); verify(creator.getCommandSender(), atLeast(1)).sendMessage(ChatColor.DARK_GREEN + "graywolf336 has 30 minutes remaining.");
//jail time add graywolf336 30m // jail time add graywolf336 30m
assertTrue("The command failed.", main.onCommand(creator.getCommandSender(), null, "jail", new String[] { "time", "add", creator.getPlayer().getName(), "30m" })); assertTrue("The command failed.", main.onCommand(creator.getCommandSender(), null, "jail", new String[] { "time", "add", creator.getPlayer().getName(), "30m" }));
verify(creator.getCommandSender(), atLeast(1)).sendMessage(ChatColor.DARK_GREEN + "graywolf336 has 60 minutes remaining."); verify(creator.getCommandSender(), atLeast(1)).sendMessage(ChatColor.DARK_GREEN + "graywolf336 has 60 minutes remaining.");
//jail time remove graywolf336 10m // jail time remove graywolf336 10m
assertTrue("The command failed.", main.onCommand(creator.getCommandSender(), null, "jail", new String[] { "time", "remove", creator.getPlayer().getName(), "10m" })); assertTrue("The command failed.", main.onCommand(creator.getCommandSender(), null, "jail", new String[] { "time", "remove", creator.getPlayer().getName(), "10m" }));
verify(creator.getCommandSender(), atLeast(1)).sendMessage(ChatColor.DARK_GREEN + "graywolf336 has 50 minutes remaining."); verify(creator.getCommandSender(), atLeast(1)).sendMessage(ChatColor.DARK_GREEN + "graywolf336 has 50 minutes remaining.");
//jail time set graywolf336 25m // jail time set graywolf336 25m
assertTrue("The command failed.", main.onCommand(creator.getCommandSender(), null, "jail", new String[] { "time", "set", creator.getPlayer().getName(), "25m" })); 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."); 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; package test.java.com.graywolf336.jail;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; 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.JailMain;
import com.graywolf336.jail.Util; import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@ -93,7 +95,7 @@ public class TestJailLanguage {
assertEquals(colorize("&cYou can not be afk while being jailed."), Lang.AFKKICKMESSAGE.get()); assertEquals(colorize("&cYou can not be afk while being jailed."), Lang.AFKKICKMESSAGE.get());
assertEquals(colorize("&cgraywolf336 is already jailed."), Lang.ALREADYJAILED.get("graywolf336")); assertEquals(colorize("&cgraywolf336 is already jailed."), Lang.ALREADYJAILED.get("graywolf336"));
assertEquals(colorize("&9graywolf336 has been jailed forever for: &cSome cool reason."), Lang.BROADCASTMESSAGEFOREVER.get(new String[] { "graywolf336", "Some cool reason." })); assertEquals(colorize("&9graywolf336 has been jailed forever for: &cSome cool reason."), Lang.BROADCASTMESSAGEFOREVER.get(new String[] { "graywolf336", "Some cool reason." }));
assertEquals(colorize("&9graywolf336 has been jailed for 60 minutes for: &cSome cool reason."), Lang.BROADCASTMESSAGEFORMINUTES.get(new String[] { "graywolf336", "60", "Some cool reason."})); assertEquals(colorize("&9graywolf336 has been jailed for 60 minutes for: &cSome cool reason."), Lang.BROADCASTMESSAGEFORMINUTES.get(new String[] { "graywolf336", "60", "Some cool reason." }));
assertEquals(colorize("&9graywolf336 has been unjailed by console."), Lang.BROADCASTUNJAILING.get(new String[] { "graywolf336", "console" })); assertEquals(colorize("&9graywolf336 has been unjailed by console."), Lang.BROADCASTUNJAILING.get(new String[] { "graywolf336", "console" }));
assertEquals(colorize("&cJailing graywolf336 was cancelled by another plugin and they did not leave you a message."), Lang.CANCELLEDBYANOTHERPLUGIN.get("graywolf336")); assertEquals(colorize("&cJailing graywolf336 was cancelled by another plugin and they did not leave you a message."), Lang.CANCELLEDBYANOTHERPLUGIN.get("graywolf336"));
assertEquals(colorize("&cThat player can not be jailed."), Lang.CANTBEJAILED.get()); assertEquals(colorize("&cThat player can not be jailed."), Lang.CANTBEJAILED.get());
@ -161,6 +163,23 @@ public class TestJailLanguage {
assertEquals(colorize("&aYour handcuffs have been removed."), Lang.UNHANDCUFFED.get()); 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) { private String colorize(String msg) {
return ChatColor.translateAlternateColorCodes('&', msg); return ChatColor.translateAlternateColorCodes('&', msg);
} }

View File

@ -1,6 +1,7 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -18,6 +19,7 @@ import com.graywolf336.jail.Util;
public class TestUtilClass { public class TestUtilClass {
private static List<String> list; private static List<String> list;
private static String[] array;
private static Vector bottomCorner; private static Vector bottomCorner;
private static Vector topCorner; private static Vector topCorner;
@ -27,6 +29,7 @@ public class TestUtilClass {
list.add(Material.SEEDS.toString()); list.add(Material.SEEDS.toString());
list.add("coal_ore"); list.add("coal_ore");
list.add("torch"); list.add("torch");
array = new String[] { Material.SEEDS.toString(), "coal_ore", "torch" };
bottomCorner = new Vector(-10.50, 50.25, 100.00); bottomCorner = new Vector(-10.50, 50.25, 100.00);
topCorner = new Vector(50, 100, 250); topCorner = new Vector(50, 100, 250);
} }
@ -56,6 +59,26 @@ public class TestUtilClass {
assertFalse(Util.isInsideAB(halfAndHalf, bottomCorner, topCorner)); 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 @Test
public void testInList() { public void testInList() {
assertTrue(Util.isStringInsideList("seeds", list)); assertTrue(Util.isStringInsideList("seeds", list));
@ -70,6 +93,21 @@ public class TestUtilClass {
assertFalse(Util.isStringInsideList(Material.BEDROCK.toString(), list)); 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 @Test
public void testNoFormat() throws Exception { public void testNoFormat() throws Exception {
assertEquals(60000L, Util.getTime("1"), 0); assertEquals(60000L, Util.getTime("1"), 0);
@ -109,7 +147,7 @@ public class TestUtilClass {
assertEquals(1L, Util.getTime("60m", TimeUnit.HOURS), 0); assertEquals(1L, Util.getTime("60m", TimeUnit.HOURS), 0);
assertEquals(6L, Util.getTime("6d", TimeUnit.DAYS), 0); assertEquals(6L, Util.getTime("6d", TimeUnit.DAYS), 0);
} }
@Test @Test
public void testDurationBreakdown() { public void testDurationBreakdown() {
assertEquals("1s", Util.getDurationBreakdown(1000)); assertEquals("1s", Util.getDurationBreakdown(1000));
@ -118,4 +156,21 @@ public class TestUtilClass {
assertEquals("1d0h0m0s", Util.getDurationBreakdown(86400000)); assertEquals("1d0h0m0s", Util.getDurationBreakdown(86400000));
assertEquals("1d1h1m1s", Util.getDurationBreakdown(90061000)); 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,336 +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 int clear(int i, int i2) {
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(int i) {
return false;
}
@Override
public boolean contains(Material material) {
return false;
}
@Override
public boolean contains(ItemStack itemStack) {
return false;
}
@Override
public boolean contains(int i, int i1) {
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(int i) {
return null;
}
@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(int i) {
return 0;
}
@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(int i) {
}
@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;
}
@SuppressWarnings("deprecation")
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].getTypeId() != 0) {
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.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.UUID; import java.util.UUID;
@ -32,6 +33,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemFactory; import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemFactory;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.permissions.Permission; import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
@ -57,6 +60,7 @@ public class TestInstanceCreator {
private JailMain main; private JailMain main;
private Server mockServer; private Server mockServer;
private Player mockPlayer; private Player mockPlayer;
private PlayerInventory mockPlayerInventory;
private World mockWorld; private World mockWorld;
private CommandSender mockSender, mockPlayerSender; private CommandSender mockSender, mockPlayerSender;
private ConsoleCommandSender consoleSender; private ConsoleCommandSender consoleSender;
@ -70,7 +74,7 @@ public class TestInstanceCreator {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean setup() { public boolean setup() {
r = new Random(); r = new Random();
try { try {
pluginDirectory.mkdirs(); pluginDirectory.mkdirs();
Assert.assertTrue(pluginDirectory.exists()); Assert.assertTrue(pluginDirectory.exists());
@ -161,23 +165,22 @@ public class TestInstanceCreator {
when(mockServer.getPluginManager()).thenReturn(mockPluginManager); when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer( when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer(new Answer<World>() {
new Answer<World>() { public World answer(InvocationOnMock invocation) throws Throwable {
public World answer(InvocationOnMock invocation) throws Throwable { WorldCreator arg;
WorldCreator arg; try {
try { arg = (WorldCreator) invocation.getArguments()[0];
arg = (WorldCreator) invocation.getArguments()[0]; } catch (Exception e) {
} catch (Exception e) { return null;
return null; }
} // Add special case for creating null worlds.
// Add special case for creating null worlds. // Not sure I like doing it this way, but this is a special
// Not sure I like doing it this way, but this is a special case // case
if (arg.name().equalsIgnoreCase("nullworld")) { if (arg.name().equalsIgnoreCase("nullworld"))
return MockWorldFactory.makeNewNullMockWorld(arg.name(), arg.environment(), arg.type()); return MockWorldFactory.makeNewNullMockWorld(arg.name(), arg.environment(), arg.type());
} return MockWorldFactory.makeNewMockWorld(arg.name(), arg.environment(), arg.type());
return MockWorldFactory.makeNewMockWorld(arg.name(), arg.environment(), arg.type()); }
} });
});
when(mockServer.unloadWorld(anyString(), anyBoolean())).thenReturn(true); when(mockServer.unloadWorld(anyString(), anyBoolean())).thenReturn(true);
@ -186,10 +189,9 @@ public class TestInstanceCreator {
when(bt.getTaskId()).thenReturn(r.nextInt()); when(bt.getTaskId()).thenReturn(r.nextInt());
when(bt.getOwner()).thenReturn(main); when(bt.getOwner()).thenReturn(main);
when(bt.isSync()).thenReturn(false); when(bt.isSync()).thenReturn(false);
BukkitScheduler mockScheduler = mock(BukkitScheduler.class); BukkitScheduler mockScheduler = mock(BukkitScheduler.class);
when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong())). when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong())).thenAnswer(new Answer<BukkitTask>() {
thenAnswer(new Answer<BukkitTask>() {
public BukkitTask answer(InvocationOnMock invocation) throws Throwable { public BukkitTask answer(InvocationOnMock invocation) throws Throwable {
Runnable arg; Runnable arg;
try { try {
@ -199,9 +201,9 @@ public class TestInstanceCreator {
} }
arg.run(); arg.run();
return bt; 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 { public BukkitTask answer(InvocationOnMock invocation) throws Throwable {
Runnable arg; Runnable arg;
try { try {
@ -211,9 +213,9 @@ public class TestInstanceCreator {
} }
arg.run(); arg.run();
return bt; 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 { public BukkitTask answer(InvocationOnMock invocation) throws Throwable {
Runnable arg; Runnable arg;
try { try {
@ -223,7 +225,8 @@ public class TestInstanceCreator {
} }
arg.run(); arg.run();
return bt; return bt;
}}); }
});
when(mockServer.getScheduler()).thenReturn(mockScheduler); when(mockServer.getScheduler()).thenReturn(mockScheduler);
// Set server // Set server
@ -270,7 +273,13 @@ public class TestInstanceCreator {
when(mockSender.addAttachment(main)).thenReturn(null); when(mockSender.addAttachment(main)).thenReturn(null);
when(mockSender.isOp()).thenReturn(true); 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); mockPlayer = mock(Player.class);
UUID playerId = UUID.fromString("062c14ba-4c47-4757-911b-bbf9a60dab7b"); UUID playerId = UUID.fromString("062c14ba-4c47-4757-911b-bbf9a60dab7b");
when(mockPlayer.getUniqueId()).thenReturn(playerId); when(mockPlayer.getUniqueId()).thenReturn(playerId);
@ -281,13 +290,14 @@ public class TestInstanceCreator {
when(mockPlayer.hasPermission(anyString())).thenReturn(true); when(mockPlayer.hasPermission(anyString())).thenReturn(true);
when(mockPlayer.hasPermission(Matchers.isA(Permission.class))).thenReturn(true); when(mockPlayer.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(mockPlayer.isOp()).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(mockPlayer.getLocation()).thenReturn(new Location(mockWorld, 23, 70, -242));
when(mockServer.getPlayer("graywolf336")).thenReturn(mockPlayer); when(mockServer.getPlayer("graywolf336")).thenReturn(mockPlayer);
when(mockServer.getPlayer(playerId)).thenReturn(mockPlayer); when(mockServer.getPlayer(playerId)).thenReturn(mockPlayer);
players.add(playerId); 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; mockPlayerSender = mockPlayer;
when(mockPlayerSender.getServer()).thenReturn(mockServer); when(mockPlayerSender.getServer()).thenReturn(mockServer);
when(mockPlayerSender.getName()).thenReturn("graywolf336"); when(mockPlayerSender.getName()).thenReturn("graywolf336");
@ -336,12 +346,12 @@ public class TestInstanceCreator {
deleteFolder(serverDirectory); deleteFolder(serverDirectory);
return true; return true;
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean addMockPlayer(String name, UUID id) { public boolean addMockPlayer(String name, UUID id) {
if(players.contains(id)) { if (players.contains(id))
return false; return false;
}else { else {
Player anotherPlayer = mock(Player.class); Player anotherPlayer = mock(Player.class);
when(anotherPlayer.getUniqueId()).thenReturn(id); when(anotherPlayer.getUniqueId()).thenReturn(id);
when(anotherPlayer.getName()).thenReturn(name); when(anotherPlayer.getName()).thenReturn(name);
@ -351,7 +361,7 @@ public class TestInstanceCreator {
when(anotherPlayer.hasPermission(anyString())).thenReturn(true); when(anotherPlayer.hasPermission(anyString())).thenReturn(true);
when(anotherPlayer.hasPermission(Matchers.isA(Permission.class))).thenReturn(true); when(anotherPlayer.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(anotherPlayer.isOp()).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(anotherPlayer.getLocation()).thenReturn(new Location(mockWorld, 56, 85, -2420));
when(mockServer.getPlayer(name)).thenReturn(anotherPlayer); when(mockServer.getPlayer(name)).thenReturn(anotherPlayer);
when(mockServer.getPlayer(id)).thenReturn(anotherPlayer); when(mockServer.getPlayer(id)).thenReturn(anotherPlayer);
@ -359,11 +369,11 @@ public class TestInstanceCreator {
return true; return true;
} }
} }
public boolean addJail(String name) { public boolean addJail(String name) {
if(main.getJailManager().isValidJail(name)) { if (main.getJailManager().isValidJail(name))
return false; return false;
}else { else {
Jail j = new Jail(main, name); Jail j = new Jail(main, name);
j.setWorld("world"); j.setWorld("world");
j.setMaxPoint(new int[] { r.nextInt(), r.nextInt(256), r.nextInt() }); j.setMaxPoint(new int[] { r.nextInt(), r.nextInt(256), r.nextInt() });
@ -376,36 +386,36 @@ public class TestInstanceCreator {
} }
public JailMain getMain() { public JailMain getMain() {
return this.main; return main;
} }
public Server getServer() { public Server getServer() {
return this.mockServer; return mockServer;
} }
public CommandSender getCommandSender() { public CommandSender getCommandSender() {
return this.mockSender; return mockSender;
} }
public Player getPlayer() { public Player getPlayer() {
return this.mockPlayer; return mockPlayer;
} }
public CommandSender getPlayerCommandSender() { public CommandSender getPlayerCommandSender() {
return this.mockPlayerSender; return mockPlayerSender;
} }
public ConsoleCommandSender getConsoleSender() { public ConsoleCommandSender getConsoleSender() {
return this.consoleSender; return consoleSender;
} }
private void deleteFolder(File folder) { private void deleteFolder(File folder) {
File[] files = folder.listFiles(); File[] files = folder.listFiles();
if(files != null) { if (files != null) {
for(File f: files) { for (File f : files) {
if(f.isDirectory()) { if (f.isDirectory()) {
deleteFolder(f); deleteFolder(f);
}else { } else {
f.delete(); f.delete();
} }
} }