Best MockBukkit code snippet using be.seeseemelk.mockbukkit.exception.EventHandlerException.EventHandlerException
Source:PluginManagerMock.java
1package be.seeseemelk.mockbukkit.plugin;2import be.seeseemelk.mockbukkit.ServerMock;3import be.seeseemelk.mockbukkit.UnimplementedOperationException;4import be.seeseemelk.mockbukkit.exception.EventHandlerException;5import be.seeseemelk.mockbukkit.scheduler.BukkitSchedulerMock;6import com.destroystokyo.paper.event.server.ServerExceptionEvent;7import com.destroystokyo.paper.exception.ServerEventException;8import com.google.common.base.Preconditions;9import com.google.common.collect.ImmutableSet;10import org.bukkit.command.PluginCommand;11import org.bukkit.command.PluginCommandUtils;12import org.bukkit.configuration.file.YamlConfiguration;13import org.bukkit.event.Event;14import org.bukkit.event.EventPriority;15import org.bukkit.event.HandlerList;16import org.bukkit.event.Listener;17import org.bukkit.event.server.PluginEnableEvent;18import org.bukkit.permissions.Permissible;19import org.bukkit.permissions.Permission;20import org.bukkit.permissions.PermissionDefault;21import org.bukkit.plugin.EventExecutor;22import org.bukkit.plugin.IllegalPluginAccessException;23import org.bukkit.plugin.InvalidDescriptionException;24import org.bukkit.plugin.InvalidPluginException;25import org.bukkit.plugin.Plugin;26import org.bukkit.plugin.PluginDescriptionFile;27import org.bukkit.plugin.PluginLoader;28import org.bukkit.plugin.PluginManager;29import org.bukkit.plugin.RegisteredListener;30import org.bukkit.plugin.UnknownDependencyException;31import org.bukkit.plugin.java.JavaPlugin;32import org.bukkit.plugin.java.JavaPluginLoader;33import org.bukkit.plugin.java.JavaPluginUtils;34import org.jetbrains.annotations.NotNull;35import java.io.File;36import java.io.FileNotFoundException;37import java.io.IOException;38import java.lang.reflect.Constructor;39import java.lang.reflect.Method;40import java.net.URL;41import java.nio.file.Files;42import java.nio.file.Path;43import java.util.ArrayList;44import java.util.Arrays;45import java.util.Collection;46import java.util.Collections;47import java.util.Comparator;48import java.util.Enumeration;49import java.util.HashMap;50import java.util.HashSet;51import java.util.List;52import java.util.Locale;53import java.util.Map;54import java.util.Map.Entry;55import java.util.Random;56import java.util.Set;57import java.util.WeakHashMap;58import java.util.concurrent.ThreadLocalRandom;59import java.util.function.Consumer;60import java.util.function.Predicate;61import java.util.logging.Level;62import java.util.stream.Collectors;63import java.util.stream.Stream;64import static org.junit.jupiter.api.Assertions.fail;65public class PluginManagerMock implements PluginManager66{67 private final @NotNull ServerMock server;68 private final @NotNull JavaPluginLoader loader;69 private final List<Plugin> plugins = new ArrayList<>();70 private final List<PluginCommand> commands = new ArrayList<>();71 private final List<Event> events = new ArrayList<>();72 private File parentTemporaryDirectory;73 private final Map<String, Permission> permissions = new HashMap<>();74 private final Map<Permissible, Set<String>> permissionSubscriptions = new HashMap<>();75 private final Map<Boolean, Map<Permissible, Boolean>> defaultPermissionSubscriptions = new HashMap<Boolean, Map<Permissible, Boolean>>();76 private final @NotNull Map<String, List<Listener>> listeners = new HashMap<>();77 private final List<Class<?>> pluginConstructorTypes = Arrays.asList(JavaPluginLoader.class,78 PluginDescriptionFile.class, File.class, File.class);79 @SuppressWarnings("deprecation")80 public PluginManagerMock(@NotNull ServerMock server)81 {82 this.server = server;83 loader = new JavaPluginLoader(this.server);84 }85 /**86 * Should be called when the plugin manager is not used anymore.87 */88 public void unload()89 {90 if (parentTemporaryDirectory == null)91 return;92 // Delete the temporary directory, from the deepest file to the root.93 try (Stream<Path> walk = Files.walk(parentTemporaryDirectory.toPath()))94 {95 walk.sorted(Comparator.reverseOrder())96 .map(Path::toFile)97 .forEach(File::delete);98 }99 catch (IOException e)100 {101 server.getLogger().log(Level.SEVERE, "Could not delete temporary directory", e);102 }103 }104 /**105 * Asserts that at least one event conforms to the given predicate.106 *107 * @param message The message to display when no event conforms.108 * @param predicate The predicate to test against.109 */110 public void assertEventFired(@NotNull String message, @NotNull Predicate<Event> predicate)111 {112 for (Event event : events)113 {114 if (predicate.test(event))115 {116 return;117 }118 }119 fail(message);120 }121 /**122 * Asserts that at least one event conforms to the given predicate.123 *124 * @param predicate The predicate to test against.125 */126 public void assertEventFired(@NotNull Predicate<Event> predicate)127 {128 assertEventFired("Event assert failed", predicate);129 }130 /**131 * Asserts that there is at least one event of a certain class for which the predicate is true.132 *133 * @param <T> The type of event that is expected.134 * @param message The message to display if no event is found.135 * @param eventClass The class type that the event should be an instance of.136 * @param predicate The predicate to test the event against.137 */138 public <T extends Event> void assertEventFired(String message, @NotNull Class<T> eventClass, @NotNull Predicate<T> predicate)139 {140 for (Event event : events)141 {142 if (eventClass.isInstance(event) && predicate.test(eventClass.cast(event)))143 {144 return;145 }146 }147 fail(message);148 }149 /**150 * Asserts that there is at least one event of a certain class for which the predicate is true.151 *152 * @param <T> The type of event that is expected.153 * @param eventClass The class type that the event should be an instance of.154 * @param predicate The predicate to test the event against.155 */156 public <T extends Event> void assertEventFired(@NotNull Class<T> eventClass, @NotNull Predicate<T> predicate)157 {158 assertEventFired("No event of the correct class tested true", eventClass, predicate);159 }160 /**161 * Asserts that a specific event or one of it's sub-events has been fired at least once.162 *163 * @param eventClass The class of the event to check for.164 */165 public void assertEventFired(@NotNull Class<? extends Event> eventClass)166 {167 assertEventFired("No event of that type has been fired", eventClass::isInstance);168 }169 /**170 * Asserts that a specific event or one of it's sub-event has not been fired.171 *172 * @param eventClass The class of the event to check for.173 */174 public void assertEventNotFired(@NotNull Class<? extends Event> eventClass)175 {176 assertEventNotFired(eventClass, "An event of type " + eventClass.getSimpleName() + " has been fired when it shouldn't have been");177 }178 /**179 * Asserts that a specific event or one of it's sub-event has not been fired.180 *181 * @param eventClass The class of the event to check for.182 * @param message The message to print when failed.183 */184 public void assertEventNotFired(@NotNull Class<? extends Event> eventClass, String message)185 {186 for (Event event : this.events)187 {188 if (eventClass.isAssignableFrom(event.getClass()))189 {190 fail(message);191 }192 }193 }194 @Override195 public Plugin getPlugin(@NotNull String name)196 {197 for (Plugin plugin : plugins)198 {199 if (name.equals(plugin.getName()))200 {201 return plugin;202 }203 }204 return null;205 }206 @Override207 public Plugin @NotNull [] getPlugins()208 {209 return plugins.toArray(new Plugin[0]);210 }211 /**212 * Get a collection of all available commands.213 *214 * @return A collection of all available commands.215 */216 public @NotNull Collection<PluginCommand> getCommands()217 {218 return Collections.unmodifiableList(commands);219 }220 /**221 * Checks if a constructor is compatible with an array of types.222 *223 * @param constructor The constructor to check.224 * @param types The array of parameter types the constructor must support. Note that the first 4 parameters225 * should be an exact match while the rest don't have to be.226 * @return {@code true} if the constructor is compatible, {@code false} if it isn't.227 */228 private boolean isConstructorCompatible(@NotNull Constructor<?> constructor, @NotNull Class<?> @NotNull [] types)229 {230 Class<?>[] parameters = constructor.getParameterTypes();231 for (int i = 0; i < types.length; i++)232 {233 Class<?> type = types[i];234 Class<?> parameter = parameters[i];235 if (i < 4)236 {237 if (!type.equals(parameter))238 {239 return false;240 }241 }242 else if (!parameter.isAssignableFrom(type))243 {244 return false;245 }246 }247 return true;248 }249 /**250 * Looks for a compatible constructor of a plugin with a certain constructor.251 *252 * @param class1 The plugin class for which a constructor should be found.253 * @param types The types of parameters that the constructor should be able to except. Note that the first 4254 * parameters should be an exact match while the rest don't have to be.255 * @return A constructor that will take the given types.256 * @throws NoSuchMethodException if no compatible constructor could be found.257 */258 @SuppressWarnings("unchecked")259 private @NotNull Constructor<? extends JavaPlugin> getCompatibleConstructor(@NotNull Class<? extends JavaPlugin> class1,260 Class<?> @NotNull [] types) throws NoSuchMethodException261 {262 for (Constructor<?> constructor : class1.getDeclaredConstructors())263 {264 Class<?>[] parameters = constructor.getParameterTypes();265 if (parameters.length == types.length && isConstructorCompatible(constructor, types))266 {267 return (Constructor<? extends JavaPlugin>) constructor;268 }269 }270 StringBuilder parameters = new StringBuilder("[");271 for (Class<?> type : types)272 parameters.append(type.getName()).append(", ");273 String str = parameters.substring(0, parameters.length() - 2) + "]";274 throw new NoSuchMethodException(275 "No compatible constructor for " + class1.getName() + " with parameters " + str);276 }277 public @NotNull File getParentTemporaryDirectory() throws IOException278 {279 if (parentTemporaryDirectory == null)280 {281 Random random = ThreadLocalRandom.current();282 parentTemporaryDirectory = Files.createTempDirectory("MockBukkit-" + random.nextInt(0, Integer.MAX_VALUE)).toFile();283 }284 return parentTemporaryDirectory;285 }286 /**287 * Tries to create a temporary directory.288 *289 * @param name The name of the directory to create.290 * @return The created temporary directory.291 * @throws IOException when the directory could not be created.292 */293 public @NotNull File createTemporaryDirectory(@NotNull String name) throws IOException294 {295 File directory = new File(getParentTemporaryDirectory(), name);296 directory.mkdirs();297 return directory;298 }299 /**300 * Tries to create a temporary plugin file.301 *302 * @param name The name of the plugin.303 * @return The created temporary file.304 * @throws IOException when the file could not be created.305 */306 public @NotNull File createTemporaryPluginFile(@NotNull String name) throws IOException307 {308 File pluginFile = new File(getParentTemporaryDirectory(), name + ".jar");309 if (!pluginFile.exists() && !pluginFile.createNewFile())310 {311 throw new IOException("Could not create file " + pluginFile.getAbsolutePath());312 }313 return pluginFile;314 }315 /**316 * Registers a plugin that has already been loaded. This is necessary to register plugins loaded from external jars.317 *318 * @param plugin The plugin that has been loaded.319 */320 public void registerLoadedPlugin(@NotNull Plugin plugin)321 {322 addCommandsFrom(plugin);323 plugins.add(plugin);324 plugin.onLoad();325 }326 /**327 * Load a plugin from a class. It will use the system resource {@code plugin.yml} as the resource file.328 *329 * @param description The {@link PluginDescriptionFile} that contains information about the plugin.330 * @param class1 The plugin to load.331 * @param parameters Extra parameters to pass on to the plugin constructor. Must not be {@code null}.332 * @return The loaded plugin.333 */334 public @NotNull JavaPlugin loadPlugin(@NotNull Class<? extends JavaPlugin> class1, @NotNull PluginDescriptionFile description,335 Object @NotNull [] parameters)336 {337 try338 {339 List<Class<?>> types = new ArrayList<>(pluginConstructorTypes);340 for (Object parameter : parameters)341 {342 types.add(parameter.getClass());343 }344 Constructor<? extends JavaPlugin> constructor = getCompatibleConstructor(class1, types.toArray(new Class<?>[0]));345 constructor.setAccessible(true);346 Object[] arguments = new Object[types.size()];347 arguments[0] = loader;348 arguments[1] = description;349 arguments[2] = createTemporaryDirectory(description.getName() + "-" + description.getVersion());350 arguments[3] = createTemporaryPluginFile(description.getName() + "-" + description.getVersion());351 System.arraycopy(parameters, 0, arguments, 4, parameters.length);352 JavaPlugin plugin = constructor.newInstance(arguments);353 registerLoadedPlugin(plugin);354 return plugin;355 }356 catch (ReflectiveOperationException | IOException e)357 {358 throw new RuntimeException("Failed to instantiate plugin", e);359 }360 }361 /**362 * Load a plugin from a class. It will use the system resource {@code plugin.yml} as the resource file.363 *364 * @param description The {@link PluginDescriptionFile} that contains information about the plugin.365 * @param class1 The plugin to load.366 * @return The loaded plugin.367 */368 public @NotNull JavaPlugin loadPlugin(@NotNull Class<? extends JavaPlugin> class1, @NotNull PluginDescriptionFile description)369 {370 return loadPlugin(class1, description, new Object[0]);371 }372 /**373 * Load a plugin from a class. It will use the system resource {@code plugin.yml} as the resource file.374 *375 * @param class1 The plugin to load.376 * @param parameters Extra parameters to pass on to the plugin constructor.377 * @return The loaded plugin.378 */379 public @NotNull JavaPlugin loadPlugin(@NotNull Class<? extends JavaPlugin> class1, Object @NotNull [] parameters)380 {381 try382 {383 PluginDescriptionFile description = findPluginDescription(class1);384 return loadPlugin(class1, description, parameters);385 }386 catch (IOException | InvalidDescriptionException e)387 {388 throw new RuntimeException(e);389 }390 }391 /**392 * Tries to find the correct plugin.yml for a given plugin. It does this by opening each plugin.yml that it finds393 * and comparing the 'main' property to the qualified name of the plugin class.394 *395 * @param class1 The class that is in a subpackage of where to get the file.396 * @return The plugin description file.397 * @throws IOException Thrown when the file wan't be found or loaded.398 * @throws InvalidDescriptionException If the plugin description file is formatted incorrectly.399 */400 private @NotNull PluginDescriptionFile findPluginDescription(@NotNull Class<? extends JavaPlugin> class1)401 throws IOException, InvalidDescriptionException402 {403 Enumeration<URL> resources = class1.getClassLoader().getResources("plugin.yml");404 while (resources.hasMoreElements())405 {406 URL url = resources.nextElement();407 PluginDescriptionFile description = new PluginDescriptionFile(url.openStream());408 String mainClass = description.getMain();409 if (class1.getName().equals(mainClass))410 return description;411 }412 throw new FileNotFoundException(413 "Could not find file plugin.yml. Maybe forgot to add the 'main' property?");414 }415 @Override416 public void callEvent(@NotNull Event event)417 {418 if (event.isAsynchronous() && server.isOnMainThread())419 {420 throw new IllegalStateException("Asynchronous Events cannot be called on the main Thread.");421 }422 events.add(event);423 HandlerList handlers = event.getHandlers();424 for (RegisteredListener listener : handlers.getRegisteredListeners())425 {426 callRegisteredListener(listener, event);427 }428 }429 /**430 * This method invokes {@link #callEvent(Event)} from a different {@link Thread}431 * using the {@link BukkitSchedulerMock}.432 *433 * @param event The asynchronous {@link Event} to call.434 */435 public void callEventAsynchronously(@NotNull Event event)436 {437 callEventAsynchronously(event, null);438 }439 /**440 * This method invokes {@link #callEvent(Event)} from a different {@link Thread}441 * using the {@link BukkitSchedulerMock}.442 *443 * @param event The asynchronous {@link Event} to call.444 * @param func A function to invoke after the event has been called.445 */446 public <T extends Event> void callEventAsynchronously(@NotNull T event, Consumer<T> func)447 {448 if (!event.isAsynchronous())449 {450 throw new IllegalStateException("Synchronous Events cannot be called asynchronously.");451 }452 // Our Scheduler will call the Event on a dedicated Event Thread Executor453 server.getScheduler().executeAsyncEvent(event, func);454 }455 private void callRegisteredListener(@NotNull RegisteredListener registration, @NotNull Event event)456 {457 if (!registration.getPlugin().isEnabled())458 {459 return;460 }461 try462 {463 registration.callEvent(event);464 }465 catch (Throwable ex)466 {467 if (!(event instanceof ServerExceptionEvent))468 { // Don't cause an endless loop469 String msg = "Could not pass event " + event.getEventName() + " to " + registration.getPlugin().getDescription().getFullName();470 callEvent(new ServerExceptionEvent(new ServerEventException(msg, ex, registration.getPlugin(), registration.getListener(), event)));471 }472 if (ex instanceof RuntimeException r)473 {474 throw r; // Rethrow same exception if possible475 }476 else477 {478 throw new EventHandlerException(ex);479 }480 }481 }482 @Override483 public void enablePlugin(@NotNull Plugin plugin)484 {485 if (plugin instanceof JavaPlugin)486 {487 if (!plugin.isEnabled())488 {489 JavaPluginUtils.setEnabled((JavaPlugin) plugin, true);490 callEvent(new PluginEnableEvent(plugin));491 }492 }...
Source:PluginManagerMockTest.java
1package be.seeseemelk.mockbukkit.plugin;2import be.seeseemelk.mockbukkit.MockBukkit;3import be.seeseemelk.mockbukkit.ServerMock;4import be.seeseemelk.mockbukkit.TestPlugin;5import be.seeseemelk.mockbukkit.exception.EventHandlerException;6import org.bukkit.World;7import org.bukkit.WorldCreator;8import org.bukkit.command.PluginCommand;9import org.bukkit.entity.Player;10import org.bukkit.event.EventHandler;11import org.bukkit.event.Listener;12import org.bukkit.event.block.BlockBreakEvent;13import org.bukkit.event.player.PlayerInteractEvent;14import org.bukkit.event.server.PluginDisableEvent;15import org.bukkit.permissions.Permissible;16import org.bukkit.permissions.Permission;17import org.bukkit.permissions.PermissionDefault;18import org.bukkit.plugin.Plugin;19import org.bukkit.plugin.ServicePriority;20import org.bukkit.plugin.java.JavaPluginUtils;21import org.bukkit.scheduler.BukkitRunnable;22import org.junit.jupiter.api.AfterEach;23import org.junit.jupiter.api.BeforeEach;24import org.junit.jupiter.api.Disabled;25import org.junit.jupiter.api.Test;26import java.util.Collection;27import java.util.Iterator;28import static org.junit.jupiter.api.Assertions.assertEquals;29import static org.junit.jupiter.api.Assertions.assertFalse;30import static org.junit.jupiter.api.Assertions.assertNotNull;31import static org.junit.jupiter.api.Assertions.assertNull;32import static org.junit.jupiter.api.Assertions.assertThrows;33import static org.junit.jupiter.api.Assertions.assertThrowsExactly;34import static org.junit.jupiter.api.Assertions.assertTrue;35class PluginManagerMockTest36{37 private ServerMock server;38 private PluginManagerMock pluginManager;39 private TestPlugin plugin;40 @BeforeEach41 void setUp()42 {43 server = MockBukkit.mock();44 pluginManager = server.getPluginManager();45 plugin = MockBukkit.load(TestPlugin.class);46 }47 @AfterEach48 void tearDown()49 {50 MockBukkit.unmock();51 }52 @Test53 void callEvent_UnregisteredPlayerInteractEvent_NoneCalled()54 {55 PlayerInteractEvent event = new PlayerInteractEvent(null, null, null, null, null);56 pluginManager.callEvent(event);57 assertFalse(plugin.unannotatedPlayerInteractEventExecuted);58 assertFalse(plugin.annotatedBlockBreakEventExecuted);59 assertFalse(plugin.annotatedPlayerInteractEventExecuted);60 }61 @Test62 void callEvent_RegisteredPlayerInteractEvent_OneCalled()63 {64 PlayerInteractEvent event = new PlayerInteractEvent(null, null, null, null, null);65 pluginManager.registerEvents(plugin, plugin);66 pluginManager.callEvent(event);67 assertFalse(plugin.unannotatedPlayerInteractEventExecuted);68 assertFalse(plugin.annotatedBlockBreakEventExecuted);69 assertTrue(plugin.annotatedPlayerInteractEventExecuted);70 }71 @Test72 void test_ManualListener_Registration()73 {74 MockBukkit.getMock().getPluginManager().registerEvents(plugin, plugin);75 assertEquals(3, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);76 pluginManager.unregisterPluginEvents(plugin);77 assertEquals(0, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);78 MockBukkit.getMock().getPluginManager().registerEvents(plugin, plugin);79 MockBukkit.getMock().getPluginManager().registerEvents(plugin, plugin);80 assertEquals(6, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);81 pluginManager.unregisterPluginEvents(plugin);82 assertEquals(0, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);83 }84 @Test85 void test_AutomaticListener_DeRegistration()86 {87 MockBukkit.getMock().getPluginManager().registerEvents(plugin, plugin);88 assertEquals(3, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);89 MockBukkit.unmock();90 assertEquals(0, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);91 }92 @Test93 void getPlugin_PluginName_Plugin()94 {95 Plugin plugin = pluginManager.getPlugin("MockBukkitTestPlugin");96 assertNotNull(plugin);97 assertTrue(plugin instanceof TestPlugin);98 }99 @Test100 void getPlugin_UnknownName_Nothing()101 {102 Plugin plugin = pluginManager.getPlugin("NoPlugin");103 assertNull(plugin);104 }105 @Test106 void getCommands_Default_PluginCommand()107 {108 Collection<PluginCommand> commands = pluginManager.getCommands();109 assertEquals(3, commands.size());110 Iterator<PluginCommand> iterator = commands.iterator();111 assertEquals("mockcommand", iterator.next().getName());112 assertEquals("testcommand", iterator.next().getName());113 assertEquals("othercommand", iterator.next().getName());114 assertFalse(iterator.hasNext());115 }116 @Test117 void assertEventFired_PredicateTrue_DoesNotAssert()118 {119 Player player = server.addPlayer();120 BlockBreakEvent eventToFire = new BlockBreakEvent(null, player);121 pluginManager.callEvent(eventToFire);122 pluginManager.assertEventFired(event ->123 event instanceof BlockBreakEvent && ((BlockBreakEvent) event).getPlayer().equals(player)124 );125 }126 @Test127 void assertEventFired_PredicateFalse_Asserts()128 {129 Player player = server.addPlayer();130 BlockBreakEvent eventToFire = new BlockBreakEvent(null, player);131 pluginManager.callEvent(eventToFire);132 assertThrows(AssertionError.class, () -> pluginManager.assertEventFired(event -> false));133 }134 @Test135 void assertListenerRan_With_Order()136 {137 server.getPluginManager().registerEvents(plugin, plugin);138 Player p = server.addPlayer();139 BlockBreakEvent event = new BlockBreakEvent(null, p);140 assertTrue(plugin.ignoredCancelledEvent);141 pluginManager.callEvent(event);142 assertTrue(event.isCancelled());143 assertTrue(plugin.ignoredCancelledEvent);144 }145 @Test146 void assertEventFired_EventWasFired_DoesNotAssert()147 {148 BlockBreakEvent event = new BlockBreakEvent(null, null);149 pluginManager.callEvent(event);150 pluginManager.assertEventFired(BlockBreakEvent.class);151 }152 @Test153 void assertEventFired_EventWasNotFired_Asserts()154 {155 assertThrows(AssertionError.class, () -> pluginManager.assertEventFired(BlockBreakEvent.class));156 }157 @Test158 void getPermission_NoPermission_Null()159 {160 assertNull(pluginManager.getPermission("mockbukkit.perm"));161 }162 @Test163 void getPermission_PermissionAdded_NotNull()164 {165 Permission permission = new Permission("mockbukkit.perm");166 pluginManager.addPermission(permission);167 assertNotNull(pluginManager.getPermission(permission.getName()));168 }169 @Test170 void getDefaultPermission_OpPermissionAddedAndAsked_ContainsPermission()171 {172 Permission permission = new Permission("mockbukkit.perm", PermissionDefault.OP);173 pluginManager.addPermission(permission);174 assertTrue(pluginManager.getDefaultPermissions(true).contains(permission));175 }176 @Test177 void getDefaultPermission_OpPermissionAskedButNotAdded_DoesNotContainPermission()178 {179 Permission permission = new Permission("mockbukkit.perm", PermissionDefault.NOT_OP);180 pluginManager.addPermission(permission);181 assertFalse(pluginManager.getDefaultPermissions(true).contains(permission));182 }183 @Test184 void removePermission_String() {185 Permission permission = new Permission("mockbukkit.perm");186 pluginManager.addPermission(permission);187 assertTrue(pluginManager.getPermissions().contains(permission));188 pluginManager.removePermission("mockbukkit.perm");189 assertFalse(pluginManager.getPermissions().contains(permission));190 }191 @Test192 void disablePlugin_LoadedPlugin_PluginDisabled()193 {194 TestPlugin plugin = MockBukkit.load(TestPlugin.class);195 assertTrue(plugin.isEnabled());196 pluginManager.disablePlugin(plugin);197 assertFalse(plugin.isEnabled(), "Plugin was not disabled");198 assertTrue(plugin.onDisableExecuted);199 }200 @Test201 void disablePlugins_LoadedPlugins_AllDisabled()202 {203 TestPlugin plugin1 = MockBukkit.load(TestPlugin.class);204 TestPlugin plugin2 = MockBukkit.load(TestPlugin.class);205 assertTrue(plugin1.isEnabled());206 assertTrue(plugin2.isEnabled());207 pluginManager.disablePlugins();208 assertFalse(plugin1.isEnabled(), "Plugin1 was not disabled");209 assertFalse(plugin2.isEnabled(), "Plugin2 was not disabled");210 assertTrue(plugin1.onDisableExecuted);211 assertTrue(plugin2.onDisableExecuted);212 }213 @Test214 void disablePlugin_PluginDisableEvent_IsFired()215 {216 TestPlugin plugin = MockBukkit.load(TestPlugin.class);217 pluginManager.disablePlugin(plugin);218 pluginManager.assertEventFired(PluginDisableEvent.class, event -> event.getPlugin().equals(plugin));219 }220 @Test221 void disablePlugin_Unloaded_PluginDisableEvent_NotFired()222 {223 TestPlugin plugin = MockBukkit.load(TestPlugin.class);224 JavaPluginUtils.setEnabled(plugin, false);225 pluginManager.disablePlugin(plugin);226 pluginManager.assertEventNotFired(PluginDisableEvent.class);227 }228 @Test229 void disablePlugin_TasksCanceled()230 {231 TestPlugin plugin = MockBukkit.load(TestPlugin.class);232 BukkitRunnable runnable = new BukkitRunnable()233 {234 @Override235 public void run()236 {237 }238 };239 runnable.runTaskTimer(plugin, 1, 1);240 pluginManager.disablePlugin(plugin);241 assertTrue(runnable.isCancelled());242 }243 @Test244 void disablePlugin_ServicesUnregistered()245 {246 TestPlugin plugin = MockBukkit.load(TestPlugin.class);247 server.getServicesManager().register(Object.class, new Object(), plugin, ServicePriority.High);248 assertTrue(server.getServicesManager().isProvidedFor(Object.class));249 pluginManager.disablePlugin(plugin);250 assertFalse(server.getServicesManager().isProvidedFor(Object.class));251 }252 @Test253 void disablePlugin_DisablesPluginChannels()254 {255 TestPlugin plugin = MockBukkit.load(TestPlugin.class);256 server.getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord");257 server.getMessenger().registerIncomingPluginChannel(plugin, "BungeeCord", (channel, player, message) ->258 {259 });260 assertTrue(server.getMessenger().isOutgoingChannelRegistered(plugin, "BungeeCord"));261 assertTrue(server.getMessenger().isIncomingChannelRegistered(plugin, "BungeeCord"));262 pluginManager.disablePlugin(plugin);263 assertFalse(server.getMessenger().isOutgoingChannelRegistered(plugin, "BungeeCord"));264 assertFalse(server.getMessenger().isIncomingChannelRegistered(plugin, "BungeeCord"));265 }266 @Test267 @Disabled("Not implemented yet")268 void disablePlugin_WorldChunkTicketsRemoved()269 {270 TestPlugin plugin = MockBukkit.load(TestPlugin.class);271 World world = server.createWorld(new WorldCreator(""));272 world.addPluginChunkTicket(0, 0, plugin);273 assertTrue(world.getPluginChunkTickets(0, 0).contains(plugin));274 pluginManager.disablePlugin(plugin);275 assertFalse(world.getPluginChunkTickets(0, 0).contains(plugin));276 }277 @Test278 void clearPlugins_LoadedPlugins_AllPluginsRemove()279 {280 TestPlugin plugin = MockBukkit.load(TestPlugin.class);281 assertTrue(plugin.isEnabled());282 pluginManager.clearPlugins();283 assertFalse(plugin.isEnabled(), "Plugin was not disabled");284 Plugin[] plugins = pluginManager.getPlugins();285 assertEquals(0, plugins.length);286 }287 @Test288 void subscribeToDefaultPerms()289 {290 Permissible player = server.addPlayer();291 pluginManager.subscribeToDefaultPerms(true, player);292 assertTrue(pluginManager.getDefaultPermSubscriptions(true).contains(player));293 }294 @Test295 void unsubscribeToDefaultPerms()296 {297 Permissible player = server.addPlayer();298 pluginManager.subscribeToDefaultPerms(true, player);299 pluginManager.unsubscribeFromDefaultPerms(true, player);300 assertFalse(pluginManager.getDefaultPermSubscriptions(true).contains(player));301 }302 @Test303 void eventThrowsException_RuntimeException_RethrowsSame()304 {305 pluginManager.registerEvents(new Listener()306 {307 @EventHandler308 public void event(BlockBreakEvent e)309 {310 throw new IllegalStateException();311 }312 }, MockBukkit.createMockPlugin());313 assertThrowsExactly(IllegalStateException.class, () -> pluginManager.callEvent(new BlockBreakEvent(null, null)));314 }315 @Test316 void eventThrowsException_NotRuntimeException_ThrowsEventHandlerException()317 {318 pluginManager.registerEvents(new Listener()319 {320 @EventHandler321 public void event(BlockBreakEvent e) throws Exception322 {323 throw new Exception();324 }325 }, MockBukkit.createMockPlugin());326 assertThrowsExactly(EventHandlerException.class, () -> pluginManager.callEvent(new BlockBreakEvent(null, null)));327 }328}...
Source:EventHandlerException.java
...3import java.io.Serial;4/**5 * Thrown when an event handler throws a non-{@link RuntimeException}6 */7public class EventHandlerException extends RuntimeException8{9 @Serial10 private static final long serialVersionUID = 6093700474770834429L;11 public EventHandlerException(@NotNull Throwable cause)12 {13 super(cause);14 }15}...
EventHandlerException
Using AI Code Generation
1import be.seeseemelk.mockbukkit.MockBukkit;2import be.seeseemelk.mockbukkit.ServerMock;3import be.seeseemelk.mockbukkit.entity.PlayerMock;4import be.seeseemelk.mockbukkit.event.EventCatcher;5import be.seeseemelk.mockbukkit.event.EventCatcherHandler;6import be.seeseemelk.mockbukkit.event.EventCatcherHandlerList;7import be.seeseemelk.mockbukkit.event.EventCatcherInfo;8import be.s
EventHandlerException
Using AI Code Generation
1package com.example;2import org.bukkit.event.Listener;3import org.bukkit.event.player.PlayerJoinEvent;4import org.junit.jupiter.api.Test;5import be.seeseemelk.mockbukkit.MockBukkit;6import be.seeseemelk.mockbukkit.ServerMock;7import be.seeseemelk.mockbukkit.exception.EventHandlerException;8public class ExampleTest {9 public void test() {10 ServerMock server = MockBukkit.mock();11 try {12 server.getPluginManager().registerEvents(new Listener() {13 public void onPlayerJoin(PlayerJoinEvent event) {14 throw new RuntimeException("Error");15 }16 }, null);17 } catch (EventHandlerException e) {18 e.printStackTrace();19 }20 MockBukkit.unmock();21 }22}23package com.example;24import org.bukkit.event.Listener;25import org.bukkit.event.player.PlayerJoinEvent;26import org.junit.jupiter.api.Test;27import be.seeseemelk.mockbukkit.MockBukkit;28import be.seeseemelk.mockbukkit.ServerMock;29import be.seeseemelk.mockbukkit.exception.EventHandlerException;30public class ExampleTest {31 public void test() {32 ServerMock server = MockBukkit.mock();33 try {34 server.getPluginManager().registerEvents(new Listener() {35 public void onPlayerJoin(PlayerJoinEvent event) {36 throw new RuntimeException("Error");37 }38 }, null);39 } catch (EventHandlerException e) {40 e.printStackTrace();41 }42 MockBukkit.unmock();43 }44}45package com.example;46import org.bukkit.event.Listener;47import org.bukkit.event.player.PlayerJoinEvent;48import org.junit.jupiter.api.Test;49import be.seeseemelk.mockbukkit.MockBukkit;50import be.seeseemelk.mockbukkit.ServerMock;51import be.seeseemelk.mockbukkit.exception.EventHandlerException;52public class ExampleTest {53 public void test() {54 ServerMock server = MockBukkit.mock();55 try {56 server.getPluginManager().registerEvents(new Listener() {57 public void onPlayerJoin(Player
EventHandlerException
Using AI Code Generation
1{2 public void onEnable()3 {4 getServer().getPluginManager().registerEvents(new Listener()5 {6 public void onPlayerJoin(PlayerJoinEvent event)7 {8 event.getPlayer().sendMessage("Welcome to the server!");9 }10 }, this);11 }12}13{14 public void onEnable()15 {16 getServer().getPluginManager().registerEvents(new Listener()17 {18 public void onPlayerJoin(PlayerJoinEvent event)19 {20 event.getPlayer().sendMessage("Welcome to the server!");21 }22 }, this);23 }24}25{26 public void onEnable()27 {28 getServer().getPluginManager().registerEvents(new Listener()29 {30 public void onPlayerJoin(PlayerJoinEvent event)31 {32 event.getPlayer().sendMessage("Welcome to the server!");33 }34 }, this);35 }36}37{38 public void onEnable()39 {40 getServer().getPluginManager().registerEvents(new Listener()41 {42 public void onPlayerJoin(PlayerJoinEvent event)43 {44 event.getPlayer().sendMessage("Welcome to the server!");45 }46 }, this);47 }48}49{50 public void onEnable()51 {52 getServer().getPluginManager().registerEvents(new Listener()53 {54 public void onPlayerJoin(PlayerJoinEvent event)55 {56 event.getPlayer().sendMessage("Welcome to the server!");57 }58 }, this);59 }60}
EventHandlerException
Using AI Code Generation
1import org.bukkit.event.Listener;2import org.bukkit.event.player.PlayerInteractEvent;3import org.bukkit.plugin.Plugin;4import org.bukkit.plugin.PluginManager;5import org.junit.Assert;6import org.junit.Before;7import org.junit.Test;8import org.junit.runner.RunWith;9import org.mockito.Mockito;10import org.powermock.api.mockito.PowerMockito;11import org.powermock.core.classloader.annotations.PrepareForTest;12import org.powermock.modules.junit4.PowerMockRunner;13import be.seeseemelk.mockbukkit.MockBukkit;14import be.seeseemelk.mockbukkit.ServerMock;15import be.seeseemelk.mockbukkit.exception.EventHandlerException;16@RunWith(PowerMockRunner.class)17@PrepareForTest({ MockBukkit.class, ServerMock.class })18public class Test2 {19 private PluginManager pluginManager;20 private Plugin plugin;21 private Listener listener;22 public void setUp() throws Exception {23 ServerMock server = PowerMockito.mock(ServerMock.class);24 pluginManager = Mockito.mock(PluginManager.class);25 Mockito.when(server.getPluginManager()).thenReturn(pluginManager);26 PowerMockito.mockStatic(MockBukkit.class);27 PowerMockito.when(MockBukkit.getMock()).thenReturn(server);28 plugin = PowerMockito.mock(Plugin.class);29 Mockito.when(plugin.getName()).thenReturn("TestPlugin");30 listener = PowerMockito.mock(Listener.class);31 }32 public void test() {33 try {34 MockBukkit.loadEvents(plugin, listener);35 } catch (EventHandlerException e) {36 Assert.assertTrue(e.getMessage().contains("TestPlugin"));37 Assert.assertTrue(e.getMessage().contains("PlayerInteractEvent"));38 Assert.assertTrue(e.getMessage().contains("onPlayerInteract"));39 }40 }41}
EventHandlerException
Using AI Code Generation
1package be.seeseemelk.mockbukkit;2import static org.junit.jupiter.api.Assertions.assertThrows;3import org.bukkit.event.Event;4import org.bukkit.event.Listener;5import org.junit.jupiter.api.Test;6import be.seeseemelk.mockbukkit.event.EventDispatcher;7import be.seeseemelk.mockbukkit.event.EventHandlerException;8{9 public void testEventHandlerException()10 {11 EventDispatcher dispatcher = new EventDispatcher();12 Listener listener = new Listener() {};13 dispatcher.registerListener(listener);14 assertThrows(EventHandlerException.class, () -> {15 dispatcher.dispatch(new Event() {});16 });17 }18}19package be.seeseemelk.mockbukkit;20import static org.junit.jupiter.api.Assertions.assertThrows;21import org.bukkit.event.Event;22import org.bukkit.event.Listener;23import org.junit.jupiter.api.Test;24import be.seeseemelk.mockbukkit.event.EventDispatcher;25import be.seeseemelk.mockbukkit.exception.EventHandlerException;26{27 public void testEventHandlerException()28 {29 EventDispatcher dispatcher = new EventDispatcher();30 Listener listener = new Listener() {};31 dispatcher.registerListener(listener);32 assertThrows(EventHandlerException.class, () -> {33 dispatcher.dispatch(new Event() {});34 });35 }36}37package be.seeseemelk.mockbukkit;38import static org.junit.jupiter.api.Assertions.assertThrows;39import org.bukkit.event.Event;40import org.bukkit.event.Listener;41import org.junit.jupiter.api.Test;42import be.seeseemelk.mockbukkit.event.EventDispatcher;43import be.seeseemelk.mockbukkit.exception.EventHandlerException;44{45 public void testEventHandlerException()46 {47 EventDispatcher dispatcher = new EventDispatcher();48 Listener listener = new Listener() {};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!