### Run Tests with Maven
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/getting_started
This command executes all tests in a Maven project. MockBukkit tests will be run as part of this process if the dependency is correctly configured.
```bash
mvn test
```
--------------------------------
### Run Tests with Gradle
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/getting_started
This command executes all tests in a Gradle project. MockBukkit tests will be run as part of this process if the dependency is correctly configured.
```bash
gradle test
```
--------------------------------
### MockBukkit Test Class Setup and Execution (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/first_test
Demonstrates how to set up a test environment using MockBukkit, load a plugin, create a world, and execute a test case. Includes @BeforeEach for setup, @AfterEach for teardown, and @Test for the actual test logic. This pattern is crucial for unit testing Bukkit plugins without a live server.
```java
package org.mockbukkit.docsdemo;
import org.mockbukkit.mockbukkit.MockBukkit;
import org.mockbukkit.mockbukkit.ServerMock;
import org.bukkit.Location;
import org.bukkit.World;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class DemoPluginTest {
World world;
@BeforeEach
void setUp() {
ServerMock mock = MockBukkit.mock();
DemoPlugin plugin = MockBukkit.load(DemoPlugin.class);
this.world = mock.addSimpleWorld("test");
}
@AfterEach
void tearDown() {
MockBukkit.unmock();
}
@Test
void test() {
world.createExplosion(new Location(world, 0, 0, 0), 0.2f);
}
}
```
```kotlin
package org.mockbukkit.docsdemo
import org.mockbukkit.mockbukkit.MockBukkit
import org.mockbukkit.mockbukkit.ServerMock
import org.bukkit.Location
import org.bukkit.World
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import kotlin.jvm.java
class DemoPluginTest {
private lateinit var world: World
@BeforeEach
fun setUp() {
val mock: ServerMock = MockBukkit.mock()
val plugin = MockBukkit.load(DemoPlugin::class.java)
world = mock.addSimpleWorld("test")
}
@AfterEach
fun tearDown() {
MockBukkit.unmock()
}
@Test
fun test() {
world.createExplosion(Location(world, 0.0, 0.0, 0.0), 0.2f)
}
}
```
--------------------------------
### Add MockBukkit Dependency for Gradle (Groovy)
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/getting_started
This snippet demonstrates how to add the MockBukkit dependency to a Gradle project using Groovy syntax. It specifies the dependency coordinates and marks it for test implementation.
```groovy
dependencies {
testImplementation 'org.mockbukkit.mockbukkit:mockbukkit-v1.21:4.0.0'
}
```
--------------------------------
### Create MockBukkit Test Class Setup and Teardown
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/first_test
Demonstrates the basic structure of a test class in Java and Kotlin, including setting up the mock server and loading the plugin before each test, and tearing them down afterwards. This is essential for isolating tests.
```java
import org.bukkit.plugin.java.JavaPlugin;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import be.seeseemelk.mockbukkit.MockBukkit;
import be.seeseemelk.mockbukkit.ServerMock;
public class MyPluginTests {
private ServerMock server;
private MyPlugin plugin;
@BeforeEach
public void setUp() {
// Start the mock server
server = MockBukkit.mock();
// Load your plugin
plugin = MockBukkit.load(MyPlugin.class);
}
@AfterEach
public void tearDown() {
// Stop the mock server
MockBukkit.unmock();
}
@Test
public void thisTestWillFail() {
// Perform your test
}
}
```
```kotlin
import org.bukkit.plugin.java.JavaPlugin
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import be.seeseemelk.mockbukkit.MockBukkit
import be.seeseemelk.mockbukkit.ServerMock
open class MyPluginTests {
private lateinit var server: ServerMock
private lateinit var plugin: MyPlugin
@BeforeEach
fun setUp() {
// Start the mock server
server = MockBukkit.mock()
// Load your plugin
plugin = MockBukkit.load(MyPlugin::class.java)
}
@AfterEach
fun tearDown() {
// Stop the mock server
MockBukkit.unmock()
}
@Test
fun thisTestWillFail() {
// Perform your test
}
}
```
--------------------------------
### MockBukkit Plugin Class Example
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/first_test
Provides an example of a simple Bukkit plugin class in both Java and Kotlin, demonstrating the `onEnable` and `onDisable` methods. This serves as a base for testing plugin functionality.
```java
package org.mockbukkit.docsdemo;
import org.bukkit.plugin.java.JavaPlugin;
public class DemoPlugin extends JavaPlugin {
@Override
public void onEnable() {
getLogger().info("DemoPlugin enabled");
}
@Override
public void onDisable() {
getLogger().info("Plugin disabled");
}
}
```
```kotlin
package org.mockbukkit.docsdemo
import org.bukkit.plugin.java.JavaPlugin
open class DemoPlugin: JavaPlugin() {
override fun onEnable() {
logger.info("${this.name} enabled")
}
override fun onDisable() {
logger.info("${this.name} disabled")
}
}
```
--------------------------------
### Add MockBukkit Dependency for Gradle (Kotlin DSL)
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/getting_started
This snippet shows how to add the MockBukkit dependency to a Gradle project using Kotlin DSL. It specifies the dependency coordinates and marks it for test implementation.
```kotlin
dependencies {
testImplementation("org.mockbukkit.mockbukkit:mockbukkit-v1.21:4.0.0")
}
```
--------------------------------
### Add MockBukkit Dependency for Maven
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/getting_started
This snippet shows how to add the MockBukkit dependency to your Maven project's pom.xml file. It specifies the group ID, artifact ID (including the target Bukkit version), and the version of MockBukkit. The scope is set to 'test', indicating it's only used during testing.
```xml
org.mockbukkit.mockbukkit
mockbukkit-v1.21
4.0.0
test
```
--------------------------------
### Catching Exceptions with JUnit assertThrow()
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/first_test
This example demonstrates using JUnit's assertThrow() method to catch and verify expected exceptions during testing. It's particularly useful for testing code that is expected to throw specific errors, such as unimplemented operations.
```java
Not implemented
org.mockbukkit.mockbukkit.UnimplementedOperationException: Not implemented
at app//org.mockbukkit.mockbukkit.WorldMock.createExplosion(WorldMock.java:1928)
at app//org.mockbukkit.docsdemo.DemoPluginTest.lambda$test$0(DemoPluginTest.java:32)
at app//org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:53)
at app//org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:35)
at app//org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:3128)
at app//org.mockbukkit.docsdemo.DemoPluginTest.test(DemoPluginTest.java:32)
at java.base@21.0.4/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
at java.base@21.0.4/java.lang.reflect.Method.invoke(Method.java:580)
at app//org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:766)
at app//org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at app//org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
at app//org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
at app//org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at app//org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
at app//org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$8(TestMethodTestDescriptor.java:217)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:156)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:146)
at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:144)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:143)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:100)
at java.base@21.0.4/java.util.ArrayList.forEach(ArrayList.java:1596)
at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:160)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:146)
```
--------------------------------
### Get Current Scheduler Tick (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/scheduler
This snippet demonstrates how to retrieve the current tick count of the scheduler since MockBukkit was initialized. This method is exclusive to MockBukkit and helps in tracking the scheduler's progress.
```java
long tick = server.getScheduler().getCurrentTick();
```
```kotlin
val tick: Long = server.scheduler.getCurrentTick();
```
--------------------------------
### Assert Event Fired with Custom Failure Message in Java and Kotlin
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/events
This example shows how to provide a custom error message when an event assertion fails. By including a string argument in the `assertEventFired` method, developers can specify a more informative message that will be displayed if the event is not fired as expected. This improves the clarity of test failures.
```java
public class MyPluginTests {
private ServerMock server;
@BeforeEach
public void setUp() {
server = MockBukkit.mock();
}
@AfterEach
public void tearDown() {
MockBukkit.unmock();
}
@Test
public void testEvent() {
Player player = server.addPlayer();
player.setGameMode(GameMode.CREATIVE);
server.getPluginManager().assertEventFired(PlayerGameModeChangeEvent.class, "The event was not fired!");
}
}
```
```kotlin
class MyPluginTests {
private lateinit var server: ServerMock
@BeforeEach
fun setUp() {
server = MockBukkit.mock()
}
@AfterEach
fun tearDown() {
MockBukkit.unmock()
}
@Test
fun testEvent() {
val player = server.addPlayer()
player.gameMode = GameMode.CREATIVE
server.pluginManager.assertEventFired(PlayerGameModeChangeEvent::class.java, "The event was not fired!")
}
}
```
--------------------------------
### Execute Gradle Test Task
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/first_test
This command executes the test task using Gradle. It's used to run tests for the MockBukkit project. The output indicates a successful build with all tests up-to-date.
```bash
./gradlew test
```
--------------------------------
### Manage Adventure Platform in MockBukkit (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/adventure
Demonstrates how to properly initialize and close the Adventure Audiences platform when using MockBukkit. This is crucial for preventing static field persistence issues that can affect consecutive tests. The solution involves calling `platform.close()` in the `onDisable()` method.
```java
BukkitAudiences platform;
public void onEnable() {
platform = BukkitAudiences.create(pluginInstance);
}
public void onDisable() {
platform.close();
}
```
```kotlin
lateinit var platform: BukkitAudiences
override fun onEnable() {
platform = BukkitAudiences.create(pluginInstance)
}
override fun onDisable() {
platform.close()
}
```
--------------------------------
### Add Multiple Players to Server (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/player
Demonstrates how to add a specified number of players to the MockBukkit server using `ServerMock.setPlayers(int)`. This is useful for scenarios requiring a larger player count for testing.
```java
ServerMock server = Mockbukkit.getMock();
server.setPlayers(20);
```
```kotlin
val server = Mockbukkit.getMock()
server.setPlayers(20)
```
--------------------------------
### Create Mock World in Kotlin
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/mock_world
This snippet shows how to create a simple mock Minecraft world using the Mockbukkit server API in Kotlin. It leverages on-the-fly generation of superflat worlds for efficient creation. The world is named 'my_world'.
```kotlin
val world = server.addSimpleWorld("my_world")
```
--------------------------------
### Execute Multiple Scheduler Ticks (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/scheduler
This snippet shows how to execute a specified number of scheduler ticks at once. This is beneficial for testing scenarios involving sequential delays or multiple timed events. The ticks are executed in order, simulating a real server environment.
```java
ServerMock server = Mockbukkit.getMock();
server.getScheduler().performTicks(100L);
```
```kotlin
val server = Mockbukkit.getMock()
server.scheduler.performTicks(100L)
```
--------------------------------
### Add Single Player to Server (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/player
Demonstrates how to add a single player to the MockBukkit server using the `addPlayer()` method. This method returns a `PlayerMock` object for further interaction. It can create a random player or a player with a specified name.
```java
PlayerMock player = server.addPlayer();
```
```kotlin
val player: PlayerMock = server.addPlayer()
```
```java
PlayerMock player = server.addPlayer("Player1");
```
```kotlin
val player: PlayerMock = server.addPlayer("Player1")
```
--------------------------------
### Create Mock World in Java
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/mock_world
This snippet demonstrates how to create a simple mock Minecraft world using the Mockbukkit server API in Java. It initializes a superflat world on demand, making world creation an inexpensive operation. The world is named 'my_world'.
```java
WorldMock world = server.addSimpleWorld("my_world");
```
--------------------------------
### Add Custom Player to Server (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/player
Shows how to add a pre-configured `PlayerMock` object to the MockBukkit server. This allows for detailed customization of player properties like name, UUID, and gamemode before adding them to the server.
```java
public PlayerMock getCustomPlayer(){
PlayerMock playerMock = new PlayerMock(server, "custom_name", UUID.randomUUID());
playerMock.setGameMode(GameMode.CREATIVE);
return playerMock;
}
public static void main(String[] args) {
PlayerMock playerMock = server.addPlayer(getCustomPlayer());
}
```
```kotlin
fun getCustomPlayer(): PlayerMock {
return PlayerMock(server, "custom_name", UUID.randomUUID()).apply {
gameMode = GameMode.CREATIVE
}
}
fun main() {
val playerMock = server.addPlayer(getCustomPlayer())
}
```
--------------------------------
### Create Custom Server Mock (Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/custom_server_mock
Instantiates a custom server mock by extending the ServerMock class and passing it to MockBukkit.mock(). This allows for custom implementations of server methods or specific mock behaviors. The returned instance can be retrieved using MockBukkit.getMock().
```kotlin
val server: MyCustomServerMock = Mockbukkit.mock(MyCustomServerMock())
```
--------------------------------
### Send and Receive Messages with MessageTarget (Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/message_target
Demonstrates sending a message to a SimpleEntityMock and retrieving it using nextMessage(). This is useful for testing message handling in command senders and entities.
```kotlin
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
// Assuming SimpleEntityMock is available and implements MessageTarget
class MessageTargetTest {
@Test
fun test_receive() {
val entity = SimpleEntityMock()
entity.sendMessage("Hello world!")
val message = entity.nextMessage()
assertEquals("Hello world!", message)
}
}
```
--------------------------------
### Run MockBukkit Migration with Maven Command
Source: https://docs.mockbukkit.org/docs/en/user_guide/migration/migrate_mockbukkit_4.0_openrewrite
Execute this Maven command to directly run the OpenRewrite migration scripts for MockBukkit. It specifies the recipe artifact and the active recipes for package and class renaming.
```bash
mvn org.openrewrite.maven:rewrite-maven-plugin:run \
-Drewrite.recipeArtifactCoordinates=org.mockbukkit.rewrite:openrewrite-recipes:1.0.2 \
-Drewrite.activeRecipes=org.mockbukkit.rewrite.PackageRename,org.mockbukkit.rewrite.ClassRename
```
--------------------------------
### Run OpenRewrite Refactoring with Gradle
Source: https://docs.mockbukkit.org/docs/en/user_guide/migration/migrate_mockbukkit_4.0_openrewrite
Execute this Gradle command to run the configured OpenRewrite refactoring tasks in your project. This command should be used after setting up the OpenRewrite plugin in your build.gradle file.
```bash
./gradlew rewriteRun
```
--------------------------------
### Send and Receive Messages with MessageTarget (Java)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/message_target
Demonstrates sending a message to a SimpleEntityMock and retrieving it using nextMessage(). This is useful for testing message handling in command senders and entities.
```java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
// Assuming SimpleEntityMock is available and implements MessageTarget
public class MessageTargetTest {
@Test
void test_receive(){
SimpleEntityMock entity = new SimpleEntityMock();
entity.sendMessage("Hello world!");
String message = entity.nextMessage();
assertEquals("Hello world!", message);
}
}
```
--------------------------------
### Execute One Scheduler Tick (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/scheduler
This snippet demonstrates how to execute a single tick of the scheduler using MockBukkit. It's useful for testing immediate scheduler actions. No external dependencies are required beyond MockBukkit.
```java
ServerMock server = Mockbukkit.getMock();
server.getScheduler().performOneTick();
```
```kotlin
val server = Mockbukkit.getMock()
server.scheduler.performOneTick()
```
--------------------------------
### Create Custom Server Mock (Java)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/custom_server_mock
Instantiates a custom server mock by extending the ServerMock class and passing it to MockBukkit.mock(). This allows for custom implementations of server methods or specific mock behaviors. The returned instance can be retrieved using MockBukkit.getMock().
```java
MyCustomServerMock server = MockBukkit.mock(new MyCustomServerMock());
```
--------------------------------
### Simulate Player Reconnecting (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/player
Shows how to simulate a player reconnecting to the server after a disconnection using the `reconnect()` method on a `PlayerMock` object. This restores the player's online status and full functionality.
```java
player.reconnect();
```
```kotlin
player.reconnect()
```
--------------------------------
### Run OpenRewrite Refactoring with Maven
Source: https://docs.mockbukkit.org/docs/en/user_guide/migration/migrate_mockbukkit_4.0_openrewrite
Execute this Maven command to run the configured OpenRewrite refactoring tasks in your project. This command should be used after setting up the OpenRewrite plugin in your POM file.
```bash
mvn rewrite:run
```
--------------------------------
### Gradle Test Execution Output
Source: https://docs.mockbukkit.org/docs/en/user_guide/introduction/first_test
This is the expected output when running the Gradle test task. It confirms that the build was successful and all tasks were up-to-date, indicating no tests were actually run but the build process completed without errors.
```bash
BUILD SUCCESSFUL in 522ms
4 actionable tasks: 4 up-to-date
```
--------------------------------
### Configure MockBukkit Migration in Gradle Kotlin DSL
Source: https://docs.mockbukkit.org/docs/en/user_guide/migration/migrate_mockbukkit_4.0_openrewrite
Configure the OpenRewrite plugin in your Gradle project using Kotlin DSL for MockBukkit migration. This involves applying the plugin, adding the MockBukkit recipe dependency, and defining the active recipes.
```kotlin
plugins {
id("org.openrewrite.rewrite") version "6.x.x"
}
dependencies {
// Add the Mockbukkit recipes
rewrite("org.mockbukkit.rewrite:openrewrite-recipes:1.0.2")
}
// Add the recipe source to your project’s rewrite configuration
rewrite {
activeRecipe("org.mockbukkit.rewrite.PackageRename")
activeRecipe("org.mockbukkit.rewrite.ClassRename")
}
```
--------------------------------
### Configure MockBukkit Migration in Maven POM
Source: https://docs.mockbukkit.org/docs/en/user_guide/migration/migrate_mockbukkit_4.0_openrewrite
Add the OpenRewrite plugin to your Maven project's POM file to configure the MockBukkit migration. This includes specifying the plugin version, active recipes, and the MockBukkit recipe dependency.
```xml
org.openrewrite.maven
rewrite-maven-plugin
5.42.2
org.mockbukkit.rewrite.PackageRename
org.mockbukkit.rewrite.ClassRename
org.mockbukkit.rewrite
openrewrite-recipes
1.0.2
```
--------------------------------
### Assert Messages Received by MessageTarget (Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/message_target
Shows how to use assertSaid() and assertNoMoreSaid() to verify messages sent to a SimpleEntityMock. These methods are crucial for ensuring correct message delivery and preventing unintended messages.
```kotlin
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
// Assuming SimpleEntityMock is available and implements MessageTarget
class MessageTargetTest {
@Test
fun test_assert() {
val entity = SimpleEntityMock()
entity.sendMessage("Hello world!")
entity.assertSaid("Hello world!")
entity.assertNoMoreSaid()
}
}
```
--------------------------------
### Assert Messages Received by MessageTarget (Java)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/message_target
Shows how to use assertSaid() and assertNoMoreSaid() to verify messages sent to a SimpleEntityMock. These methods are crucial for ensuring correct message delivery and preventing unintended messages.
```java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
// Assuming SimpleEntityMock is available and implements MessageTarget
public class MessageTargetTest {
@Test
void test_assert(){
SimpleEntityMock entity = new SimpleEntityMock();
entity.sendMessage("Hello world!");
entity.assertSaid("Hello world!");
entity.assertNoMoreSaid();
}
}
```
--------------------------------
### Simulate Player Disconnecting (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/player
Illustrates how to simulate a player disconnecting from the server using the `disconnect()` method on a `PlayerMock` object. This action marks the player as offline while retaining their `OfflinePlayer` status.
```java
player.disconnect();
```
```kotlin
player.disconnect()
```
--------------------------------
### Assert Event Fired with Specific Values in Java and Kotlin
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/events
This code illustrates how to assert that an event was fired and also verify specific properties of that event. It uses a `Predicate` in Java or a lambda in Kotlin to define conditions that the fired event must meet, such as checking if the player's new game mode is `CREATIVE`. This allows for more granular testing of event data.
```java
public class MyPluginTests {
private ServerMock server;
@BeforeEach
public void setUp() {
server = MockBukkit.mock();
}
@AfterEach
public void tearDown() {
MockBukkit.unmock();
}
@Test
public void testEvent() {
Player player = server.addPlayer();
player.setGameMode(GameMode.CREATIVE);
server.getPluginManager().assertEventFired(PlayerGameModeChangeEvent.class, event -> {
event.getNewGameMode() == GameMode.CREATIVE;
});
}
}
```
```kotlin
class MyPluginTests {
private lateinit var server: ServerMock
@BeforeEach
fun setUp() {
server = MockBukkit.mock()
}
@AfterEach
fun tearDown() {
MockBukkit.unmock()
}
@Test
fun testEvent() {
val player = server.addPlayer()
player.gameMode = GameMode.CREATIVE
server.pluginManager.assertEventFired(PlayerGameModeChangeEvent::class.java) { event ->
event.newGameMode == GameMode.CREATIVE
}
}
}
```
--------------------------------
### Assert Player Gamemode (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/player
Provides a convenience method `assertGameMode(Gamemode)` on `PlayerMock` to easily verify a player's current gamemode. If the gamemode does not match the expected value, an `AssertionException` is thrown, failing the test.
```java
player.assertGameMode(GameMode.SURVIVAL);
```
```kotlin
player.assertGameMode(GameMode.SURVIVAL)
```
--------------------------------
### Exclude Paperweight Artifacts in Gradle (Kotlin DSL)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/paperweight
This snippet demonstrates how to exclude Paperweight artifacts during test time in a Gradle build script using Kotlin DSL. It ensures that MockBukkit can be used without conflicts by preventing the simultaneous provision of two server implementations. Note that this prevents the use of NMS behavior during tests.
```kotlin
dependencies {
paperweight.paperDevBundle("your-chosen-paper-version")
testImplementation("your-mockbukkit-dependency")
}
paperweight {
addServerDependencyTo = configurations.named(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME).map { setOf(it) }
}
```
--------------------------------
### Assert Event Fired in Java and Kotlin
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/events
This snippet demonstrates how to assert that a specific Bukkit event has been fired using MockBukkit. It initializes a mock server, adds a player, modifies their game mode, and then asserts that the `PlayerGameModeChangeEvent` was triggered. This is a fundamental test for event-driven logic.
```java
public class MyPluginTests {
private ServerMock server;
@BeforeEach
public void setUp() {
server = MockBukkit.mock();
}
@AfterEach
public void tearDown() {
MockBukkit.unmock();
}
@Test
public void testEvent() {
Player player = server.addPlayer();
player.setGameMode(GameMode.CREATIVE);
server.getPluginManager().assertEventFired(PlayerGameModeChangeEvent.class);
}
}
```
```kotlin
class MyPluginTests {
private lateinit var server: ServerMock
@BeforeEach
fun setUp() {
server = MockBukkit.mock()
}
@AfterEach
fun tearDown() {
MockBukkit.unmock()
}
@Test
fun testEvent() {
val player = server.addPlayer()
player.gameMode = GameMode.CREATIVE
server.pluginManager.assertEventFired(PlayerGameModeChangeEvent::class.java)
}
}
```
--------------------------------
### Rename Entity in Mockbukkit
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/entity
Allows renaming an entity within the Mockbukkit environment. This is a straightforward method to change the display name of an entity for testing purposes.
```java
```java
entity.setName("new-name");
```
```
```kotlin
```kotlin
entity.setName("new-name")
```
```
--------------------------------
### Assert Entity Location in Mockbukkit
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/entity
Asserts that an entity is within a specified range of a given location. This method is useful for verifying entity positioning in tests. It takes a Location object and a double representing the allowed distance.
```java
```java
@Test
void test_AssertLocation() {
//Assumes you already have entity instance
entity.assertLocation(new Location(entity.getWorld(),0,0,0),2);
}
```
```
```kotlin
```kotlin
@Test
fun test_AssertLocation() {
//Assumes you already have entity instance
entity.assertLocation(Location(entity.getWorld(),0,0,0),2)
}
```
```
--------------------------------
### Assert Entity Teleportation in Mockbukkit
Source: https://docs.mockbukkit.org/docs/en/user_guide/entities/entity
Asserts whether an entity has been teleported or not. Includes methods to check if teleportation occurred and if it did not. The teleported flag can be cleared using `clearTeleported()`.
```java
```java
@Test
void test_assertTeleported() {
//Assumes you already have entity instance
entity.assertTeleported(location, distance);
}
@Test
void test_assertTeleported() {
//Assumes you already have entity instance
entity.assertNotTeleported();
}
```
```
```kotlin
```kotlin
@Test
fun test_assertTeleported() {
//Assumes you already have entity instance
entity.assertTeleported(location, distance)
}
@Test
fun test_assertTeleported() {
//Assumes you already have entity instance
entity.assertNotTeleported()
}
```
```
--------------------------------
### Assert Event Not Fired with MockBukkit (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/events
Demonstrates how to use MockBukkit's `assertEventNotFired` method to check if a specific Bukkit event was not triggered. This is useful for testing scenarios where an event should not occur. It requires the MockBukkit library and standard Bukkit event classes.
```java
public class MyPluginTests {
private ServerMock server;
@BeforeEach
public void setUp() {
server = MockBukkit.mock();
}
@AfterEach
public void tearDown() {
MockBukkit.unmock();
}
@Test
public void testEvent() {
Player player = server.addPlayer();
player.setGameMode(GameMode.CREATIVE);
server.getPluginManager().assertEventNotFired(PlayerMoveEvent.class);
}
}
```
```kotlin
class MyPluginTests {
private lateinit var server: ServerMock
@BeforeEach
fun setUp() {
server = MockBukkit.mock()
}
@AfterEach
fun tearDown() {
MockBukkit.unmock()
}
@Test
fun testEvent() {
val player = server.addPlayer()
player.gameMode = GameMode.CREATIVE
server.pluginManager.assertEventNotFired(PlayerMoveEvent::class.java)
}
}
```
--------------------------------
### Assert Event Not Fired with Custom Message (Java & Kotlin)
Source: https://docs.mockbukkit.org/docs/en/user_guide/advanced/events
Shows how to assert that a Bukkit event was not fired using MockBukkit, while also providing a custom error message that will be displayed if the assertion fails. This enhances test readability and debugging. It depends on MockBukkit and Bukkit event classes.
```java
public class MyPluginTests {
private ServerMock server;
@BeforeEach
public void setUp() {
server = MockBukkit.mock();
}
@AfterEach
public void tearDown() {
MockBukkit.unmock();
}
@Test
public void testEvent() {
Player player = server.addPlayer();
player.setGameMode(GameMode.CREATIVE);
server.getPluginManager().assertEventNotFired(PlayerMoveEvent.class, "The event was fired!");
}
}
```
```kotlin
class MyPluginTests {
private lateinit var server: ServerMock
@BeforeEach
fun setUp() {
server = MockBukkit.mock()
}
@AfterEach
fun tearDown() {
MockBukkit.unmock()
}
@Test
fun testEvent() {
val player = server.addPlayer()
player.gameMode = GameMode.CREATIVE
server.pluginManager.assertEventNotFired(PlayerMoveEvent::class.java, "The event was fired!")
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.