Moved to Mockito 2 and PowerMock

This commit is contained in:
tastybento 2019-08-04 21:44:46 -07:00
parent be673fa527
commit 44cbd81320
17 changed files with 264 additions and 189 deletions

View File

@ -42,7 +42,7 @@ public class PVPListener extends FlagListener {
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityDamage(EntityDamageByEntityEvent e) { public void onEntityDamage(EntityDamageByEntityEvent e) {
if (e.getEntity() instanceof Player && getPlugin().getIWM().inWorld(e.getEntity().getLocation())) { if (e.getEntity() instanceof Player && getPlugin().getIWM().inWorld(e.getEntity().getWorld())) {
// Allow self damage // Allow self damage
if (e.getEntity().equals(e.getDamager())) { if (e.getEntity().equals(e.getDamager())) {
return; return;
@ -121,7 +121,7 @@ public class PVPListener extends FlagListener {
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onSplashPotionSplash(final PotionSplashEvent e) { public void onSplashPotionSplash(final PotionSplashEvent e) {
if (e.getEntity().getShooter() instanceof Player && getPlugin().getIWM().inWorld(e.getEntity().getLocation())) { if (e.getEntity().getShooter() instanceof Player && getPlugin().getIWM().inWorld(e.getEntity().getWorld())) {
User user = User.getInstance((Player)e.getEntity().getShooter()); User user = User.getInstance((Player)e.getEntity().getShooter());
// Run through affected entities and cancel the splash if any are a protected player // Run through affected entities and cancel the splash if any are a protected player
e.setCancelled(e.getAffectedEntities().stream().anyMatch(le -> blockPVP(user, le, e, getFlag(e.getEntity().getWorld())))); e.setCancelled(e.getAffectedEntities().stream().anyMatch(le -> blockPVP(user, le, e, getFlag(e.getEntity().getWorld()))));
@ -164,7 +164,7 @@ public class PVPListener extends FlagListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onLingeringPotionSplash(final LingeringPotionSplashEvent e) { public void onLingeringPotionSplash(final LingeringPotionSplashEvent e) {
// Try to get the shooter // Try to get the shooter
if (e.getEntity().getShooter() instanceof Player && getPlugin().getIWM().inWorld(e.getEntity().getLocation())) { if (e.getEntity().getShooter() instanceof Player && getPlugin().getIWM().inWorld(e.getEntity().getWorld())) {
// Store it and remove it when the effect is gone (Entity ID, UUID of throwing player) // Store it and remove it when the effect is gone (Entity ID, UUID of throwing player)
thrownPotions.put(e.getAreaEffectCloud().getEntityId(), ((Player)e.getEntity().getShooter()).getUniqueId()); thrownPotions.put(e.getAreaEffectCloud().getEntityId(), ((Player)e.getEntity().getShooter()).getUniqueId());
Bukkit.getScheduler().runTaskLater(getPlugin(), () -> thrownPotions.remove(e.getAreaEffectCloud().getEntityId()), e.getAreaEffectCloud().getDuration()); Bukkit.getScheduler().runTaskLater(getPlugin(), () -> thrownPotions.remove(e.getAreaEffectCloud().getEntityId()), e.getAreaEffectCloud().getDuration());

View File

@ -119,8 +119,8 @@ public class CleanSuperFlatListener extends FlagListener {
&& e.getChunk().getBlock(0, 2, 0).getType().equals(Material.DIRT) && e.getChunk().getBlock(0, 2, 0).getType().equals(Material.DIRT)
&& e.getChunk().getBlock(0, 3, 0).getType().equals(Material.GRASS_BLOCK)) && e.getChunk().getBlock(0, 3, 0).getType().equals(Material.GRASS_BLOCK))
|| (world.getEnvironment().equals(Environment.NETHER) && (!plugin.getIWM().isNetherGenerate(world) || (world.getEnvironment().equals(Environment.NETHER) && (!plugin.getIWM().isNetherGenerate(world)
|| !plugin.getIWM().isNetherIslands(world))) || !plugin.getIWM().isNetherIslands(world)))
|| (world.getEnvironment().equals(Environment.THE_END) && (!plugin.getIWM().isEndGenerate(world) || (world.getEnvironment().equals(Environment.THE_END) && (!plugin.getIWM().isEndGenerate(world)
|| !plugin.getIWM().isEndIslands(world)))); || !plugin.getIWM().isEndIslands(world))));
} }
} }

View File

@ -35,7 +35,7 @@ public class EnderChestListener extends FlagListener {
private boolean checkEnderChest(Player player, Material type) { private boolean checkEnderChest(Player player, Material type) {
if (type.equals(Material.ENDER_CHEST) if (type.equals(Material.ENDER_CHEST)
&& getIWM().inWorld(player.getLocation()) && getIWM().inWorld(player.getWorld())
&& !player.isOp() && !player.isOp()
&& !player.hasPermission(getPlugin().getIWM().getPermissionPrefix(player.getWorld()) + "craft.enderchest") && !player.hasPermission(getPlugin().getIWM().getPermissionPrefix(player.getWorld()) + "craft.enderchest")
&& !Flags.ENDER_CHEST.isSetForWorld(player.getWorld())) { && !Flags.ENDER_CHEST.isSetForWorld(player.getWorld())) {

View File

@ -102,7 +102,7 @@ public class InvincibleVisitorsListener extends FlagListener implements ClickHan
public void onVisitorGetDamage(EntityDamageEvent e) { public void onVisitorGetDamage(EntityDamageEvent e) {
World world = e.getEntity().getWorld(); World world = e.getEntity().getWorld();
if (!(e.getEntity() instanceof Player) if (!(e.getEntity() instanceof Player)
|| !getIWM().inWorld(e.getEntity().getLocation()) || !getIWM().inWorld(world)
|| !getIWM().getIvSettings(world).contains(e.getCause().name()) || !getIWM().getIvSettings(world).contains(e.getCause().name())
|| getIslands().userIsOnIsland(world, User.getInstance(e.getEntity()))) { || getIslands().userIsOnIsland(world, User.getInstance(e.getEntity()))) {
return; return;

View File

@ -29,6 +29,8 @@ public class TreesGrowingOutsideRangeListener extends FlagListener {
} }
// Now, run through all the blocks that will be generated and if there is no protected island at their location, turn them into AIR. // Now, run through all the blocks that will be generated and if there is no protected island at their location, turn them into AIR.
e.getBlocks().stream().filter(blockState -> !getIslands().getProtectedIslandAt(blockState.getLocation()).isPresent()).forEach(blockState -> blockState.setType(Material.AIR)); e.getBlocks().stream()
.filter(blockState -> !getIslands().getProtectedIslandAt(blockState.getLocation()).isPresent())
.forEach(blockState -> blockState.setType(Material.AIR));
} }
} }

View File

@ -3,11 +3,12 @@ package world.bentobox.bentobox.api.commands.admin;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.Mockito.any;
import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.Mockito.eq;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -199,13 +200,13 @@ public class AdminSetrankCommandTest {
Island island = mock(Island.class); Island island = mock(Island.class);
when(island.getRank(any())).thenReturn(RanksManager.SUB_OWNER_RANK); when(island.getRank(any())).thenReturn(RanksManager.SUB_OWNER_RANK);
when(im.getIsland(any(), any(UUID.class))).thenReturn(island); when(im.getIsland(any(), any(UUID.class))).thenReturn(island);
when(user.getTranslation(anyString())).thenReturn("sub-owner", "member"); when(user.getTranslation(any())).thenReturn("sub-owner", "member");
assertTrue(c.execute(user, "", Arrays.asList("tastybento", "member"))); assertTrue(c.execute(user, "", Arrays.asList("tastybento", "member")));
verify(user).sendMessage("commands.admin.setrank.rank-set", verify(user).sendMessage(eq("commands.admin.setrank.rank-set"),
"[from]", eq("[from]"),
"sub-owner", eq("sub-owner"),
"[to]", eq("[to]"),
"member"); eq("member"));
} }
/** /**
@ -214,7 +215,7 @@ public class AdminSetrankCommandTest {
@Test @Test
public void testTabCompleteUserStringListOfString() { public void testTabCompleteUserStringListOfString() {
when(rm.getRanks()).thenReturn(Collections.singletonMap("visitor", 0)); when(rm.getRanks()).thenReturn(Collections.singletonMap("visitor", 0));
when(user.getTranslation(anyString())).thenReturn("visitor"); when(user.getTranslation(any())).thenReturn("visitor");
Optional<List<String>> result = c.tabComplete(user, "", Collections.emptyList()); Optional<List<String>> result = c.tabComplete(user, "", Collections.emptyList());
assertTrue(result.isPresent()); assertTrue(result.isPresent());
result.ifPresent(list -> { result.ifPresent(list -> {

View File

@ -1,6 +1,3 @@
/**
*
*/
package world.bentobox.bentobox.api.commands.admin; package world.bentobox.bentobox.api.commands.admin;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -8,6 +5,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.Mockito.any;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -76,6 +74,7 @@ public class AdminSetspawnCommandTest {
when(user.getUniqueId()).thenReturn(uuid); when(user.getUniqueId()).thenReturn(uuid);
when(user.getPlayer()).thenReturn(p); when(user.getPlayer()).thenReturn(p);
when(user.getName()).thenReturn("tastybento"); when(user.getName()).thenReturn("tastybento");
when(user.getLocation()).thenReturn(mock(Location.class));
User.setPlugin(plugin); User.setPlugin(plugin);
// Parent command has no aliases // Parent command has no aliases
@ -90,10 +89,10 @@ public class AdminSetspawnCommandTest {
// Player has island to begin with // Player has island to begin with
im = mock(IslandsManager.class); im = mock(IslandsManager.class);
when(im.hasIsland(Mockito.any(), Mockito.any(UUID.class))).thenReturn(true); when(im.hasIsland(any(), any(UUID.class))).thenReturn(true);
when(im.hasIsland(Mockito.any(), Mockito.any(User.class))).thenReturn(true); when(im.hasIsland(any(), any(User.class))).thenReturn(true);
when(im.isOwner(Mockito.any(),Mockito.any())).thenReturn(true); when(im.isOwner(any(),any())).thenReturn(true);
when(im.getOwner(Mockito.any(),Mockito.any())).thenReturn(uuid); when(im.getOwner(any(),any())).thenReturn(uuid);
when(plugin.getIslands()).thenReturn(im); when(plugin.getIslands()).thenReturn(im);
@ -104,7 +103,7 @@ public class AdminSetspawnCommandTest {
// Locales // Locales
LocalesManager lm = mock(LocalesManager.class); LocalesManager lm = mock(LocalesManager.class);
when(lm.get(Mockito.any(), Mockito.any())).thenReturn("mock translation"); when(lm.get(any(), any())).thenReturn("mock translation");
when(plugin.getLocalesManager()).thenReturn(lm); when(plugin.getLocalesManager()).thenReturn(lm);
// Return the reference (USE THIS IN THE FUTURE) // Return the reference (USE THIS IN THE FUTURE)
when(user.getTranslation(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class)); when(user.getTranslation(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));
@ -147,7 +146,7 @@ public class AdminSetspawnCommandTest {
public void testExecuteUserStringListOfString() { public void testExecuteUserStringListOfString() {
Island island = mock(Island.class); Island island = mock(Island.class);
Optional<Island> oi = Optional.of(island); Optional<Island> oi = Optional.of(island);
when(im.getIslandAt(Mockito.any(Location.class))).thenReturn(oi); when(im.getIslandAt(any(Location.class))).thenReturn(oi);
AdminSetspawnCommand c = new AdminSetspawnCommand(ac); AdminSetspawnCommand c = new AdminSetspawnCommand(ac);
assertTrue(c.execute(user, "setspawn", Collections.emptyList())); assertTrue(c.execute(user, "setspawn", Collections.emptyList()));
Mockito.verify(user).getTranslation("commands.admin.setspawn.confirmation"); Mockito.verify(user).getTranslation("commands.admin.setspawn.confirmation");
@ -158,7 +157,7 @@ public class AdminSetspawnCommandTest {
*/ */
@Test @Test
public void testExecuteUserStringListOfStringNoIsland() { public void testExecuteUserStringListOfStringNoIsland() {
when(im.getIslandAt(Mockito.any(Location.class))).thenReturn(Optional.empty()); when(im.getIslandAt(any(Location.class))).thenReturn(Optional.empty());
AdminSetspawnCommand c = new AdminSetspawnCommand(ac); AdminSetspawnCommand c = new AdminSetspawnCommand(ac);
assertFalse(c.execute(user, "setspawn", Collections.emptyList())); assertFalse(c.execute(user, "setspawn", Collections.emptyList()));
Mockito.verify(user).sendMessage("commands.admin.setspawn.no-island-here"); Mockito.verify(user).sendMessage("commands.admin.setspawn.no-island-here");
@ -172,7 +171,7 @@ public class AdminSetspawnCommandTest {
Island island = mock(Island.class); Island island = mock(Island.class);
when(island.isSpawn()).thenReturn(true); when(island.isSpawn()).thenReturn(true);
Optional<Island> oi = Optional.of(island); Optional<Island> oi = Optional.of(island);
when(im.getIslandAt(Mockito.any(Location.class))).thenReturn(oi); when(im.getIslandAt(any(Location.class))).thenReturn(oi);
AdminSetspawnCommand c = new AdminSetspawnCommand(ac); AdminSetspawnCommand c = new AdminSetspawnCommand(ac);
assertTrue(c.execute(user, "setspawn", Collections.emptyList())); assertTrue(c.execute(user, "setspawn", Collections.emptyList()));
Mockito.verify(user).sendMessage("commands.admin.setspawn.already-spawn"); Mockito.verify(user).sendMessage("commands.admin.setspawn.already-spawn");

View File

@ -2,8 +2,8 @@ package world.bentobox.bentobox.api.commands.island;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.Mockito.any;
import static org.mockito.Matchers.eq; import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -19,7 +19,6 @@ import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
@ -174,7 +173,6 @@ public class IslandResetCommandTest {
verify(user).sendMessage("commands.island.reset.none-left"); verify(user).sendMessage("commands.island.reset.none-left");
} }
@Ignore("NPE with ChatColor")
@Test @Test
public void testNoConfirmationRequired() throws IOException { public void testNoConfirmationRequired() throws IOException {
IslandResetCommand irc = new IslandResetCommand(ic); IslandResetCommand irc = new IslandResetCommand(ic);

View File

@ -2,7 +2,7 @@ package world.bentobox.bentobox.listeners.flags.settings;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -25,7 +25,6 @@ import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
@ -60,6 +59,8 @@ public class MobSpawnListenerTest {
private Cow cow; private Cow cow;
@Mock @Mock
private IslandWorldManager iwm; private IslandWorldManager iwm;
@Mock
private LivingEntity livingEntity;
@Before @Before
public void setUp() { public void setUp() {
@ -123,13 +124,15 @@ public class MobSpawnListenerTest {
// Default - plugin is loaded // Default - plugin is loaded
when(plugin.isLoaded()).thenReturn(true); when(plugin.isLoaded()).thenReturn(true);
// Living Entity
when(livingEntity.getLocation()).thenReturn(location);
} }
@Ignore //FIXME don't know why it is failing
@Test @Test
public void testNotLoaded() { public void testNotLoaded() {
when(plugin.isLoaded()).thenReturn(false); when(plugin.isLoaded()).thenReturn(false);
CreatureSpawnEvent e = new CreatureSpawnEvent(null, SpawnReason.NATURAL); CreatureSpawnEvent e = new CreatureSpawnEvent(livingEntity, SpawnReason.NATURAL);
MobSpawnListener l = new MobSpawnListener(); MobSpawnListener l = new MobSpawnListener();
assertFalse(l.onNaturalMobSpawn(e)); assertFalse(l.onNaturalMobSpawn(e));
assertFalse(e.isCancelled()); assertFalse(e.isCancelled());

View File

@ -3,12 +3,13 @@ package world.bentobox.bentobox.listeners.flags.settings;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.Mockito.any;
import static org.mockito.Matchers.eq; import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.Mockito.times;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -44,6 +45,7 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitScheduler;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -210,6 +212,11 @@ public class PVPListenerTest {
} }
@After
public void tearDown() {
User.clearUsers();
}
private void wrongWorld() { private void wrongWorld() {
when(iwm.inWorld(any(World.class))).thenReturn(false); when(iwm.inWorld(any(World.class))).thenReturn(false);
when(iwm.inWorld(any(Location.class))).thenReturn(false); when(iwm.inWorld(any(Location.class))).thenReturn(false);
@ -303,8 +310,7 @@ public class PVPListenerTest {
e = new EntityDamageByEntityEvent(damager, damagee, EntityDamageEvent.DamageCause.ENTITY_ATTACK, e = new EntityDamageByEntityEvent(damager, damagee, EntityDamageEvent.DamageCause.ENTITY_ATTACK,
new EnumMap<>(ImmutableMap.of(DamageModifier.BASE, 0D)), new EnumMap<>(ImmutableMap.of(DamageModifier.BASE, 0D)),
new EnumMap<DamageModifier, Function<? super Double, Double>>(ImmutableMap.of(DamageModifier.BASE, Functions.constant(-0.0)))); new EnumMap<DamageModifier, Function<? super Double, Double>>(ImmutableMap.of(DamageModifier.BASE, Functions.constant(-0.0))));
when(iwm.inWorld(any(World.class))).thenReturn(false); wrongWorld();
when(iwm.inWorld(any(Location.class))).thenReturn(false);
new PVPListener().onEntityDamage(e); new PVPListener().onEntityDamage(e);
assertFalse(e.isCancelled()); assertFalse(e.isCancelled());
} }
@ -314,6 +320,28 @@ public class PVPListenerTest {
*/ */
@Test @Test
public void testOnEntityDamageOnVisitorByZombieVisitorProtected() { public void testOnEntityDamageOnVisitorByZombieVisitorProtected() {
Entity damager = mock(Zombie.class);
Entity damagee = mock(Player.class);
when(damager.getWorld()).thenReturn(world);
when(damagee.getWorld()).thenReturn(world);
// Protect visitors
when(iwm.getIvSettings(world)).thenReturn(Collections.singletonList("ENTITY_ATTACK"));
// This player is a visitor
when(im.userIsOnIsland(any(), any())).thenReturn(false);
EntityDamageByEntityEvent e = new EntityDamageByEntityEvent(damager, damagee, EntityDamageEvent.DamageCause.ENTITY_ATTACK,
new EnumMap<>(ImmutableMap.of(DamageModifier.BASE, 0D)),
new EnumMap<DamageModifier, Function<? super Double, Double>>(ImmutableMap.of(DamageModifier.BASE, Functions.constant(-0.0))));
new PVPListener().onEntityDamage(e);
assertTrue(e.isCancelled());
}
/**
* Test method for {@link PVPListener#onEntityDamage(org.bukkit.event.entity.EntityDamageByEntityEvent)}.
*/
@Test
public void testOnEntityDamageOnVisitorByZombieVisitorProtectedWrongWorld() {
Entity damager = mock(Zombie.class); Entity damager = mock(Zombie.class);
Entity damagee = mock(Player.class); Entity damagee = mock(Player.class);
World world = mock(World.class); World world = mock(World.class);
@ -328,17 +356,10 @@ public class PVPListenerTest {
// This player is a visitor // This player is a visitor
when(im.userIsOnIsland(any(), any())).thenReturn(false); when(im.userIsOnIsland(any(), any())).thenReturn(false);
EntityDamageByEntityEvent e = new EntityDamageByEntityEvent(damager, damagee, EntityDamageEvent.DamageCause.ENTITY_ATTACK, EntityDamageByEntityEvent e = new EntityDamageByEntityEvent(damager, damagee, EntityDamageEvent.DamageCause.ENTITY_ATTACK,
new EnumMap<>(ImmutableMap.of(DamageModifier.BASE, 0D)), new EnumMap<>(ImmutableMap.of(DamageModifier.BASE, 0D)),
new EnumMap<DamageModifier, Function<? super Double, Double>>(ImmutableMap.of(DamageModifier.BASE, Functions.constant(-0.0)))); new EnumMap<DamageModifier, Function<? super Double, Double>>(ImmutableMap.of(DamageModifier.BASE, Functions.constant(-0.0))));
new PVPListener().onEntityDamage(e); wrongWorld();
assertTrue(e.isCancelled());
// Wrong world
e = new EntityDamageByEntityEvent(damager, damagee, EntityDamageEvent.DamageCause.ENTITY_ATTACK,
new EnumMap<>(ImmutableMap.of(DamageModifier.BASE, 0D)),
new EnumMap<DamageModifier, Function<? super Double, Double>>(ImmutableMap.of(DamageModifier.BASE, Functions.constant(-0.0))));
when(iwm.inWorld(any(World.class))).thenReturn(false);
when(iwm.inWorld(any(Location.class))).thenReturn(false);
new PVPListener().onEntityDamage(e); new PVPListener().onEntityDamage(e);
assertFalse(e.isCancelled()); assertFalse(e.isCancelled());
} }
@ -805,10 +826,11 @@ public class PVPListenerTest {
LingeringPotionSplashEvent e = new LingeringPotionSplashEvent(tp, cloud); LingeringPotionSplashEvent e = new LingeringPotionSplashEvent(tp, cloud);
new PVPListener().onLingeringPotionSplash(e); new PVPListener().onLingeringPotionSplash(e);
// Verify // Verify
verify(player, Mockito.times(3)).getUniqueId(); verify(player, times(3)).getUniqueId();
verify(cloud).getEntityId(); verify(cloud).getEntityId();
verify(tp, Mockito.times(2)).getShooter(); verify(tp, times(2)).getShooter();
PowerMockito.verifyStatic(Bukkit.class); PowerMockito.verifyStatic(Bukkit.class);
Bukkit.getScheduler();
} }
/** /**
@ -826,6 +848,7 @@ public class PVPListenerTest {
verify(cloud, never()).getEntityId(); verify(cloud, never()).getEntityId();
verify(tp).getShooter(); verify(tp).getShooter();
PowerMockito.verifyStatic(Bukkit.class, never()); PowerMockito.verifyStatic(Bukkit.class, never());
Bukkit.getScheduler();
} }
/** /**

View File

@ -1,9 +1,11 @@
package world.bentobox.bentobox.listeners.flags.worldsettings; package world.bentobox.bentobox.listeners.flags.worldsettings;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Matchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.HashMap; import java.util.HashMap;
@ -27,6 +29,7 @@ import org.eclipse.jdt.annotation.Nullable;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
@ -50,11 +53,16 @@ import world.bentobox.bentobox.util.Util;
@PrepareForTest({Bukkit.class, BentoBox.class, Util.class }) @PrepareForTest({Bukkit.class, BentoBox.class, Util.class })
public class CleanSuperFlatListenerTest { public class CleanSuperFlatListenerTest {
@Mock
private World world; private World world;
@Mock
private Block block; private Block block;
@Mock
private Chunk chunk; private Chunk chunk;
@Mock
private IslandWorldManager iwm; private IslandWorldManager iwm;
private CleanSuperFlatListener l; private CleanSuperFlatListener l;
@Mock
private BukkitScheduler scheduler; private BukkitScheduler scheduler;
/** /**
@ -70,24 +78,23 @@ public class CleanSuperFlatListenerTest {
when(plugin.isLoaded()).thenReturn(true); when(plugin.isLoaded()).thenReturn(true);
// World // World
world = mock(World.class);
when(world.getEnvironment()).thenReturn(World.Environment.NORMAL); when(world.getEnvironment()).thenReturn(World.Environment.NORMAL);
when(world.getName()).thenReturn("world");
PowerMockito.mockStatic(Util.class); PowerMockito.mockStatic(Util.class);
when(Util.getWorld(Mockito.any())).thenReturn(world); when(Util.getWorld(any())).thenReturn(world);
// World Settings // World Settings
iwm = mock(IslandWorldManager.class);
when(plugin.getIWM()).thenReturn(iwm); when(plugin.getIWM()).thenReturn(iwm);
WorldSettings ws = mock(WorldSettings.class); WorldSettings ws = mock(WorldSettings.class);
when(iwm.getWorldSettings(Mockito.any())).thenReturn(ws); when(iwm.getWorldSettings(any())).thenReturn(ws);
Map<String, Boolean> worldFlags = new HashMap<>(); Map<String, Boolean> worldFlags = new HashMap<>();
when(ws.getWorldFlags()).thenReturn(worldFlags); when(ws.getWorldFlags()).thenReturn(worldFlags);
when(iwm.inWorld(Mockito.any(World.class))).thenReturn(true); when(iwm.inWorld(any(World.class))).thenReturn(true);
when(iwm.isNetherGenerate(Mockito.any())).thenReturn(true); when(iwm.isNetherGenerate(any())).thenReturn(true);
when(iwm.isEndGenerate(Mockito.any())).thenReturn(true); when(iwm.isEndGenerate(any())).thenReturn(true);
when(iwm.isNetherIslands(Mockito.any())).thenReturn(true); when(iwm.isNetherIslands(any())).thenReturn(true);
when(iwm.isEndIslands(Mockito.any())).thenReturn(true); when(iwm.isEndIslands(any())).thenReturn(true);
when(iwm.isUseOwnGenerator(any())).thenReturn(false); when(iwm.isUseOwnGenerator(any())).thenReturn(false);
when(iwm.getAddon(any())).thenReturn(Optional.empty()); when(iwm.getAddon(any())).thenReturn(Optional.empty());
@ -95,14 +102,12 @@ public class CleanSuperFlatListenerTest {
PowerMockito.mockStatic(Bukkit.class); PowerMockito.mockStatic(Bukkit.class);
ItemFactory itemF = mock(ItemFactory.class); ItemFactory itemF = mock(ItemFactory.class);
ItemMeta im = mock(ItemMeta.class); ItemMeta im = mock(ItemMeta.class);
when(itemF.getItemMeta(Mockito.any())).thenReturn(im); when(itemF.getItemMeta(any())).thenReturn(im);
when(Bukkit.getItemFactory()).thenReturn(itemF); when(Bukkit.getItemFactory()).thenReturn(itemF);
// Default is that flag is active // Default is that flag is active
Flags.CLEAN_SUPER_FLAT.setSetting(world, true); Flags.CLEAN_SUPER_FLAT.setSetting(world, true);
// Default is that chunk has bedrock // Default is that chunk has bedrock
chunk = mock(Chunk.class);
when(chunk.getWorld()).thenReturn(world); when(chunk.getWorld()).thenReturn(world);
block = mock(Block.class);
// Super flat! // Super flat!
when(block.getType()).thenReturn(Material.BEDROCK, Material.DIRT, Material.DIRT, Material.GRASS_BLOCK); when(block.getType()).thenReturn(Material.BEDROCK, Material.DIRT, Material.DIRT, Material.GRASS_BLOCK);
when(chunk.getBlock(Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(block); when(chunk.getBlock(Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(block);
@ -112,7 +117,6 @@ public class CleanSuperFlatListenerTest {
l.onBentoBoxReady(mock(BentoBoxReadyEvent.class)); l.onBentoBoxReady(mock(BentoBoxReadyEvent.class));
// Scheduler // Scheduler
scheduler = mock(BukkitScheduler.class);
when(Bukkit.getScheduler()).thenReturn(scheduler); when(Bukkit.getScheduler()).thenReturn(scheduler);
// Addons Manager // Addons Manager
@ -138,7 +142,7 @@ public class CleanSuperFlatListenerTest {
ChunkLoadEvent e = new ChunkLoadEvent(chunk, false); ChunkLoadEvent e = new ChunkLoadEvent(chunk, false);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler, Mockito.never()).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler, never()).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
} }
/** /**
@ -148,7 +152,7 @@ public class CleanSuperFlatListenerTest {
public void testOnChunkLoadBedrock() { public void testOnChunkLoadBedrock() {
ChunkLoadEvent e = new ChunkLoadEvent(chunk, false); ChunkLoadEvent e = new ChunkLoadEvent(chunk, false);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
} }
/** /**
@ -160,7 +164,7 @@ public class CleanSuperFlatListenerTest {
ChunkLoadEvent e = new ChunkLoadEvent(chunk, false); ChunkLoadEvent e = new ChunkLoadEvent(chunk, false);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler, Mockito.never()).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler, never()).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
} }
/** /**
@ -171,15 +175,15 @@ public class CleanSuperFlatListenerTest {
when(world.getEnvironment()).thenReturn(World.Environment.NETHER); when(world.getEnvironment()).thenReturn(World.Environment.NETHER);
ChunkLoadEvent e = new ChunkLoadEvent(chunk, false); ChunkLoadEvent e = new ChunkLoadEvent(chunk, false);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
when(iwm.isNetherGenerate(Mockito.any())).thenReturn(false); when(iwm.isNetherGenerate(any())).thenReturn(false);
when(iwm.isNetherIslands(Mockito.any())).thenReturn(true); when(iwm.isNetherIslands(any())).thenReturn(true);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
when(iwm.isNetherGenerate(Mockito.any())).thenReturn(true); when(iwm.isNetherGenerate(any())).thenReturn(true);
when(iwm.isNetherIslands(Mockito.any())).thenReturn(false); when(iwm.isNetherIslands(any())).thenReturn(false);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
} }
/** /**
@ -190,15 +194,15 @@ public class CleanSuperFlatListenerTest {
when(world.getEnvironment()).thenReturn(World.Environment.THE_END); when(world.getEnvironment()).thenReturn(World.Environment.THE_END);
ChunkLoadEvent e = new ChunkLoadEvent(chunk, false); ChunkLoadEvent e = new ChunkLoadEvent(chunk, false);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
when(iwm.isEndGenerate(Mockito.any())).thenReturn(false); when(iwm.isEndGenerate(any())).thenReturn(false);
when(iwm.isEndIslands(Mockito.any())).thenReturn(true); when(iwm.isEndIslands(any())).thenReturn(true);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
when(iwm.isEndGenerate(Mockito.any())).thenReturn(true); when(iwm.isEndGenerate(any())).thenReturn(true);
when(iwm.isEndIslands(Mockito.any())).thenReturn(false); when(iwm.isEndIslands(any())).thenReturn(false);
l.onChunkLoad(e); l.onChunkLoad(e);
Mockito.verify(scheduler).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L)); verify(scheduler).runTaskTimer(any(), any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
} }
} }

View File

@ -34,6 +34,7 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
@ -59,11 +60,17 @@ import world.bentobox.bentobox.util.Util;
@PrepareForTest({BentoBox.class, Util.class }) @PrepareForTest({BentoBox.class, Util.class })
public class EnderChestListenerTest { public class EnderChestListenerTest {
@Mock
private World world; private World world;
@Mock
private Player player; private Player player;
@Mock
private IslandWorldManager iwm; private IslandWorldManager iwm;
@Mock
private Notifier notifier; private Notifier notifier;
@Mock
private ItemStack item; private ItemStack item;
@Mock
private Block clickedBlock; private Block clickedBlock;
private Action action; private Action action;
@ -73,9 +80,6 @@ public class EnderChestListenerTest {
BentoBox plugin = mock(BentoBox.class); BentoBox plugin = mock(BentoBox.class);
Whitebox.setInternalState(BentoBox.class, "instance", plugin); Whitebox.setInternalState(BentoBox.class, "instance", plugin);
// World
world = mock(World.class);
// Owner // Owner
UUID uuid1 = UUID.randomUUID(); UUID uuid1 = UUID.randomUUID();
@ -99,7 +103,6 @@ public class EnderChestListenerTest {
when(Util.getWorld(any())).thenReturn(world); when(Util.getWorld(any())).thenReturn(world);
// World Settings // World Settings
iwm = mock(IslandWorldManager.class);
when(plugin.getIWM()).thenReturn(iwm); when(plugin.getIWM()).thenReturn(iwm);
WorldSettings ws = mock(WorldSettings.class); WorldSettings ws = mock(WorldSettings.class);
when(iwm.getWorldSettings(any())).thenReturn(ws); when(iwm.getWorldSettings(any())).thenReturn(ws);
@ -114,7 +117,6 @@ public class EnderChestListenerTest {
Flags.ENDER_CHEST.setSetting(world, false); Flags.ENDER_CHEST.setSetting(world, false);
// Sometimes use Mockito.withSettings().verboseLogging() // Sometimes use Mockito.withSettings().verboseLogging()
player = mock(Player.class);
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
when(player.getUniqueId()).thenReturn(uuid); when(player.getUniqueId()).thenReturn(uuid);
when(player.isOp()).thenReturn(false); when(player.isOp()).thenReturn(false);
@ -136,14 +138,11 @@ public class EnderChestListenerTest {
when(placeholdersManager.replacePlaceholders(any(), any())).thenAnswer(answer); when(placeholdersManager.replacePlaceholders(any(), any())).thenAnswer(answer);
// Notifier // Notifier
notifier = mock(Notifier.class);
when(plugin.getNotifier()).thenReturn(notifier); when(plugin.getNotifier()).thenReturn(notifier);
// Action, Item and clicked block // Action, Item and clicked block
action = Action.RIGHT_CLICK_BLOCK; action = Action.RIGHT_CLICK_BLOCK;
item = mock(ItemStack.class);
when(item.getType()).thenReturn(Material.ENDER_CHEST); when(item.getType()).thenReturn(Material.ENDER_CHEST);
clickedBlock = mock(Block.class);
when(clickedBlock.getLocation()).thenReturn(inside); when(clickedBlock.getLocation()).thenReturn(inside);
when(clickedBlock.getType()).thenReturn(Material.ENDER_CHEST); when(clickedBlock.getType()).thenReturn(Material.ENDER_CHEST);
// Addon // Addon

View File

@ -99,12 +99,15 @@ public class InvincibleVisitorsListenerTest {
// Sometimes use Mockito.withSettings().verboseLogging() // Sometimes use Mockito.withSettings().verboseLogging()
when(user.inWorld()).thenReturn(true); when(user.inWorld()).thenReturn(true);
when(user.getWorld()).thenReturn(mock(World.class)); when(user.getWorld()).thenReturn(mock(World.class));
when(player.getWorld()).thenReturn(mock(World.class));
when(user.getLocation()).thenReturn(mock(Location.class)); when(user.getLocation()).thenReturn(mock(Location.class));
when(player.getLocation()).thenReturn(mock(Location.class));
when(user.getPlayer()).thenReturn(player); when(user.getPlayer()).thenReturn(player);
when(user.hasPermission(Mockito.anyString())).thenReturn(true); when(user.hasPermission(Mockito.anyString())).thenReturn(true);
when(user.getTranslation(Mockito.anyString())).thenReturn("panel"); when(user.getTranslation(Mockito.anyString())).thenReturn("panel");
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
when(user.getUniqueId()).thenReturn(uuid); when(user.getUniqueId()).thenReturn(uuid);
when(player.getUniqueId()).thenReturn(uuid);
PowerMockito.mockStatic(Util.class); PowerMockito.mockStatic(Util.class);
when(Util.getWorld(any())).thenReturn(mock(World.class)); when(Util.getWorld(any())).thenReturn(mock(World.class));
@ -268,7 +271,9 @@ public class InvincibleVisitorsListenerTest {
@Test @Test
public void testOnVisitorGetDamageVoidPlayerHasIsland() { public void testOnVisitorGetDamageVoidPlayerHasIsland() {
// No island at this location
when(im.getIslandAt(any())).thenReturn(Optional.empty()); when(im.getIslandAt(any())).thenReturn(Optional.empty());
// Player has an island
when(im.hasIsland(any(), any(UUID.class))).thenReturn(true); when(im.hasIsland(any(), any(UUID.class))).thenReturn(true);
EntityDamageEvent e = new EntityDamageEvent(player, EntityDamageEvent.DamageCause.VOID, 0D); EntityDamageEvent e = new EntityDamageEvent(player, EntityDamageEvent.DamageCause.VOID, 0D);
// Player should be teleported to their island // Player should be teleported to their island

View File

@ -1,11 +1,8 @@
/**
*
*/
package world.bentobox.bentobox.listeners.flags.worldsettings; package world.bentobox.bentobox.listeners.flags.worldsettings;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -19,11 +16,9 @@ import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Enderman; import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.ItemFrame; import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile; import org.bukkit.entity.Projectile;
import org.bukkit.entity.Slime; import org.bukkit.entity.Slime;
@ -36,6 +31,7 @@ import org.bukkit.plugin.PluginManager;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
@ -60,7 +56,14 @@ import world.bentobox.bentobox.util.Util;
@PrepareForTest( {BentoBox.class, Flags.class, Util.class, Bukkit.class} ) @PrepareForTest( {BentoBox.class, Flags.class, Util.class, Bukkit.class} )
public class ItemFrameListenerTest { public class ItemFrameListenerTest {
private static Enderman enderman; @Mock
private Enderman enderman;
@Mock
private World world;
@Mock
private ItemFrame entity;
@Mock
private Location location;
@Before @Before
public void setUp() { public void setUp() {
@ -69,7 +72,6 @@ public class ItemFrameListenerTest {
Whitebox.setInternalState(BentoBox.class, "instance", plugin); Whitebox.setInternalState(BentoBox.class, "instance", plugin);
Server server = mock(Server.class); Server server = mock(Server.class);
World world = mock(World.class);
when(server.getLogger()).thenReturn(Logger.getAnonymousLogger()); when(server.getLogger()).thenReturn(Logger.getAnonymousLogger());
when(server.getWorld("world")).thenReturn(world); when(server.getWorld("world")).thenReturn(world);
when(server.getVersion()).thenReturn("BSB_Mocking"); when(server.getVersion()).thenReturn("BSB_Mocking");
@ -86,8 +88,7 @@ public class ItemFrameListenerTest {
SkullMeta skullMeta = mock(SkullMeta.class); SkullMeta skullMeta = mock(SkullMeta.class);
when(itemFactory.getItemMeta(any())).thenReturn(skullMeta); when(itemFactory.getItemMeta(any())).thenReturn(skullMeta);
when(Bukkit.getItemFactory()).thenReturn(itemFactory); when(Bukkit.getItemFactory()).thenReturn(itemFactory);
when(Bukkit.getLogger()).thenReturn(Logger.getAnonymousLogger()); // Location
Location location = mock(Location.class);
when(location.getWorld()).thenReturn(world); when(location.getWorld()).thenReturn(world);
when(location.getBlockX()).thenReturn(0); when(location.getBlockX()).thenReturn(0);
when(location.getBlockY()).thenReturn(0); when(location.getBlockY()).thenReturn(0);
@ -97,7 +98,6 @@ public class ItemFrameListenerTest {
FlagsManager flagsManager = new FlagsManager(plugin); FlagsManager flagsManager = new FlagsManager(plugin);
when(plugin.getFlagsManager()).thenReturn(flagsManager); when(plugin.getFlagsManager()).thenReturn(flagsManager);
// Worlds // Worlds
IslandWorldManager iwm = mock(IslandWorldManager.class); IslandWorldManager iwm = mock(IslandWorldManager.class);
when(iwm.inWorld(any(World.class))).thenReturn(true); when(iwm.inWorld(any(World.class))).thenReturn(true);
@ -106,7 +106,6 @@ public class ItemFrameListenerTest {
when(iwm.getAddon(any())).thenReturn(Optional.empty()); when(iwm.getAddon(any())).thenReturn(Optional.empty());
// Monsters and animals // Monsters and animals
enderman = mock(Enderman.class);
when(enderman.getLocation()).thenReturn(location); when(enderman.getLocation()).thenReturn(location);
when(enderman.getWorld()).thenReturn(world); when(enderman.getWorld()).thenReturn(world);
Slime slime = mock(Slime.class); Slime slime = mock(Slime.class);
@ -132,6 +131,11 @@ public class ItemFrameListenerTest {
PowerMockito.mockStatic(Util.class); PowerMockito.mockStatic(Util.class);
when(Util.getWorld(Mockito.any())).thenReturn(mock(World.class)); when(Util.getWorld(Mockito.any())).thenReturn(mock(World.class));
// Item Frame
when(entity.getWorld()).thenReturn(world);
when(entity.getLocation()).thenReturn(location);
// Not allowed to start // Not allowed to start
Flags.ITEM_FRAME_DAMAGE.setSetting(world, false); Flags.ITEM_FRAME_DAMAGE.setSetting(world, false);
@ -143,7 +147,6 @@ public class ItemFrameListenerTest {
@Test @Test
public void testOnItemFrameDamageEntityDamageByEntityEvent() { public void testOnItemFrameDamageEntityDamageByEntityEvent() {
ItemFrameListener ifl = new ItemFrameListener(); ItemFrameListener ifl = new ItemFrameListener();
Entity entity = mock(ItemFrame.class);
DamageCause cause = DamageCause.ENTITY_ATTACK; DamageCause cause = DamageCause.ENTITY_ATTACK;
EntityDamageByEntityEvent e = new EntityDamageByEntityEvent(enderman, entity, cause , 0); EntityDamageByEntityEvent e = new EntityDamageByEntityEvent(enderman, entity, cause , 0);
ifl.onItemFrameDamage(e); ifl.onItemFrameDamage(e);
@ -156,9 +159,10 @@ public class ItemFrameListenerTest {
@Test @Test
public void testNotItemFrame() { public void testNotItemFrame() {
ItemFrameListener ifl = new ItemFrameListener(); ItemFrameListener ifl = new ItemFrameListener();
Entity entity = mock(Monster.class); Creeper creeper = mock(Creeper.class);
when(creeper.getLocation()).thenReturn(location);
DamageCause cause = DamageCause.ENTITY_ATTACK; DamageCause cause = DamageCause.ENTITY_ATTACK;
EntityDamageByEntityEvent e = new EntityDamageByEntityEvent(enderman, entity, cause , 0); EntityDamageByEntityEvent e = new EntityDamageByEntityEvent(enderman, creeper, cause , 0);
ifl.onItemFrameDamage(e); ifl.onItemFrameDamage(e);
assertFalse(e.isCancelled()); assertFalse(e.isCancelled());
} }
@ -169,7 +173,6 @@ public class ItemFrameListenerTest {
@Test @Test
public void testProjectile() { public void testProjectile() {
ItemFrameListener ifl = new ItemFrameListener(); ItemFrameListener ifl = new ItemFrameListener();
Entity entity = mock(ItemFrame.class);
DamageCause cause = DamageCause.ENTITY_ATTACK; DamageCause cause = DamageCause.ENTITY_ATTACK;
Projectile p = mock(Projectile.class); Projectile p = mock(Projectile.class);
when(p.getShooter()).thenReturn(enderman); when(p.getShooter()).thenReturn(enderman);
@ -184,7 +187,6 @@ public class ItemFrameListenerTest {
@Test @Test
public void testPlayerProjectile() { public void testPlayerProjectile() {
ItemFrameListener ifl = new ItemFrameListener(); ItemFrameListener ifl = new ItemFrameListener();
Entity entity = mock(ItemFrame.class);
DamageCause cause = DamageCause.ENTITY_ATTACK; DamageCause cause = DamageCause.ENTITY_ATTACK;
Projectile p = mock(Projectile.class); Projectile p = mock(Projectile.class);
Player player = mock(Player.class); Player player = mock(Player.class);
@ -200,8 +202,7 @@ public class ItemFrameListenerTest {
@Test @Test
public void testOnItemFrameDamageHangingBreakByEntityEvent() { public void testOnItemFrameDamageHangingBreakByEntityEvent() {
ItemFrameListener ifl = new ItemFrameListener(); ItemFrameListener ifl = new ItemFrameListener();
Hanging hanging = mock(ItemFrame.class); HangingBreakByEntityEvent e = new HangingBreakByEntityEvent(entity, enderman);
HangingBreakByEntityEvent e = new HangingBreakByEntityEvent(hanging, enderman);
ifl.onItemFrameDamage(e); ifl.onItemFrameDamage(e);
assertTrue(e.isCancelled()); assertTrue(e.isCancelled());
} }

View File

@ -3,8 +3,9 @@ package world.bentobox.bentobox.listeners.flags.worldsettings;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
@ -21,9 +22,9 @@ import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.event.world.StructureGrowEvent;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
@ -46,21 +47,33 @@ import world.bentobox.bentobox.managers.IslandsManager;
public class TreesGrowingOutsideRangeListenerTest { public class TreesGrowingOutsideRangeListenerTest {
/* IslandWorldManager */ /* IslandWorldManager */
@Mock
private IslandWorldManager iwm; private IslandWorldManager iwm;
/* Event */ /* Event */
private StructureGrowEvent event; private StructureGrowEvent event;
/* Block */ /* Block */
@Mock
private Block sapling; private Block sapling;
private List<BlockState> blockStates; private List<BlockState> blockStates;
/* World */ /* World */
@Mock
private World world; private World world;
/* Islands */ /* Islands */
@Mock
private IslandsManager islandsManager; private IslandsManager islandsManager;
@Mock
private Island island;
@Mock
private BlockState firstBlock;
@Mock
private BlockState lastBlock;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
// Set up plugin // Set up plugin
@ -68,7 +81,6 @@ public class TreesGrowingOutsideRangeListenerTest {
Whitebox.setInternalState(BentoBox.class, "instance", plugin); Whitebox.setInternalState(BentoBox.class, "instance", plugin);
/* Blocks */ /* Blocks */
sapling = mock(Block.class);
when(sapling.getType()).thenReturn(Material.OAK_SAPLING); when(sapling.getType()).thenReturn(Material.OAK_SAPLING);
when(sapling.getLocation()).thenReturn(new Location(world, 2, 0, 2)); when(sapling.getLocation()).thenReturn(new Location(world, 2, 0, 2));
@ -78,16 +90,13 @@ public class TreesGrowingOutsideRangeListenerTest {
/* Event */ /* Event */
event = new StructureGrowEvent(sapling.getLocation(), TreeType.TREE, false, null, blockStates); event = new StructureGrowEvent(sapling.getLocation(), TreeType.TREE, false, null, blockStates);
/* World */
world = mock(World.class);
/* Island World Manager */ /* Island World Manager */
iwm = mock(IslandWorldManager.class);
when(plugin.getIWM()).thenReturn(iwm); when(plugin.getIWM()).thenReturn(iwm);
// WorldSettings and World Flags // WorldSettings and World Flags
WorldSettings ws = mock(WorldSettings.class); WorldSettings ws = mock(WorldSettings.class);
when(iwm.getWorldSettings(Mockito.any())).thenReturn(ws); when(iwm.getWorldSettings(any())).thenReturn(ws);
Map<String, Boolean> worldFlags = new HashMap<>(); Map<String, Boolean> worldFlags = new HashMap<>();
when(ws.getWorldFlags()).thenReturn(worldFlags); when(ws.getWorldFlags()).thenReturn(worldFlags);
@ -101,17 +110,17 @@ public class TreesGrowingOutsideRangeListenerTest {
Flags.TREES_GROWING_OUTSIDE_RANGE.setSetting(world, false); Flags.TREES_GROWING_OUTSIDE_RANGE.setSetting(world, false);
/* Islands */ /* Islands */
islandsManager = mock(IslandsManager.class);
when(plugin.getIslands()).thenReturn(islandsManager); when(plugin.getIslands()).thenReturn(islandsManager);
// By default, there should be an island. // By default, there should be an island.
Island island = mock(Island.class); when(islandsManager.getProtectedIslandAt(any())).thenReturn(Optional.of(island));
when(islandsManager.getProtectedIslandAt(Mockito.any())).thenReturn(Optional.of(island));
} }
/** /**
* Populates {@link TreesGrowingOutsideRangeListenerTest#blockStates} with a tree schema. * Populates {@link TreesGrowingOutsideRangeListenerTest#blockStates} with a tree schema.
*/ */
private void populateBlockStatesList() { private void populateBlockStatesList() {
//when(firstBlock.getLocation()).thenReturn(new Location(world, 2, 0, 2));
blockStates.add(firstBlock);
// Tree logs // Tree logs
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
BlockState logState = mock(BlockState.class); BlockState logState = mock(BlockState.class);
@ -133,6 +142,8 @@ public class TreesGrowingOutsideRangeListenerTest {
} }
} }
} }
//when(lastBlock.getLocation()).thenReturn(new Location(world, 2, 0, 2));
blockStates.add(lastBlock);
} }
/** /**
@ -189,13 +200,18 @@ public class TreesGrowingOutsideRangeListenerTest {
assertFalse(event.isCancelled()); assertFalse(event.isCancelled());
} }
@Ignore @SuppressWarnings("unchecked")
@Test @Test
public void testTreePartiallyOutsideIsland() { public void testTreePartiallyOutsideIsland() {
//FIXME // Only the first few blocks are inside the island
when(islandsManager.getProtectedIslandAt(any())).thenReturn(Optional.of(island),
Optional.of(island),
Optional.of(island),
Optional.empty());
// Run // Run
new TreesGrowingOutsideRangeListener().onTreeGrow(event); new TreesGrowingOutsideRangeListener().onTreeGrow(event);
assertFalse(event.isCancelled()); assertFalse(event.isCancelled());
verify(firstBlock, Mockito.never()).setType(Material.AIR);
verify(lastBlock).setType(Material.AIR);
} }
} }

View File

@ -5,10 +5,12 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.eq; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.io.File; import java.io.File;
@ -217,10 +219,10 @@ public class IslandsManagerTest {
// Worlds translate to world // Worlds translate to world
PowerMockito.mockStatic(Util.class); PowerMockito.mockStatic(Util.class);
when(Util.getWorld(Mockito.any())).thenReturn(world); when(Util.getWorld(any())).thenReturn(world);
// Mock island cache // Mock island cache
when(islandCache.getIslandAt(Mockito.any(Location.class))).thenReturn(is); when(islandCache.getIslandAt(any(Location.class))).thenReturn(is);
optionalIsland = Optional.ofNullable(is); optionalIsland = Optional.ofNullable(is);
// User location // User location
@ -232,10 +234,10 @@ public class IslandsManagerTest {
when(server.getPluginManager()).thenReturn(pim); when(server.getPluginManager()).thenReturn(pim);
// Addon // Addon
when(iwm.getAddon(Mockito.any())).thenReturn(Optional.empty()); when(iwm.getAddon(any())).thenReturn(Optional.empty());
// Cover hostile entities // Cover hostile entities
when(Util.isHostileEntity(Mockito.any())).thenCallRealMethod(); when(Util.isHostileEntity(any())).thenCallRealMethod();
// Set up island entities // Set up island entities
WorldSettings ws = mock(WorldSettings.class); WorldSettings ws = mock(WorldSettings.class);
@ -250,7 +252,7 @@ public class IslandsManagerTest {
whitelist.add(EntityType.WITHER); whitelist.add(EntityType.WITHER);
whitelist.add(EntityType.ZOMBIE_VILLAGER); whitelist.add(EntityType.ZOMBIE_VILLAGER);
whitelist.add(EntityType.PIG_ZOMBIE); whitelist.add(EntityType.PIG_ZOMBIE);
when(iwm.getRemoveMobsWhitelist(Mockito.any())).thenReturn(whitelist); when(iwm.getRemoveMobsWhitelist(any())).thenReturn(whitelist);
// Monsters and animals // Monsters and animals
@ -277,7 +279,7 @@ public class IslandsManagerTest {
collection.add(pufferfish); collection.add(pufferfish);
collection.add(skelly); collection.add(skelly);
when(world when(world
.getNearbyEntities(Mockito.any(Location.class), Mockito.anyDouble(), Mockito.anyDouble(), Mockito.anyDouble())) .getNearbyEntities(any(Location.class), Mockito.anyDouble(), Mockito.anyDouble(), Mockito.anyDouble()))
.thenReturn(collection); .thenReturn(collection);
@ -531,7 +533,7 @@ public class IslandsManagerTest {
Island island = im.createIsland(location, owner); Island island = im.createIsland(location, owner);
im.deleteIsland(island, false, owner); im.deleteIsland(island, false, owner);
assertNull(island.getOwner()); assertNull(island.getOwner());
Mockito.verify(pim, Mockito.times(2)).callEvent(Mockito.any(IslandDeleteEvent.class)); verify(pim).callEvent(any(IslandDeleteEvent.class));
} }
/** /**
@ -539,13 +541,13 @@ public class IslandsManagerTest {
*/ */
@Test @Test
public void testDeleteIslandIslandBooleanRemoveBlocks() { public void testDeleteIslandIslandBooleanRemoveBlocks() {
Mockito.verify(pim, never()).callEvent(Mockito.any()); verify(pim, never()).callEvent(any());
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
UUID owner = UUID.randomUUID(); UUID owner = UUID.randomUUID();
Island island = im.createIsland(location, owner); Island island = im.createIsland(location, owner);
im.deleteIsland(island, true, owner); im.deleteIsland(island, true, owner);
assertNull(island.getOwner()); assertNull(island.getOwner());
Mockito.verify(pim, Mockito.times(4)).callEvent(Mockito.any(IslandDeleteEvent.class)); verify(pim).callEvent(any(IslandDeleteEvent.class));
} }
/** /**
@ -584,7 +586,7 @@ public class IslandsManagerTest {
assertEquals(optionalIsland, im.getIslandAt(location)); assertEquals(optionalIsland, im.getIslandAt(location));
// in world, wrong island // in world, wrong island
when(islandCache.getIslandAt(Mockito.any(Location.class))).thenReturn(null); when(islandCache.getIslandAt(any(Location.class))).thenReturn(null);
assertEquals(Optional.empty(), im.getIslandAt(new Location(world, 100000, 120, -100000))); assertEquals(Optional.empty(), im.getIslandAt(new Location(world, 100000, 120, -100000)));
// not in world // not in world
@ -626,7 +628,7 @@ public class IslandsManagerTest {
members.add(UUID.randomUUID()); members.add(UUID.randomUUID());
members.add(UUID.randomUUID()); members.add(UUID.randomUUID());
members.add(UUID.randomUUID()); members.add(UUID.randomUUID());
when(islandCache.getMembers(Mockito.any(), Mockito.any(), Mockito.anyInt())).thenReturn(members); when(islandCache.getMembers(any(), any(), Mockito.anyInt())).thenReturn(members);
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
im.setIslandCache(islandCache); im.setIslandCache(islandCache);
assertEquals(members, im.getMembers(world, UUID.randomUUID())); assertEquals(members, im.getMembers(world, UUID.randomUUID()));
@ -640,7 +642,7 @@ public class IslandsManagerTest {
// Mock island cache // Mock island cache
Island is = mock(Island.class); Island is = mock(Island.class);
when(islandCache.getIslandAt(Mockito.any(Location.class))).thenReturn(is); when(islandCache.getIslandAt(any(Location.class))).thenReturn(is);
// In world // In world
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
@ -648,20 +650,20 @@ public class IslandsManagerTest {
Optional<Island> optionalIsland = Optional.ofNullable(is); Optional<Island> optionalIsland = Optional.ofNullable(is);
// In world, correct island // In world, correct island
when(is.onIsland(Mockito.any())).thenReturn(true); when(is.onIsland(any())).thenReturn(true);
assertEquals(optionalIsland, im.getProtectedIslandAt(location)); assertEquals(optionalIsland, im.getProtectedIslandAt(location));
// Not in protected space // Not in protected space
when(is.onIsland(Mockito.any())).thenReturn(false); when(is.onIsland(any())).thenReturn(false);
assertEquals(Optional.empty(), im.getProtectedIslandAt(location)); assertEquals(Optional.empty(), im.getProtectedIslandAt(location));
im.setSpawn(is); im.setSpawn(is);
// In world, correct island // In world, correct island
when(is.onIsland(Mockito.any())).thenReturn(true); when(is.onIsland(any())).thenReturn(true);
assertEquals(optionalIsland, im.getProtectedIslandAt(location)); assertEquals(optionalIsland, im.getProtectedIslandAt(location));
// Not in protected space // Not in protected space
when(is.onIsland(Mockito.any())).thenReturn(false); when(is.onIsland(any())).thenReturn(false);
assertEquals(Optional.empty(), im.getProtectedIslandAt(location)); assertEquals(Optional.empty(), im.getProtectedIslandAt(location));
} }
@ -671,8 +673,8 @@ public class IslandsManagerTest {
@Test @Test
public void testGetSafeHomeLocation() { public void testGetSafeHomeLocation() {
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
when(pm.getHomeLocation(Mockito.any(), Mockito.any(User.class), Mockito.eq(0))).thenReturn(null); when(pm.getHomeLocation(any(), any(User.class), eq(0))).thenReturn(null);
when(pm.getHomeLocation(Mockito.any(), Mockito.any(User.class), Mockito.eq(1))).thenReturn(location); when(pm.getHomeLocation(any(), any(User.class), eq(1))).thenReturn(location);
assertEquals(location, im.getSafeHomeLocation(world, user, 0)); assertEquals(location, im.getSafeHomeLocation(world, user, 0));
// Change location so that it is not safe // Change location so that it is not safe
// TODO // TODO
@ -689,7 +691,7 @@ public class IslandsManagerTest {
Island island = mock(Island.class); Island island = mock(Island.class);
when(island.getWorld()).thenReturn(world); when(island.getWorld()).thenReturn(world);
// Make a spawn position on the island // Make a spawn position on the island
when(island.getSpawnPoint(Mockito.any())).thenReturn(location); when(island.getSpawnPoint(any())).thenReturn(location);
// Set the spawn island // Set the spawn island
im.setSpawn(island); im.setSpawn(island);
assertEquals(location,im.getSpawnPoint(world)); assertEquals(location,im.getSpawnPoint(world));
@ -702,10 +704,10 @@ public class IslandsManagerTest {
public void testHomeTeleportPlayerInt() { public void testHomeTeleportPlayerInt() {
when(iwm.getDefaultGameMode(world)).thenReturn(GameMode.SURVIVAL); when(iwm.getDefaultGameMode(world)).thenReturn(GameMode.SURVIVAL);
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
when(pm.getHomeLocation(Mockito.any(), Mockito.any(User.class), Mockito.eq(0))).thenReturn(null); when(pm.getHomeLocation(any(), any(User.class), eq(0))).thenReturn(null);
when(pm.getHomeLocation(Mockito.any(), Mockito.any(User.class), Mockito.eq(1))).thenReturn(location); when(pm.getHomeLocation(any(), any(User.class), eq(1))).thenReturn(location);
im.homeTeleport(world, player, 0); im.homeTeleport(world, player, 0);
Mockito.verify(player).teleport(location); verify(player).teleport(location);
} }
@ -718,7 +720,7 @@ public class IslandsManagerTest {
assertFalse(im.isAtSpawn(location)); assertFalse(im.isAtSpawn(location));
Island island = mock(Island.class); Island island = mock(Island.class);
when(island.getWorld()).thenReturn(world); when(island.getWorld()).thenReturn(world);
when(island.onIsland(Mockito.any())).thenReturn(true); when(island.onIsland(any())).thenReturn(true);
im.setSpawn(island); im.setSpawn(island);
assertTrue(im.isAtSpawn(location)); assertTrue(im.isAtSpawn(location));
} }
@ -731,18 +733,18 @@ public class IslandsManagerTest {
// Mock island cache // Mock island cache
Island is = mock(Island.class); Island is = mock(Island.class);
when(islandCache.getIslandAt(Mockito.any())).thenReturn(is); when(islandCache.getIslandAt(any())).thenReturn(is);
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
im.setIslandCache(islandCache); im.setIslandCache(islandCache);
assertFalse(im.isOwner(world, null)); assertFalse(im.isOwner(world, null));
when(islandCache.hasIsland(Mockito.any(), Mockito.any())).thenReturn(false); when(islandCache.hasIsland(any(), any())).thenReturn(false);
assertFalse(im.isOwner(world, UUID.randomUUID())); assertFalse(im.isOwner(world, UUID.randomUUID()));
when(islandCache.hasIsland(Mockito.any(), Mockito.any())).thenReturn(true); when(islandCache.hasIsland(any(), any())).thenReturn(true);
when(islandCache.get(Mockito.any(), Mockito.any(UUID.class))).thenReturn(is); when(islandCache.get(any(), any(UUID.class))).thenReturn(is);
UUID owner = UUID.randomUUID(); UUID owner = UUID.randomUUID();
when(is.getOwner()).thenReturn(owner); when(is.getOwner()).thenReturn(owner);
UUID notOwner = UUID.randomUUID(); UUID notOwner = UUID.randomUUID();
@ -771,10 +773,10 @@ public class IslandsManagerTest {
// Mock island cache // Mock island cache
Island is = mock(Island.class); Island is = mock(Island.class);
when(islandCache.getIslandAt(Mockito.any(Location.class))).thenReturn(is); when(islandCache.getIslandAt(any(Location.class))).thenReturn(is);
// In world // In world
when(is.onIsland(Mockito.any())).thenReturn(true); when(is.onIsland(any())).thenReturn(true);
Builder<UUID> members = new ImmutableSet.Builder<>(); Builder<UUID> members = new ImmutableSet.Builder<>();
members.add(uuid); members.add(uuid);
@ -796,7 +798,7 @@ public class IslandsManagerTest {
// Not on island // Not on island
when(is.getMemberSet()).thenReturn(members.build()); when(is.getMemberSet()).thenReturn(members.build());
when(is.onIsland(Mockito.any())).thenReturn(false); when(is.onIsland(any())).thenReturn(false);
assertFalse(im.locationIsOnIsland(player, location)); assertFalse(im.locationIsOnIsland(player, location));
} }
@ -829,7 +831,7 @@ public class IslandsManagerTest {
when(user.isPlayer()).thenReturn(true); when(user.isPlayer()).thenReturn(true);
// The method returns true if the user's location is on an island that has them as member (rank >= MEMBER) // The method returns true if the user's location is on an island that has them as member (rank >= MEMBER)
when(is.onIsland(Mockito.any())).thenReturn(true); when(is.onIsland(any())).thenReturn(true);
Map<UUID, Integer> members = new HashMap<>(); Map<UUID, Integer> members = new HashMap<>();
when(is.getMembers()).thenReturn(members); when(is.getMembers()).thenReturn(members);
@ -988,7 +990,7 @@ public class IslandsManagerTest {
im.shutdown(); im.shutdown();
assertEquals(10, members.size()); assertEquals(10, members.size());
Mockito.verify(islandCache).clear(); verify(islandCache).clear();
} }
/** /**
@ -1042,14 +1044,14 @@ public class IslandsManagerTest {
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
im.clearArea(location); im.clearArea(location);
// No entities should be cleared // No entities should be cleared
Mockito.verify(zombie, never()).remove(); verify(zombie, never()).remove();
Mockito.verify(player, never()).remove(); verify(player, never()).remove();
Mockito.verify(cow, never()).remove(); verify(cow, never()).remove();
Mockito.verify(slime, never()).remove(); verify(slime, never()).remove();
Mockito.verify(wither, never()).remove(); verify(wither, never()).remove();
Mockito.verify(creeper, never()).remove(); verify(creeper, never()).remove();
Mockito.verify(pufferfish, never()).remove(); verify(pufferfish, never()).remove();
Mockito.verify(skelly, never()).remove(); verify(skelly, never()).remove();
} }
@ -1061,14 +1063,14 @@ public class IslandsManagerTest {
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
im.clearArea(location); im.clearArea(location);
// Only the correct entities should be cleared // Only the correct entities should be cleared
Mockito.verify(zombie).remove(); verify(zombie).remove();
Mockito.verify(player, never()).remove(); verify(player, never()).remove();
Mockito.verify(cow, never()).remove(); verify(cow, never()).remove();
Mockito.verify(slime).remove(); verify(slime).remove();
Mockito.verify(wither, never()).remove(); verify(wither, never()).remove();
Mockito.verify(creeper).remove(); verify(creeper).remove();
Mockito.verify(pufferfish, never()).remove(); verify(pufferfish, never()).remove();
Mockito.verify(skelly, never()).remove(); verify(skelly, never()).remove();
} }
/** /**
@ -1078,7 +1080,7 @@ public class IslandsManagerTest {
public void testGetIslandByIdString() { public void testGetIslandByIdString() {
Island island = mock(Island.class); Island island = mock(Island.class);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
when(islandCache.getIslandById(Mockito.anyString())).thenReturn(island); when(islandCache.getIslandById(anyString())).thenReturn(island);
// Test // Test
IslandsManager im = new IslandsManager(plugin); IslandsManager im = new IslandsManager(plugin);
im.setIslandCache(islandCache); im.setIslandCache(islandCache);

View File

@ -1,20 +1,29 @@
package world.bentobox.bentobox.managers; package world.bentobox.bentobox.managers;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.NonNull;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.api.addons.AddonDescription; import world.bentobox.bentobox.api.addons.AddonDescription;
import world.bentobox.bentobox.api.addons.GameModeAddon; import world.bentobox.bentobox.api.addons.GameModeAddon;
import world.bentobox.bentobox.api.hooks.Hook;
import world.bentobox.bentobox.hooks.placeholders.MVdWPlaceholderAPIHook;
import world.bentobox.bentobox.hooks.placeholders.PlaceholderAPIHook;
import world.bentobox.bentobox.lists.GameModePlaceholder;
/** /**
* @author tastybento * @author tastybento
@ -28,8 +37,13 @@ public class PlaceholdersManagerTest {
private BentoBox plugin; private BentoBox plugin;
@Mock @Mock
private GameModeAddon addon; private GameModeAddon addon;
@Mock
private PlaceholdersManager pm; private PlaceholdersManager pm;
@Mock
private HooksManager hm;
@Mock
private PlaceholderAPIHook hook;
@Mock
private MVdWPlaceholderAPIHook hook2;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
@ -40,33 +54,41 @@ public class PlaceholdersManagerTest {
when(plugin.getPlaceholdersManager()).thenReturn(pm); when(plugin.getPlaceholdersManager()).thenReturn(pm);
// No placeholders registered yet // No placeholders registered yet
when(pm.isPlaceholder(Mockito.any(), Mockito.any())).thenReturn(false); //when(pm.isPlaceholder(any(), any())).thenReturn(false);
// Hooks
when(plugin.getHooks()).thenReturn(hm);
Optional<Hook> optionalHook = Optional.of(hook);
when(hm.getHook(eq("PlaceholderAPI"))).thenReturn(optionalHook);
when(hook.isPlaceholder(any(), any())).thenReturn(false);
Optional<Hook> optionalHook2 = Optional.of(hook2);
when(hm.getHook(eq("MVdWPlaceholderAPI"))).thenReturn(optionalHook2);
// Placeholder manager
pm = new PlaceholdersManager(plugin);
} }
/** /**
* Test method for {@link world.bentobox.bentobox.managers.PlaceholdersManager#registerDefaultPlaceholders(GameModeAddon)}. * Test method for {@link world.bentobox.bentobox.managers.PlaceholdersManager#registerDefaultPlaceholders(GameModeAddon)}.
*/ */
@Test @Test
@Ignore("could not fix them")
public void testRegisterGameModePlaceholdersAllDefaults() { public void testRegisterGameModePlaceholdersAllDefaults() {
pm.registerDefaultPlaceholders(addon); pm.registerDefaultPlaceholders(addon);
Mockito.verify(pm, Mockito.atMost(1)).registerDefaultPlaceholders(addon); verify(hook, times(GameModePlaceholder.values().length)).registerPlaceholder(any(), anyString(), any());
// 7 registrations for this addon verify(hook2, times(GameModePlaceholder.values().length)).registerPlaceholder(any(), anyString(), any());
Mockito.verify(pm, Mockito.atLeastOnce()).registerPlaceholder(Mockito.any(), Mockito.anyString(), Mockito.any());
} }
/** /**
* Test method for {@link world.bentobox.bentobox.managers.PlaceholdersManager#registerDefaultPlaceholders(GameModeAddon)}. * Test method for {@link world.bentobox.bentobox.managers.PlaceholdersManager#registerDefaultPlaceholders(GameModeAddon)}.
*/ */
@Test @Test
@Ignore("could not fix them")
public void testRegisterDefaultPlaceholdersSomePreregistered() { public void testRegisterDefaultPlaceholdersSomePreregistered() {
// Some duplicates // Some duplicates
when(pm.isPlaceholder(Mockito.any(), Mockito.any())).thenReturn(false, true, true, false, false, true, false); when(hook.isPlaceholder(any(), any())).thenReturn(false, true, true, false, false, true, false);
pm.registerDefaultPlaceholders(addon); pm.registerDefaultPlaceholders(addon);
// 3 registrations for this addon // 3 less registrations for this addon
Mockito.verify(pm, Mockito.atLeast(1)).registerPlaceholder(Mockito.anyString(), Mockito.any()); verify(hook, times(GameModePlaceholder.values().length - 3)).registerPlaceholder(any(), anyString(), any());
} }
} }