From dd9526cd4d330051936270d23d4cc288bb93cdb5 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Thu, 23 Apr 2026 09:28:00 +0200 Subject: [PATCH 1/5] JUnit 5 cleanup for packages api and command --- .../fr/xephi/authme/api/v3/AuthMeApiTest.java | 86 +++++++++--------- .../authme/api/v3/AuthMePlayerImplTest.java | 9 +- .../command/CommandConsistencyTest.java | 7 +- .../authme/command/CommandHandlerTest.java | 39 ++++---- .../command/CommandInitializerTest.java | 27 +++--- .../authme/command/CommandMapperTest.java | 69 +++++++------- .../authme/command/CommandUtilsTest.java | 45 +++++----- .../authme/command/PlayerCommandTest.java | 17 ++-- .../authme/AccountsCommandTest.java | 32 +++---- .../executable/authme/AuthMeCommandTest.java | 17 +--- .../executable/authme/BackupCommandTest.java | 13 +-- .../ChangePasswordAdminCommandTest.java | 15 ++-- .../authme/ConverterCommandTest.java | 25 +++--- .../authme/FirstSpawnCommandTest.java | 15 ++-- .../authme/ForceLoginCommandTest.java | 21 ++--- .../authme/GetEmailCommandTest.java | 15 ++-- .../executable/authme/GetIpCommandTest.java | 17 ++-- .../authme/LastLoginCommandTest.java | 27 +++--- .../authme/PurgeBannedPlayersCommandTest.java | 13 +-- .../executable/authme/PurgeCommandTest.java | 23 ++--- .../authme/PurgeLastPositionCommandTest.java | 19 ++-- .../authme/PurgePlayerCommandTest.java | 18 ++-- .../authme/RecentPlayersCommandTest.java | 15 ++-- .../authme/RegisterAdminCommandTest.java | 31 +++---- .../executable/authme/ReloadCommandTest.java | 23 ++--- .../authme/SetEmailCommandTest.java | 25 +++--- .../authme/SetFirstSpawnCommandTest.java | 15 ++-- .../authme/SetSpawnCommandTest.java | 15 ++-- .../executable/authme/SpawnCommandTest.java | 15 ++-- .../authme/SwitchAntiBotCommandTest.java | 19 ++-- .../authme/TotpDisableAdminCommandTest.java | 21 ++--- .../authme/TotpViewStatusCommandTest.java | 19 ++-- .../authme/UnregisterAdminCommandTest.java | 17 ++-- .../authme/UpdateHelpMessagesCommandTest.java | 17 ++-- .../authme/debug/DataStatisticsTest.java | 24 ++--- .../authme/debug/DebugCommandTest.java | 28 +++--- .../debug/DebugSectionConsistencyTest.java | 13 ++- .../authme/debug/DebugSectionUtilsTest.java | 25 +++--- .../debug/HasPermissionCheckerTest.java | 23 ++--- .../debug/MySqlDefaultChangerColumnsTest.java | 11 ++- .../authme/debug/MySqlDefaultChangerTest.java | 21 ++--- .../authme/debug/PlayerAuthViewerTest.java | 26 +++--- ...pMessageAndHelpSectionConsistencyTest.java | 7 +- .../help/HelpMessagesConsistencyTest.java | 11 ++- .../command/help/HelpMessagesServiceTest.java | 30 +++---- .../authme/command/help/HelpProviderTest.java | 90 +++++++++---------- 46 files changed, 454 insertions(+), 656 deletions(-) diff --git a/authme-core/src/test/java/fr/xephi/authme/api/v3/AuthMeApiTest.java b/authme-core/src/test/java/fr/xephi/authme/api/v3/AuthMeApiTest.java index e276559ea1..938b8b22bd 100644 --- a/authme-core/src/test/java/fr/xephi/authme/api/v3/AuthMeApiTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/api/v3/AuthMeApiTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.api.v3; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.data.auth.PlayerAuth; @@ -22,10 +18,11 @@ import org.bukkit.World; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.time.Instant; import java.util.Arrays; @@ -55,8 +52,7 @@ * Test for {@link AuthMeApi}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AuthMeApiTest { +class AuthMeApiTest { @InjectMocks private AuthMeApi api; @@ -75,11 +71,9 @@ public class AuthMeApiTest { private AuthMe authMe; @Mock private GeoIpService geoIpService; - @Captor - private ArgumentCaptor authCaptor; @Test - public void shouldReturnInstanceOrNull() { + void shouldReturnInstanceOrNull() { AuthMeApi result = AuthMeApi.getInstance(); assertThat(result, sameInstance(api)); @@ -88,7 +82,7 @@ public void shouldReturnInstanceOrNull() { } @Test - public void shouldReturnIfPlayerIsAuthenticated() { + void shouldReturnIfPlayerIsAuthenticated() { // given String name = "Bobby"; Player player = mockPlayerWithName(name); @@ -103,7 +97,7 @@ public void shouldReturnIfPlayerIsAuthenticated() { } @Test - public void shouldReturnIfPlayerIsNpc() { + void shouldReturnIfPlayerIsNpc() { // given Player player = mock(Player.class); given(player.hasMetadata("NPC")).willReturn(true); @@ -117,7 +111,7 @@ public void shouldReturnIfPlayerIsNpc() { } @Test - public void shouldReturnIfPlayerIsUnrestricted() { + void shouldReturnIfPlayerIsUnrestricted() { // given String name = "Tester"; Player player = mockPlayerWithName(name); @@ -132,7 +126,7 @@ public void shouldReturnIfPlayerIsUnrestricted() { } @Test - public void shouldGetLastLocation() { + void shouldGetLastLocation() { // given String name = "Gary"; Player player = mockPlayerWithName(name); @@ -164,7 +158,7 @@ public void shouldGetLastLocation() { } @Test - public void shouldGetLastIp() { + void shouldGetLastIp() { // given String name = "Gabriel"; Player player = mockPlayerWithName(name); @@ -182,7 +176,7 @@ public void shouldGetLastIp() { } @Test - public void shouldReturnNullAsLastIpForUnknownUser() { + void shouldReturnNullAsLastIpForUnknownUser() { // given String name = "Harrison"; given(playerCache.getAuth(name)).willReturn(null); @@ -198,7 +192,7 @@ public void shouldReturnNullAsLastIpForUnknownUser() { } @Test - public void shouldGetLastLogin() { + void shouldGetLastLogin() { // given String name = "David"; PlayerAuth auth = PlayerAuth.builder().name(name) @@ -215,7 +209,7 @@ public void shouldGetLastLogin() { } @Test - public void shouldHandleNullLastLogin() { + void shouldHandleNullLastLogin() { // given String name = "John"; PlayerAuth auth = PlayerAuth.builder().name(name) @@ -232,7 +226,7 @@ public void shouldHandleNullLastLogin() { } @Test - public void shouldGetLastLoginTime() { + void shouldGetLastLoginTime() { // given String name = "David"; PlayerAuth auth = PlayerAuth.builder().name(name) @@ -249,13 +243,16 @@ public void shouldGetLastLoginTime() { } @Test - public void testGetLastLoginMillis() { - AuthMeApi result = AuthMeApi.getInstance(); - assertThat(result.getLastLoginTime("notAPlayer"), nullValue()); + void shouldReturnNullLastLoginForUnknownPlayer() { + // given / when + Instant result = api.getLastLoginTime("notAPlayer"); + + // then + assertThat(result, nullValue()); } @Test - public void shouldHandleNullLastLoginTime() { + void shouldHandleNullLastLoginTime() { // given String name = "John"; PlayerAuth auth = PlayerAuth.builder().name(name) @@ -272,7 +269,7 @@ public void shouldHandleNullLastLoginTime() { } @Test - public void shouldReturnNullForUnavailablePlayer() { + void shouldReturnNullForUnavailablePlayer() { // given String name = "Numan"; Player player = mockPlayerWithName(name); @@ -286,7 +283,7 @@ public void shouldReturnNullForUnavailablePlayer() { } @Test - public void shouldCheckForRegisteredName() { + void shouldCheckForRegisteredName() { // given String name = "toaster"; given(dataSource.isAuthAvailable(name)).willReturn(true); @@ -299,7 +296,7 @@ public void shouldCheckForRegisteredName() { } @Test - public void shouldCheckPassword() { + void shouldCheckPassword() { // given String playerName = "Robert"; String password = "someSecretPhrase2983"; @@ -314,7 +311,7 @@ public void shouldCheckPassword() { } @Test - public void shouldReturnAuthNames() { + void shouldReturnAuthNames() { // given String[] names = {"bobby", "peter", "elisabeth", "craig"}; List auths = Arrays.stream(names) @@ -330,7 +327,7 @@ public void shouldReturnAuthNames() { } @Test - public void shouldReturnAuthRealNames() { + void shouldReturnAuthRealNames() { // given String[] names = {"Bobby", "peter", "Elisabeth", "CRAIG"}; List auths = Arrays.stream(names) @@ -346,7 +343,7 @@ public void shouldReturnAuthRealNames() { } @Test - public void shouldUnregisterPlayer() { + void shouldUnregisterPlayer() { // given Player player = mock(Player.class); String name = "Donald"; @@ -360,7 +357,7 @@ public void shouldUnregisterPlayer() { } @Test - public void shouldUnregisterPlayerByName() { + void shouldUnregisterPlayerByName() { // given Server server = mock(Server.class); ReflectionTestUtils.setField(Bukkit.class, null, "server", server); @@ -376,7 +373,7 @@ public void shouldUnregisterPlayerByName() { } @Test - public void shouldChangePassword() { + void shouldChangePassword() { // given String name = "Bobby12"; String password = "resetPw!"; @@ -389,7 +386,7 @@ public void shouldChangePassword() { } @Test - public void shouldReturnAuthMeInstance() { + void shouldReturnAuthMeInstance() { // given / when AuthMe result = api.getPlugin(); @@ -398,7 +395,7 @@ public void shouldReturnAuthMeInstance() { } @Test - public void shouldReturnVersion() { + void shouldReturnVersion() { // given / when String result = api.getPluginVersion(); @@ -407,7 +404,7 @@ public void shouldReturnVersion() { } @Test - public void shouldForceLogin() { + void shouldForceLogin() { // given Player player = mock(Player.class); @@ -419,7 +416,7 @@ public void shouldForceLogin() { } @Test - public void shouldForceLogout() { + void shouldForceLogout() { // given Player player = mock(Player.class); @@ -431,7 +428,7 @@ public void shouldForceLogout() { } @Test - public void shouldForceRegister() { + void shouldForceRegister() { // given Player player = mock(Player.class); String pass = "test235"; @@ -445,7 +442,7 @@ public void shouldForceRegister() { } @Test - public void shouldForceRegisterAndNotAutoLogin() { + void shouldForceRegisterAndNotAutoLogin() { // given Player player = mock(Player.class); String pass = "test235"; @@ -459,7 +456,7 @@ public void shouldForceRegisterAndNotAutoLogin() { } @Test - public void shouldRegisterPlayer() { + void shouldRegisterPlayer() { // given String name = "Marco"; String password = "myP4ss"; @@ -473,6 +470,7 @@ public void shouldRegisterPlayer() { // then assertThat(result, equalTo(true)); verify(passwordSecurity).computeHash(password, name.toLowerCase(Locale.ROOT)); + ArgumentCaptor authCaptor = ArgumentCaptor.forClass(PlayerAuth.class); verify(dataSource).saveAuth(authCaptor.capture()); assertThat(authCaptor.getValue().getNickname(), equalTo(name.toLowerCase(Locale.ROOT))); assertThat(authCaptor.getValue().getRealName(), equalTo(name)); @@ -480,7 +478,7 @@ public void shouldRegisterPlayer() { } @Test - public void shouldNotRegisterAlreadyRegisteredPlayer() { + void shouldNotRegisterAlreadyRegisteredPlayer() { // given String name = "jonah"; given(dataSource.isAuthAvailable(name)).willReturn(true); @@ -495,7 +493,7 @@ public void shouldNotRegisterAlreadyRegisteredPlayer() { } @Test - public void shouldGetNamesByIp() { + void shouldGetNamesByIp() { // given String ip = "123.123.123.123"; List names = Arrays.asList("Morgan", "Batista", "QUINN"); @@ -510,7 +508,7 @@ public void shouldGetNamesByIp() { } @Test - public void shouldReturnGeoIpInfo() { + void shouldReturnGeoIpInfo() { // given String ip = "127.127.12.1"; given(geoIpService.getCountryCode(ip)).willReturn("XA"); @@ -526,7 +524,7 @@ public void shouldReturnGeoIpInfo() { } @Test - public void shouldReturnAuthMePlayerInfo() { + void shouldReturnAuthMePlayerInfo() { // given PlayerAuth auth = PlayerAuth.builder() .name("bobb") @@ -545,7 +543,7 @@ public void shouldReturnAuthMePlayerInfo() { } @Test - public void shouldReturnNullForNonExistentAuth() { + void shouldReturnNullForNonExistentAuth() { // given / when Optional result = api.getPlayerInfo("doesNotExist"); @@ -561,5 +559,3 @@ private static Player mockPlayerWithName(String name) { return player; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/api/v3/AuthMePlayerImplTest.java b/authme-core/src/test/java/fr/xephi/authme/api/v3/AuthMePlayerImplTest.java index 50e98e5a7a..a0ec516cee 100644 --- a/authme-core/src/test/java/fr/xephi/authme/api/v3/AuthMePlayerImplTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/api/v3/AuthMePlayerImplTest.java @@ -16,16 +16,16 @@ /** * Test for {@link AuthMePlayerImpl}. */ -public class AuthMePlayerImplTest { +class AuthMePlayerImplTest { @Test - public void shouldMapNullWithoutError() { + void shouldMapNullWithoutError() { // given / when / then assertThat(AuthMePlayerImpl.fromPlayerAuth(null), emptyOptional()); } @Test - public void shouldMapFromPlayerAuth() { + void shouldMapFromPlayerAuth() { // given PlayerAuth auth = PlayerAuth.builder() .name("victor") @@ -53,7 +53,7 @@ public void shouldMapFromPlayerAuth() { } @Test - public void shouldHandleNullAndDefaultValues() { + void shouldHandleNullAndDefaultValues() { // given PlayerAuth auth = PlayerAuth.builder() .name("victor") @@ -93,4 +93,3 @@ protected boolean matchesSafely(Optional item) { }; } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/CommandConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/command/CommandConsistencyTest.java index 4233c38748..4208ea368c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/CommandConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/CommandConsistencyTest.java @@ -13,20 +13,20 @@ import java.util.Map; import static fr.xephi.authme.TestHelper.getJarFile; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * Checks that the commands declared in plugin.yml correspond * to the ones built by the {@link CommandInitializer}. */ -public class CommandConsistencyTest { +class CommandConsistencyTest { @Test - public void shouldHaveEqualDefinitions() { + void shouldHaveEqualDefinitions() { // given Collection> initializedCommands = initializeCommands(); Map> pluginFileLabels = getLabelsFromPluginFile(); @@ -82,4 +82,3 @@ private static Map> getLabelsFromPluginFile() { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java b/authme-core/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java index 60abe4e35d..ebc44795f0 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.injector.factory.Factory; import com.google.common.collect.Sets; import fr.xephi.authme.command.TestCommandsUtil.TestLoginCommand; @@ -16,10 +12,11 @@ import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import java.util.Collections; @@ -32,8 +29,8 @@ import static fr.xephi.authme.command.FoundResultStatus.SUCCESS; import static fr.xephi.authme.command.FoundResultStatus.UNKNOWN_LABEL; import static java.util.Arrays.asList; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; @@ -51,8 +48,7 @@ // often consists of only one element, e.g. myMethod(asList("authme"), asList("my", "args"), ...) @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class CommandHandlerTest { +class CommandHandlerTest { private CommandHandler handler; @@ -66,14 +62,12 @@ public class CommandHandlerTest { private Messages messages; @Mock private HelpProvider helpProvider; - @Captor - private ArgumentCaptor cmdCaptor; private Map, ExecutableCommand> mockedCommands = new HashMap<>(); @BeforeEach @SuppressWarnings("unchecked") - public void initializeCommandMapper() { + void initializeCommandMapper() { given(commandMapper.getCommandClasses()).willReturn(Sets.newHashSet( ExecutableCommand.class, TestLoginCommand.class, TestRegisterCommand.class, TestUnregisterCommand.class)); setInjectorToMockExecutableCommandClasses(); @@ -107,7 +101,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { @Test - public void shouldCallMappedCommandWithArgs() { + void shouldCallMappedCommandWithArgs() { // given String bukkitLabel = "Authme"; String[] bukkitArgs = {"Login", "myPass"}; @@ -130,7 +124,7 @@ public void shouldCallMappedCommandWithArgs() { } @Test - public void shouldCallMappedCommandWithPreSplitParts() { + void shouldCallMappedCommandWithPreSplitParts() { // given CommandSender sender = mock(CommandSender.class); CommandDescription command = mock(CommandDescription.class); @@ -149,7 +143,7 @@ public void shouldCallMappedCommandWithPreSplitParts() { } @Test - public void shouldNotCallExecutableCommandIfNoPermission() { + void shouldNotCallExecutableCommandIfNoPermission() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -168,7 +162,7 @@ public void shouldNotCallExecutableCommandIfNoPermission() { } @Test - public void shouldNotCallExecutableForWrongArguments() { + void shouldNotCallExecutableForWrongArguments() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -191,7 +185,7 @@ public void shouldNotCallExecutableForWrongArguments() { } @Test - public void shouldUseCustomMessageUponArgumentMismatch() { + void shouldUseCustomMessageUponArgumentMismatch() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -214,7 +208,7 @@ public void shouldUseCustomMessageUponArgumentMismatch() { } @Test - public void shouldNotCallExecutableForWrongArgumentsAndPermissionDenied() { + void shouldNotCallExecutableForWrongArgumentsAndPermissionDenied() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -234,7 +228,7 @@ public void shouldNotCallExecutableForWrongArgumentsAndPermissionDenied() { } @Test - public void shouldNotCallExecutableForFailedParsing() { + void shouldNotCallExecutableForFailedParsing() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -254,7 +248,7 @@ public void shouldNotCallExecutableForFailedParsing() { } @Test - public void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() { + void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -271,6 +265,7 @@ public void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() { verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer")); verify(command, never()).getExecutableCommand(); verify(messages).send(sender, MessageKey.UNKNOWN_COMMAND); + ArgumentCaptor cmdCaptor = ArgumentCaptor.forClass(String.class); verify(messages).send(eq(sender), eq(MessageKey.COMMAND_DID_YOU_MEAN), cmdCaptor.capture()); assertThat(cmdCaptor.getValue(), containsString("test_cmd")); verify(messages).send(eq(sender), eq(MessageKey.COMMAND_SEE_HELP), anyString()); @@ -278,7 +273,7 @@ public void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() { } @Test - public void shouldNotCallExecutableForUnknownLabelAndNotSuggestCommand() { + void shouldNotCallExecutableForUnknownLabelAndNotSuggestCommand() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -299,7 +294,7 @@ public void shouldNotCallExecutableForUnknownLabelAndNotSuggestCommand() { } @Test - public void shouldStripWhitespace() { + void shouldStripWhitespace() { // given String bukkitLabel = "AuthMe"; String[] bukkitArgs = {" ", "", "REGISTER", " ", "testArg", " "}; @@ -321,5 +316,3 @@ public void shouldStripWhitespace() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java b/authme-core/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java index b388949b8c..e2bb00cf9a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java @@ -15,32 +15,32 @@ import java.util.function.BiConsumer; import java.util.regex.Pattern; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link CommandInitializer} to guarantee the integrity of the defined commands. */ -public class CommandInitializerTest { +class CommandInitializerTest { /** * Defines the maximum allowed depths for nesting CommandDescription instances. * Note that the depth starts at 0 (e.g. /authme), so a depth of 2 is something like /authme hello world */ - private static int MAX_ALLOWED_DEPTH = 1; + private static final int MAX_ALLOWED_DEPTH = 1; private static Collection commands; @BeforeAll - public static void initializeCommandCollection() { + static void initializeCommandCollection() { CommandInitializer commandInitializer = new CommandInitializer(); commands = commandInitializer.getCommands(); } @Test - public void shouldInitializeCommands() { + void shouldInitializeCommands() { // given/when/then // It obviously doesn't make sense to test much of the concrete data // that is being initialized; we just want to guarantee with this test @@ -52,7 +52,7 @@ public void shouldInitializeCommands() { } @Test - public void shouldNotBeNestedExcessively() { + void shouldNotBeNestedExcessively() { // given BiConsumer descriptionTester = (command, depth) -> assertThat(depth <= MAX_ALLOWED_DEPTH, equalTo(true)); @@ -63,7 +63,7 @@ public void shouldNotBeNestedExcessively() { /** Ensure that all children of a command stored the parent. */ @Test - public void shouldHaveConnectionBetweenParentAndChild() { + void shouldHaveConnectionBetweenParentAndChild() { // given BiConsumer connectionTester = new BiConsumer() { @Override @@ -84,7 +84,7 @@ public void accept(CommandDescription command, Integer depth) { } @Test - public void shouldUseProperLowerCaseLabels() { + void shouldUseProperLowerCaseLabels() { // given final Pattern invalidPattern = Pattern.compile("\\s"); BiConsumer labelFormatTester = new BiConsumer() { @@ -105,7 +105,7 @@ public void accept(CommandDescription command, Integer depth) { } @Test - public void shouldNotDefineSameLabelTwice() { + void shouldNotDefineSameLabelTwice() { // given final Set commandMappings = new HashSet<>(); BiConsumer uniqueMappingTester = new BiConsumer() { @@ -130,7 +130,7 @@ public void accept(CommandDescription command, Integer depth) { * detailed description should be longer and end with a period. */ @Test - public void shouldHaveProperDescription() { + void shouldHaveProperDescription() { // given BiConsumer descriptionTester = new BiConsumer() { @Override @@ -153,7 +153,7 @@ public void accept(CommandDescription command, Integer depth) { } @Test - public void shouldHaveOptionalArgumentsAfterMandatoryOnes() { + void shouldHaveOptionalArgumentsAfterMandatoryOnes() { // given BiConsumer argumentOrderTester = new BiConsumer() { @Override @@ -179,7 +179,7 @@ public void accept(CommandDescription command, Integer depth) { * clash with the label of the child. */ @Test - public void shouldNotHaveArgumentsIfCommandHasChildren() { + void shouldNotHaveArgumentsIfCommandHasChildren() { // given BiConsumer noArgumentForParentChecker = new BiConsumer() { @Override @@ -202,7 +202,7 @@ public void accept(CommandDescription command, Integer depth) { * count of arguments. */ @Test - public void shouldPointToSameExecutableCommandWithConsistentArgumentCount() { + void shouldPointToSameExecutableCommandWithConsistentArgumentCount() { // given final Map, Integer> mandatoryArguments = new HashMap<>(); final Map, Integer> totalArguments = new HashMap<>(); @@ -281,4 +281,3 @@ private static List getAbsoluteLabels(CommandDescription command) { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/CommandMapperTest.java b/authme-core/src/test/java/fr/xephi/authme/command/CommandMapperTest.java index 610a29618f..88b80cf21e 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/CommandMapperTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/CommandMapperTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.command.TestCommandsUtil.TestLoginCommand; import fr.xephi.authme.command.TestCommandsUtil.TestRegisterCommand; import fr.xephi.authme.command.TestCommandsUtil.TestUnregisterCommand; @@ -12,8 +8,11 @@ import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import java.util.Set; @@ -21,28 +20,28 @@ import static fr.xephi.authme.command.TestCommandsUtil.getCommandWithLabel; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; /** * Test for {@link CommandMapper}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class CommandMapperTest { +@ExtendWith(MockitoExtension.class) +class CommandMapperTest { private static List commands; - @InjectDelayed private CommandMapper mapper; @Mock @@ -52,20 +51,21 @@ public class CommandMapperTest { private CommandInitializer commandInitializer; @BeforeAll - public static void setUpCommandHandler() { + static void setUpCommandHandler() { commands = TestCommandsUtil.generateCommands(); } - @BeforeInjecting - public void setUpMocks() { + @BeforeEach + void setUpMocksAndMapper() { given(commandInitializer.getCommands()).willReturn(commands); + mapper = new CommandMapper(commandInitializer, permissionsManager); } // ----------- // mapPartsToCommand() tests // ----------- @Test - public void shouldMapPartsToLoginChildCommand() { + void shouldMapPartsToLoginChildCommand() { // given List parts = asList("authme", "login", "test1"); CommandSender sender = mock(CommandSender.class); @@ -84,7 +84,7 @@ public void shouldMapPartsToLoginChildCommand() { } @Test - public void shouldMapPartsToCommandWithNoCaseSensitivity() { + void shouldMapPartsToCommandWithNoCaseSensitivity() { // given List parts = asList("Authme", "REG", "arg1", "arg2"); CommandSender sender = mock(CommandSender.class); @@ -102,16 +102,16 @@ public void shouldMapPartsToCommandWithNoCaseSensitivity() { } @Test - public void shouldRejectCommandWithTooManyArguments() { + void shouldRejectCommandWithTooManyArguments() { // given List parts = asList("authme", "register", "pass123", "pass123", "pass123"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register"))); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS)); assertThat(result.getDifference(), equalTo(0.0)); @@ -120,16 +120,16 @@ public void shouldRejectCommandWithTooManyArguments() { } @Test - public void shouldRejectCommandWithTooFewArguments() { + void shouldRejectCommandWithTooFewArguments() { // given List parts = asList("authme", "Reg"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register"))); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS)); assertThat(result.getDifference(), equalTo(0.0)); @@ -138,16 +138,16 @@ public void shouldRejectCommandWithTooFewArguments() { } @Test - public void shouldSuggestCommandWithSimilarLabel() { + void shouldSuggestCommandWithSimilarLabel() { // given List parts = asList("authme", "reh", "pass123", "pass123"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register"))); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.UNKNOWN_LABEL)); assertThat(result.getDifference() < 0.75, equalTo(true)); @@ -157,16 +157,16 @@ public void shouldSuggestCommandWithSimilarLabel() { /** In contrast to the previous test, we test a command request with a very apart label. */ @Test - public void shouldSuggestMostSimilarCommand() { + void shouldSuggestMostSimilarCommand() { // given List parts = asList("authme", "asdfawetawty4asdca"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getCommandDescription(), not(nullValue())); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.UNKNOWN_LABEL)); assertThat(result.getDifference() > 0.75, equalTo(true)); @@ -175,16 +175,16 @@ public void shouldSuggestMostSimilarCommand() { } @Test - public void shouldHandleBaseWithWrongArguments() { + void shouldHandleBaseWithWrongArguments() { // given List parts = singletonList("unregister"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS)); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister"))); assertThat(result.getDifference(), equalTo(0.0)); @@ -193,22 +193,22 @@ public void shouldHandleBaseWithWrongArguments() { } @Test - public void shouldHandleUnknownBase() { + void shouldHandleUnknownBase() { // given List parts = asList("bogus", "label1", "arg1"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.MISSING_BASE_COMMAND)); assertThat(result.getCommandDescription(), nullValue()); } @Test - public void shouldHandleNullInput() { + void shouldHandleNullInput() { // given / when FoundCommandResult result = mapper.mapPartsToCommand(mock(CommandSender.class), null); @@ -218,7 +218,7 @@ public void shouldHandleNullInput() { } @Test - public void shouldMapToBaseWithProperArguments() { + void shouldMapToBaseWithProperArguments() { // given List parts = asList("Unreg", "player1"); CommandSender sender = mock(CommandSender.class); @@ -236,16 +236,16 @@ public void shouldMapToBaseWithProperArguments() { } @Test - public void shouldReturnChildlessBaseCommandWithArgCountError() { + void shouldReturnChildlessBaseCommandWithArgCountError() { // given List parts = asList("unregistER", "player1", "wrongArg"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS)); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister"))); assertThat(result.getDifference(), equalTo(0.0)); @@ -254,7 +254,7 @@ public void shouldReturnChildlessBaseCommandWithArgCountError() { } @Test - public void shouldPassCommandPathAsArgumentsToHelpCommand() { + void shouldPassCommandPathAsArgumentsToHelpCommand() { // given List parts = asList("email", "helptest", "arg1"); CommandSender sender = mock(CommandSender.class); @@ -272,7 +272,7 @@ public void shouldPassCommandPathAsArgumentsToHelpCommand() { } @Test - public void shouldRecognizeMissingPermissionForCommand() { + void shouldRecognizeMissingPermissionForCommand() { // given List parts = asList("authme", "login", "test1"); CommandSender sender = mock(CommandSender.class); @@ -291,7 +291,7 @@ public void shouldRecognizeMissingPermissionForCommand() { } @Test - public void shouldSupportAuthMePrefix() { + void shouldSupportAuthMePrefix() { // given List parts = asList("authme:unregister", "Betty"); CommandSender sender = mock(CommandSender.class); @@ -305,9 +305,8 @@ public void shouldSupportAuthMePrefix() { assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister"))); } - @SuppressWarnings("unchecked") @Test - public void shouldReturnExecutableCommandClasses() { + void shouldReturnExecutableCommandClasses() { // given / when Set> commandClasses = mapper.getCommandClasses(); @@ -317,5 +316,3 @@ public void shouldReturnExecutableCommandClasses() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java index 684b35e901..c6e3cf67a2 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java @@ -9,23 +9,23 @@ import java.util.Collections; import java.util.List; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link CommandUtils}. */ -public class CommandUtilsTest { +class CommandUtilsTest { private static Collection commands; @BeforeAll - public static void setUpTestCommands() { + static void setUpTestCommands() { commands = Collections.unmodifiableCollection(TestCommandsUtil.generateCommands()); } @Test - public void shouldReturnCommandPath() { + void shouldReturnCommandPath() { // given CommandDescription base = CommandDescription.builder() .labels("authme", "auth") @@ -49,7 +49,7 @@ public void shouldReturnCommandPath() { } @Test - public void shouldComputeMinAndMaxOnEmptyCommand() { + void shouldComputeMinAndMaxOnEmptyCommand() { // given CommandDescription command = getBuilderForArgsTest().register(); @@ -58,7 +58,7 @@ public void shouldComputeMinAndMaxOnEmptyCommand() { } @Test - public void shouldComputeMinAndMaxOnCommandWithMandatoryArgs() { + void shouldComputeMinAndMaxOnCommandWithMandatoryArgs() { // given CommandDescription command = getBuilderForArgsTest() .withArgument("Test", "Arg description", false) @@ -70,7 +70,7 @@ public void shouldComputeMinAndMaxOnCommandWithMandatoryArgs() { } @Test - public void shouldComputeMinAndMaxOnCommandIncludingOptionalArgs() { + void shouldComputeMinAndMaxOnCommandIncludingOptionalArgs() { // given CommandDescription command = getBuilderForArgsTest() .withArgument("arg1", "Arg description", false) @@ -83,7 +83,7 @@ public void shouldComputeMinAndMaxOnCommandIncludingOptionalArgs() { } @Test - public void shouldFormatSimpleArgument() { + void shouldFormatSimpleArgument() { // given CommandDescription command = TestCommandsUtil.getCommandWithLabel(commands, "authme"); List labels = Collections.singletonList("authme"); @@ -96,7 +96,7 @@ public void shouldFormatSimpleArgument() { } @Test - public void shouldFormatCommandWithMultipleArguments() { + void shouldFormatCommandWithMultipleArguments() { // given CommandDescription command = TestCommandsUtil.getCommandWithLabel(commands, "authme", "register"); List labels = Arrays.asList("authme", "reg"); @@ -110,7 +110,7 @@ public void shouldFormatCommandWithMultipleArguments() { @Test - public void shouldFormatCommandWithOptionalArgument() { + void shouldFormatCommandWithOptionalArgument() { // given CommandDescription command = TestCommandsUtil.getCommandWithLabel(commands, "email"); List labels = Collections.singletonList("email"); @@ -123,64 +123,64 @@ public void shouldFormatCommandWithOptionalArgument() { } @Test - public void shouldReturnEmptyListForNullInput() { + void shouldReturnEmptyListForNullInput() { assertSplitInput(null); } @Test - public void shouldReturnEmptyListForBlankInput() { + void shouldReturnEmptyListForBlankInput() { assertSplitInput(" \t \n "); } @Test - public void shouldReturnEmptyListForSlashOnlyInput() { + void shouldReturnEmptyListForSlashOnlyInput() { assertSplitInput("/"); } @Test - public void shouldReturnEmptyListForSlashWithOnlyWhitespace() { + void shouldReturnEmptyListForSlashWithOnlyWhitespace() { assertSplitInput("/ \t "); } @Test - public void shouldSplitSingleCommandWithoutLeadingSlash() { + void shouldSplitSingleCommandWithoutLeadingSlash() { assertSplitInput("authme", "authme"); } @Test - public void shouldSplitSingleCommandWithLeadingSlash() { + void shouldSplitSingleCommandWithLeadingSlash() { assertSplitInput("/authme", "authme"); } @Test - public void shouldTrimInputBeforeRemovingLeadingSlash() { + void shouldTrimInputBeforeRemovingLeadingSlash() { assertSplitInput(" /authme register ", "authme", "register"); } @Test - public void shouldIgnoreRepeatedWhitespaceBetweenParts() { + void shouldIgnoreRepeatedWhitespaceBetweenParts() { assertSplitInput("/authme register player password", "authme", "register", "player", "password"); } @Test - public void shouldSplitTabsAndNewlinesAsWhitespace() { + void shouldSplitTabsAndNewlinesAsWhitespace() { assertSplitInput("/authme\tregister\nplayer\r\npassword", "authme", "register", "player", "password"); } @Test - public void shouldSupportSlashSeparatedByWhitespaceFromCommand() { + void shouldSupportSlashSeparatedByWhitespaceFromCommand() { assertSplitInput("/ authme register", "authme", "register"); } @Test - public void shouldPreserveAdditionalLeadingSlashInFirstPart() { + void shouldPreserveAdditionalLeadingSlashInFirstPart() { assertSplitInput("//authme register", "/authme", "register"); } @Test - public void shouldPreserveNonEmptySpecialCharactersInsideParts() { + void shouldPreserveNonEmptySpecialCharactersInsideParts() { assertSplitInput("/login p@ss-word_123", "login", "p@ss-word_123"); } @@ -202,4 +202,3 @@ private static CommandDescription.CommandBuilder getBuilderForArgsTest() { .executableCommand(ExecutableCommand.class); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/PlayerCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/PlayerCommandTest.java index 01e01e0565..3c2bf8c14b 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/PlayerCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/PlayerCommandTest.java @@ -1,16 +1,14 @@ package fr.xephi.authme.command; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; @@ -25,14 +23,13 @@ * Test for {@link PlayerCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PlayerCommandTest { +class PlayerCommandTest { @Mock private Messages messages; @Test - public void shouldRejectNonPlayerSender() { + void shouldRejectNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); PlayerCommandImpl command = new PlayerCommandImpl(); @@ -46,7 +43,7 @@ public void shouldRejectNonPlayerSender() { } @Test - public void shouldCallRunCommandForPlayer() { + void shouldCallRunCommandForPlayer() { // given Player player = mock(Player.class); List arguments = Arrays.asList("arg1", "testarg2"); @@ -60,7 +57,7 @@ public void shouldCallRunCommandForPlayer() { } @Test - public void shouldRejectNonPlayerAndSendAlternative() { + void shouldRejectNonPlayerAndSendAlternative() { // given CommandSender sender = mock(CommandSender.class); PlayerCommandWithAlt command = new PlayerCommandWithAlt(); @@ -93,5 +90,3 @@ public String getAlternativeCommand() { } } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/AccountsCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/AccountsCommandTest.java index 77afcf066c..7637a0df4e 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/AccountsCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/AccountsCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.message.MessageKey; @@ -11,18 +7,19 @@ import fr.xephi.authme.service.CommonService; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; import java.util.List; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -34,8 +31,7 @@ * Test for {@link AccountsCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AccountsCommandTest { +class AccountsCommandTest { @InjectMocks private AccountsCommand command; @@ -45,11 +41,9 @@ public class AccountsCommandTest { private DataSource dataSource; @Mock private BukkitService bukkitService; - @Captor - private ArgumentCaptor captor; @Test - public void shouldGetAccountsOfCurrentUser() { + void shouldGetAccountsOfCurrentUser() { // given CommandSender sender = mock(CommandSender.class); given(sender.getName()).willReturn("Tester"); @@ -63,12 +57,13 @@ public void shouldGetAccountsOfCurrentUser() { // then verify(service).send(eq(sender), eq(MessageKey.ACCOUNTS_OWNED_SELF), eq("2")); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(sender).sendMessage(captor.capture()); assertThat(captor.getValue(), containsString("Toaster, Pester")); } @Test - public void shouldReturnUnknownUserForNullAuth() { + void shouldReturnUnknownUserForNullAuth() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("SomeUser"); @@ -84,7 +79,7 @@ public void shouldReturnUnknownUserForNullAuth() { } @Test - public void shouldReturnUnregisteredMessageForEmptyAuthList() { + void shouldReturnUnregisteredMessageForEmptyAuthList() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("SomeUser"); @@ -101,7 +96,7 @@ public void shouldReturnUnregisteredMessageForEmptyAuthList() { } @Test - public void shouldReturnSingleAccountMessage() { + void shouldReturnSingleAccountMessage() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("SomeUser"); @@ -121,7 +116,7 @@ public void shouldReturnSingleAccountMessage() { // Query by IP // ----- @Test - public void shouldReturnIpUnknown() { + void shouldReturnIpUnknown() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("123.45.67.89"); @@ -137,7 +132,7 @@ public void shouldReturnIpUnknown() { } @Test - public void shouldReturnSingleAccountForIpQuery() { + void shouldReturnSingleAccountForIpQuery() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("24.24.48.48"); @@ -153,7 +148,7 @@ public void shouldReturnSingleAccountForIpQuery() { } @Test - public void shouldReturnAccountListForIpQuery() { + void shouldReturnAccountListForIpQuery() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("98.76.41.122"); @@ -165,6 +160,7 @@ public void shouldReturnAccountListForIpQuery() { // then verify(service).send(eq(sender), eq(MessageKey.ACCOUNTS_OWNED_OTHER), eq("98.76.41.122"), eq("3")); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(sender).sendMessage(captor.capture()); assertThat(captor.getValue(), containsString("Tester, Lester, Taster")); } @@ -176,5 +172,3 @@ private static PlayerAuth authWithIp(String ip) { .build(); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/AuthMeCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/AuthMeCommandTest.java index d1957916c5..9c212ca512 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/AuthMeCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/AuthMeCommandTest.java @@ -3,17 +3,12 @@ import fr.xephi.authme.command.ExecutableCommand; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; import java.util.Collections; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -21,14 +16,10 @@ /** * Test for {@link AuthMeCommand}. */ -@ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AuthMeCommandTest { - @Captor - private ArgumentCaptor messagesCaptor; +class AuthMeCommandTest { @Test - public void shouldDisplayInformation() { + void shouldDisplayInformation() { // given ExecutableCommand command = new AuthMeCommand(); CommandSender sender = mock(CommandSender.class); @@ -37,9 +28,9 @@ public void shouldDisplayInformation() { command.executeCommand(sender, Collections.emptyList()); // then + ArgumentCaptor messagesCaptor = ArgumentCaptor.forClass(String.class); verify(sender, times(3)).sendMessage(messagesCaptor.capture()); assertThat(messagesCaptor.getAllValues().get(1), containsString("/authme help")); assertThat(messagesCaptor.getAllValues().get(2), containsString("/authme about")); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java index 5b9c62a9ea..5537aee925 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java @@ -1,14 +1,12 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.service.BackupService; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -19,8 +17,7 @@ * Test for {@link BackupCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class BackupCommandTest { +class BackupCommandTest { @InjectMocks private BackupCommand command; @@ -29,7 +26,7 @@ public class BackupCommandTest { private BackupService backupService; @Test - public void shouldStartBackup() { + void shouldStartBackup() { // given CommandSender sender = mock(CommandSender.class); @@ -40,5 +37,3 @@ public void shouldStartBackup() { verify(backupService).doBackup(BackupService.BackupCause.COMMAND, sender); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ChangePasswordAdminCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ChangePasswordAdminCommandTest.java index 35c36ba569..95f0a968bf 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ChangePasswordAdminCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ChangePasswordAdminCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.Management; import fr.xephi.authme.service.CommonService; @@ -11,8 +7,10 @@ import fr.xephi.authme.service.ValidationService.ValidationResult; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; @@ -25,8 +23,7 @@ * Test for {@link ChangePasswordAdminCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class ChangePasswordAdminCommandTest { +class ChangePasswordAdminCommandTest { @InjectMocks private ChangePasswordAdminCommand command; @@ -41,7 +38,7 @@ public class ChangePasswordAdminCommandTest { private Management management; @Test - public void shouldForwardRequestToManagement() { + void shouldForwardRequestToManagement() { // given String name = "theUser"; String pass = "newPassword"; @@ -57,7 +54,7 @@ public void shouldForwardRequestToManagement() { } @Test - public void shouldSendErrorToCommandSender() { + void shouldSendErrorToCommandSender() { // given String name = "theUser"; String pass = "newPassword"; @@ -74,5 +71,3 @@ public void shouldSendErrorToCommandSender() { verifyNoInteractions(management); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ConverterCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ConverterCommandTest.java index f97b99445c..08b5733f56 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ConverterCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ConverterCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.injector.factory.Factory; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.converter.Converter; @@ -14,8 +10,10 @@ import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.HashSet; @@ -24,9 +22,9 @@ import java.util.Set; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; @@ -40,8 +38,7 @@ * Test for {@link ConverterCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class ConverterCommandTest { +class ConverterCommandTest { @InjectMocks private ConverterCommand command; @@ -56,12 +53,12 @@ public class ConverterCommandTest { private Factory converterFactory; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldHandleUnknownConversionType() { + void shouldHandleUnknownConversionType() { // given CommandSender sender = mock(CommandSender.class); @@ -75,7 +72,7 @@ public void shouldHandleUnknownConversionType() { } @Test - public void shouldHandleCommandWithNoArgs() { + void shouldHandleCommandWithNoArgs() { // given CommandSender sender = mock(CommandSender.class); @@ -89,7 +86,7 @@ public void shouldHandleCommandWithNoArgs() { } @Test - public void shouldHaveUniqueClassForEachConverter() { + void shouldHaveUniqueClassForEachConverter() { // given Set> classes = new HashSet<>(); @@ -104,7 +101,7 @@ public void shouldHaveUniqueClassForEachConverter() { } @Test - public void shouldLaunchConverterForAllTypes() { + void shouldLaunchConverterForAllTypes() { // given String converterName = "authplus"; Class converterClass = ConverterCommand.CONVERTERS.get(converterName); @@ -123,7 +120,7 @@ public void shouldLaunchConverterForAllTypes() { } @Test - public void shouldCatchExceptionInConverterAndInformSender() { + void shouldCatchExceptionInConverterAndInformSender() { // given String converterName = "authplus"; Class converterClass = ConverterCommand.CONVERTERS.get(converterName); @@ -150,5 +147,3 @@ private T createMockReturnedByInjector(Class clazz) { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java index d14ec23114..989198bf8d 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java @@ -1,17 +1,15 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -26,8 +24,7 @@ * Test for {@link FirstSpawnCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class FirstSpawnCommandTest { +class FirstSpawnCommandTest { @InjectMocks private FirstSpawnCommand command; @@ -39,7 +36,7 @@ public class FirstSpawnCommandTest { private Messages messages; @Test - public void shouldTeleportToFirstSpawn() { + void shouldTeleportToFirstSpawn() { // given Location firstSpawn = mock(Location.class); given(spawnLoader.getFirstSpawn()).willReturn(firstSpawn); @@ -54,7 +51,7 @@ public void shouldTeleportToFirstSpawn() { } @Test - public void shouldHandleMissingFirstSpawn() { + void shouldHandleMissingFirstSpawn() { // given given(spawnLoader.getFirstSpawn()).willReturn(null); Player player = mock(Player.class); @@ -67,5 +64,3 @@ public void shouldHandleMissingFirstSpawn() { verify(player, never()).teleport(any(Location.class)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java index c839c53a42..66dab60d75 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.PermissionsManager; @@ -13,8 +9,10 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -28,8 +26,7 @@ * Test for {@link ForceLoginCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class ForceLoginCommandTest { +class ForceLoginCommandTest { @InjectMocks private ForceLoginCommand command; @@ -47,7 +44,7 @@ public class ForceLoginCommandTest { private Messages messages; @Test - public void shouldRejectOfflinePlayer() { + void shouldRejectOfflinePlayer() { // given String playerName = "Bobby"; Player player = mockPlayer(false); @@ -64,7 +61,7 @@ public void shouldRejectOfflinePlayer() { } @Test - public void shouldRejectInexistentPlayer() { + void shouldRejectInexistentPlayer() { // given String playerName = "us3rname01"; given(bukkitService.getPlayerExact(playerName)).willReturn(null); @@ -80,7 +77,7 @@ public void shouldRejectInexistentPlayer() { } @Test - public void shouldRejectPlayerWithMissingPermission() { + void shouldRejectPlayerWithMissingPermission() { // given String playerName = "testTest"; Player player = mockPlayer(true); @@ -98,7 +95,7 @@ public void shouldRejectPlayerWithMissingPermission() { } @Test - public void shouldForceLoginPlayer() { + void shouldForceLoginPlayer() { // given String playerName = "tester23"; Player player = mockPlayer(true); @@ -116,7 +113,7 @@ public void shouldForceLoginPlayer() { } @Test - public void shouldForceLoginSenderSelf() { + void shouldForceLoginSenderSelf() { // given String senderName = "tester23"; Player player = mockPlayer(true); @@ -140,5 +137,3 @@ private static Player mockPlayer(boolean isOnline) { return player; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/GetEmailCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/GetEmailCommandTest.java index 07eff3be2b..f1963bf225 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/GetEmailCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/GetEmailCommandTest.java @@ -1,17 +1,15 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.datasourcecolumns.data.DataSourceValueImpl; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.CommonService; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -24,8 +22,7 @@ * Test for {@link GetEmailCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class GetEmailCommandTest { +class GetEmailCommandTest { @InjectMocks private GetEmailCommand command; @@ -37,7 +34,7 @@ public class GetEmailCommandTest { private CommonService service; @Test - public void shouldReportUnknownUser() { + void shouldReportUnknownUser() { // given String user = "myTestUser"; given(dataSource.getEmail(user)).willReturn(DataSourceValueImpl.unknownRow()); @@ -51,7 +48,7 @@ public void shouldReportUnknownUser() { } @Test - public void shouldReturnEmail() { + void shouldReturnEmail() { // given String user = "userToView"; String email = "user.email@example.org"; @@ -65,5 +62,3 @@ public void shouldReturnEmail() { verify(service).send(eq(sender), eq(MessageKey.ADMIN_EMAIL_SHOW), eq(user), eq(email)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/GetIpCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/GetIpCommandTest.java index 03e7fe2317..5822358191 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/GetIpCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/GetIpCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; @@ -11,8 +7,10 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -29,8 +27,7 @@ * Test for {@link GetIpCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class GetIpCommandTest { +class GetIpCommandTest { @InjectMocks private GetIpCommand command; @@ -43,7 +40,7 @@ public class GetIpCommandTest { @Test - public void shouldGetIpOfPlayer() { + void shouldGetIpOfPlayer() { // given given(bukkitService.getPlayerExact(anyString())).willReturn(null); given(dataSource.getAuth(anyString())).willReturn(null); @@ -60,7 +57,7 @@ public void shouldGetIpOfPlayer() { } @Test - public void shouldReturnIpAddressOfPlayer() { + void shouldReturnIpAddressOfPlayer() { // given String playerName = "charlie"; String ip = "123.34.56.88"; @@ -81,7 +78,7 @@ public void shouldReturnIpAddressOfPlayer() { } @Test - public void shouldHandleUnregisteredOnlinePlayer() { + void shouldHandleUnregisteredOnlinePlayer() { // given String playerName = "Test"; String ip = "44.111.22.33"; @@ -107,5 +104,3 @@ private static Player mockPlayer(String name, String ip) { return player; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/LastLoginCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/LastLoginCommandTest.java index 89d2e325ed..9287ab1054 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/LastLoginCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/LastLoginCommandTest.java @@ -1,26 +1,23 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.CommonService; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.Date; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -30,8 +27,7 @@ * Test for {@link LastLoginCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class LastLoginCommandTest { +class LastLoginCommandTest { private static final long HOUR_IN_MSEC = 3600 * 1000; private static final long DAY_IN_MSEC = 24 * HOUR_IN_MSEC; @@ -44,12 +40,10 @@ public class LastLoginCommandTest { @Mock private CommonService service; - @Captor - private ArgumentCaptor captor; @Test - public void shouldRejectNonExistentUser() { + void shouldRejectNonExistentUser() { // given String player = "tester"; given(dataSource.getAuth(player)).willReturn(null); @@ -64,7 +58,7 @@ public void shouldRejectNonExistentUser() { } @Test - public void shouldDisplayLastLoginOfUser() { + void shouldDisplayLastLoginOfUser() { // given String player = "SomePlayer"; long lastLogin = System.currentTimeMillis() - @@ -80,6 +74,7 @@ public void shouldDisplayLastLoginOfUser() { // then verify(dataSource).getAuth(player); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(sender, times(3)).sendMessage(captor.capture()); String lastLoginString = new Date(lastLogin).toString(); assertThat(captor.getAllValues().get(0), @@ -89,7 +84,7 @@ public void shouldDisplayLastLoginOfUser() { } @Test - public void shouldDisplayLastLoginOfCommandSender() { + void shouldDisplayLastLoginOfCommandSender() { // given String name = "CommandSender"; CommandSender sender = mock(CommandSender.class); @@ -107,6 +102,7 @@ public void shouldDisplayLastLoginOfCommandSender() { // then verify(dataSource).getAuth(name); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(sender, times(3)).sendMessage(captor.capture()); String lastLoginString = new Date(lastLogin).toString(); assertThat(captor.getAllValues().get(0), @@ -116,7 +112,7 @@ public void shouldDisplayLastLoginOfCommandSender() { } @Test - public void shouldHandleNullLastLoginDate() { + void shouldHandleNullLastLoginDate() { // given String name = "player"; PlayerAuth auth = PlayerAuth.builder() @@ -131,10 +127,9 @@ public void shouldHandleNullLastLoginDate() { // then verify(dataSource).getAuth(name); + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(sender, times(2)).sendMessage(captor.capture()); assertThat(captor.getAllValues().get(0), allOf(containsString(name), containsString("never"))); assertThat(captor.getAllValues().get(1), containsString("123.45.67.89")); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommandTest.java index 74b79b9248..2f33514dff 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommandTest.java @@ -1,16 +1,14 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.task.purge.PurgeService; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.HashSet; @@ -29,8 +27,7 @@ * Test for {@link PurgeBannedPlayersCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PurgeBannedPlayersCommandTest { +class PurgeBannedPlayersCommandTest { @InjectMocks private PurgeBannedPlayersCommand command; @@ -42,7 +39,7 @@ public class PurgeBannedPlayersCommandTest { private BukkitService bukkitService; @Test - public void shouldForwardRequestToService() { + void shouldForwardRequestToService() { // given String[] names = {"bannedPlayer", "other_banned", "evilplayer", "Someone"}; OfflinePlayer[] players = offlinePlayersWithNames(names); @@ -76,5 +73,3 @@ private static Set asLowerCaseSet(String... items) { return result; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeCommandTest.java index 3cf8f241ca..9af91e7985 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeCommandTest.java @@ -1,24 +1,21 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.task.purge.PurgeService; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Calendar; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -29,19 +26,16 @@ * Test for {@link PurgeCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PurgeCommandTest { +class PurgeCommandTest { @InjectMocks private PurgeCommand command; @Mock private PurgeService purgeService; - @Captor - private ArgumentCaptor captor; @Test - public void shouldHandleInvalidNumber() { + void shouldHandleInvalidNumber() { // given String interval = "invalid"; CommandSender sender = mock(CommandSender.class); @@ -55,7 +49,7 @@ public void shouldHandleInvalidNumber() { } @Test - public void shouldRejectTooSmallInterval() { + void shouldRejectTooSmallInterval() { // given String interval = "29"; CommandSender sender = mock(CommandSender.class); @@ -69,7 +63,7 @@ public void shouldRejectTooSmallInterval() { } @Test - public void shouldForwardToService() { + void shouldForwardToService() { // given String interval = "45"; CommandSender sender = mock(CommandSender.class); @@ -78,6 +72,7 @@ public void shouldForwardToService() { command.executeCommand(sender, Collections.singletonList(interval)); // then + ArgumentCaptor captor = ArgumentCaptor.forClass(Long.class); verify(purgeService).runPurge(eq(sender), captor.capture()); // Check the timestamp with a certain tolerance @@ -92,5 +87,3 @@ private static void assertIsCloseTo(long value1, long value2, long tolerance) { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommandTest.java index cb291b4bac..346f7a05e7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.message.MessageKey; @@ -11,8 +7,10 @@ import fr.xephi.authme.service.bungeecord.BungeeSender; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; @@ -27,8 +25,7 @@ * Test for {@link PurgeLastPositionCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PurgeLastPositionCommandTest { +class PurgeLastPositionCommandTest { @InjectMocks private PurgeLastPositionCommand command; @@ -43,7 +40,7 @@ public class PurgeLastPositionCommandTest { private BungeeSender bungeeSender; @Test - public void shouldPurgeLastPosOfUser() { + void shouldPurgeLastPosOfUser() { // given String player = "_Bobby"; PlayerAuth auth = mock(PlayerAuth.class); @@ -60,7 +57,7 @@ public void shouldPurgeLastPosOfUser() { } @Test - public void shouldPurgePositionOfCommandSender() { + void shouldPurgePositionOfCommandSender() { // given String player = "_Bobby"; CommandSender sender = mock(CommandSender.class); @@ -78,7 +75,7 @@ public void shouldPurgePositionOfCommandSender() { } @Test - public void shouldHandleNonExistentUser() { + void shouldHandleNonExistentUser() { // given String name = "invalidPlayer"; CommandSender sender = mock(CommandSender.class); @@ -92,7 +89,7 @@ public void shouldHandleNonExistentUser() { } @Test - public void shouldResetAllLastPositions() { + void shouldResetAllLastPositions() { // given PlayerAuth auth1 = mock(PlayerAuth.class); PlayerAuth auth2 = mock(PlayerAuth.class); @@ -119,5 +116,3 @@ private static void verifyPositionWasReset(PlayerAuth auth) { verify(auth).setWorld("world"); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgePlayerCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgePlayerCommandTest.java index 5ccdf94d49..283550fa68 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgePlayerCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/PurgePlayerCommandTest.java @@ -1,22 +1,19 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.task.purge.PurgeExecutor; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Locale; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskOptionallyAsync; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.Matchers.containsString; @@ -30,8 +27,7 @@ * Test for {@link PurgePlayerCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PurgePlayerCommandTest { +class PurgePlayerCommandTest { @InjectMocks private PurgePlayerCommand command; @@ -46,7 +42,7 @@ public class PurgePlayerCommandTest { private DataSource dataSource; @Test - public void shouldNotExecutePurgeForRegisteredPlayer() { + void shouldNotExecutePurgeForRegisteredPlayer() { // given String name = "Bobby"; given(dataSource.isAuthAvailable(name)).willReturn(true); @@ -62,7 +58,7 @@ public void shouldNotExecutePurgeForRegisteredPlayer() { } @Test - public void shouldExecutePurge() { + void shouldExecutePurge() { // given String name = "Frank"; given(dataSource.isAuthAvailable(name)).willReturn(false); @@ -80,7 +76,7 @@ public void shouldExecutePurge() { } @Test - public void shouldExecutePurgeOfRegisteredPlayer() { + void shouldExecutePurgeOfRegisteredPlayer() { // given String name = "GhiJKlmn7"; OfflinePlayer player = mock(OfflinePlayer.class); @@ -95,5 +91,3 @@ public void shouldExecutePurgeOfRegisteredPlayer() { verify(purgeExecutor).executePurge(singletonList(player), singletonList(name.toLowerCase(Locale.ROOT))); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RecentPlayersCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RecentPlayersCommandTest.java index a39ae352fe..b2c70322a3 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RecentPlayersCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RecentPlayersCommandTest.java @@ -1,16 +1,14 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; import java.time.ZoneId; import java.util.Arrays; @@ -28,8 +26,7 @@ * Test for {@link RecentPlayersCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class RecentPlayersCommandTest { +class RecentPlayersCommandTest { @InjectMocks @Spy @@ -39,7 +36,7 @@ public class RecentPlayersCommandTest { private DataSource dataSource; @Test - public void shouldShowRecentPlayers() { + void shouldShowRecentPlayers() { // given PlayerAuth auth1 = PlayerAuth.builder() .name("hannah").realName("Hannah").lastIp("11.11.11.11") @@ -64,7 +61,7 @@ public void shouldShowRecentPlayers() { } @Test - public void shouldHandlePlayerWithNullLastLogin() { + void shouldHandlePlayerWithNullLastLogin() { // given PlayerAuth auth1 = PlayerAuth.builder() .name("xephren").realName("Xephren").lastIp("11.11.11.11") @@ -88,5 +85,3 @@ public void shouldHandlePlayerWithNullLastLogin() { verify(sender).sendMessage(argThat(equalToIgnoringCase("- silvah777 (11:15 PM, 09 Nov with IP 22.11.22.33)"))); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java index 8e2281e231..914ebd8d48 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; @@ -18,18 +14,19 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Locale; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskOptionallyAsync; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -40,8 +37,7 @@ * Test for {@link RegisterAdminCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class RegisterAdminCommandTest { +class RegisterAdminCommandTest { @InjectMocks private RegisterAdminCommand command; @@ -60,16 +56,14 @@ public class RegisterAdminCommandTest { @Mock private ValidationService validationService; - @Captor - private ArgumentCaptor captor; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldRejectInvalidPassword() { + void shouldRejectInvalidPassword() { // given String user = "tester"; String password = "myPassword"; @@ -87,7 +81,7 @@ public void shouldRejectInvalidPassword() { } @Test - public void shouldRejectAlreadyRegisteredAccount() { + void shouldRejectAlreadyRegisteredAccount() { // given String user = "my_name55"; String password = "@some-pass@"; @@ -106,7 +100,7 @@ public void shouldRejectAlreadyRegisteredAccount() { } @Test - public void shouldHandleSavingError() { + void shouldHandleSavingError() { // given String user = "test-test"; String password = "afdjhfkt"; @@ -124,12 +118,13 @@ public void shouldHandleSavingError() { // then verify(validationService).validatePassword(password, user); verify(commandService).send(sender, MessageKey.ERROR); + ArgumentCaptor captor = ArgumentCaptor.forClass(PlayerAuth.class); verify(dataSource).saveAuth(captor.capture()); assertAuthHasInfo(captor.getValue(), user, hashedPassword); } @Test - public void shouldRegisterOfflinePlayer() { + void shouldRegisterOfflinePlayer() { // given String user = "someone"; String password = "Al1O3P49S5%"; @@ -148,12 +143,13 @@ public void shouldRegisterOfflinePlayer() { // then verify(validationService).validatePassword(password, user); verify(commandService).send(sender, MessageKey.REGISTER_SUCCESS); + ArgumentCaptor captor = ArgumentCaptor.forClass(PlayerAuth.class); verify(dataSource).saveAuth(captor.capture()); assertAuthHasInfo(captor.getValue(), user, hashedPassword); } @Test - public void shouldRegisterOnlinePlayer() { + void shouldRegisterOnlinePlayer() { // given String user = "someone"; String password = "Al1O3P49S5%"; @@ -176,6 +172,7 @@ public void shouldRegisterOnlinePlayer() { // then verify(validationService).validatePassword(password, user); verify(commandService).send(sender, MessageKey.REGISTER_SUCCESS); + ArgumentCaptor captor = ArgumentCaptor.forClass(PlayerAuth.class); verify(dataSource).saveAuth(captor.capture()); assertAuthHasInfo(captor.getValue(), user, hashedPassword); verify(player).kickPlayer(kickForAdminRegister); @@ -187,5 +184,3 @@ private void assertAuthHasInfo(PlayerAuth auth, String name, HashedPassword hash assertThat(auth.getPassword(), equalTo(hashedPassword)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java index 7261005fb7..6a1de35bcb 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.injector.factory.SingletonStore; import fr.xephi.authme.AuthMe; import fr.xephi.authme.TestHelper; @@ -20,11 +16,13 @@ import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.command.CommandSender; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; @@ -39,8 +37,7 @@ * Test for {@link ReloadCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class ReloadCommandTest { +class ReloadCommandTest { @InjectMocks private ReloadCommand command; @@ -67,19 +64,19 @@ public class ReloadCommandTest { private SingletonStore settingsDependentStore; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } @BeforeEach - public void setDefaultSettings() { + void setDefaultSettings() { // Mock properties retrieved by ConsoleLogger given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); given(settings.getProperty(SecuritySettings.USE_LOGGING)).willReturn(false); } @Test - public void shouldReload() { + void shouldReload() { // given CommandSender sender = mock(CommandSender.class); given(settings.getProperty(DatabaseSettings.BACKEND)).willReturn(DataSourceType.MYSQL); @@ -102,7 +99,7 @@ public void shouldReload() { } @Test - public void shouldHandleReloadError() { + void shouldHandleReloadError() { // given CommandSender sender = mock(CommandSender.class); doThrow(IllegalStateException.class).when(reloadableStore).retrieveAllOfType(); @@ -120,7 +117,7 @@ public void shouldHandleReloadError() { } @Test - public void shouldIssueWarningForChangedDataSourceSetting() { + void shouldIssueWarningForChangedDataSourceSetting() { // given CommandSender sender = mock(CommandSender.class); given(settings.getProperty(DatabaseSettings.BACKEND)).willReturn(DataSourceType.MYSQL); @@ -147,5 +144,3 @@ private void verifyReloadingCalls(List reloadables, List singletonStore; - @Captor - private ArgumentCaptor stringCaptor; @BeforeEach - public void setUpLimboCacheMap() { + void setUpLimboCacheMap() { Map limboMap = new HashMap<>(); limboMap.put("test", mock(LimboPlayer.class)); ReflectionTestUtils.setField(LimboService.class, limboService, "entries", limboMap); } @Test - public void shouldOutputStatistics() { + void shouldOutputStatistics() { // given CommandSender sender = mock(CommandSender.class); given(singletonStore.retrieveAllOfType()).willReturn(mockListOfSize(Object.class, 7)); @@ -89,6 +83,7 @@ public void shouldOutputStatistics() { dataStatistics.execute(sender, Collections.emptyList()); // then + ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); verify(sender, atLeastOnce()).sendMessage(stringCaptor.capture()); assertThat(stringCaptor.getAllValues(), containsInAnyOrder( ChatColor.BLUE + "AuthMe statistics", @@ -101,7 +96,7 @@ public void shouldOutputStatistics() { } @Test - public void shouldOutputCachedDataSourceStatistics() { + void shouldOutputCachedDataSourceStatistics() { // given CacheDataSource cacheDataSource = mock(CacheDataSource.class); LoadingCache> cache = mock(LoadingCache.class); @@ -114,6 +109,7 @@ public void shouldOutputCachedDataSourceStatistics() { dataStatistics.execute(sender, Collections.emptyList()); // then + ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); verify(sender, atLeastOnce()).sendMessage(stringCaptor.capture()); assertThat(stringCaptor.getAllValues(), hasItem("Cached PlayerAuth objects: 11")); } @@ -123,5 +119,3 @@ private static List mockListOfSize(Class mockClass, int size) { return Collections.nCopies(size, mock); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugCommandTest.java index 67b6daa36b..d6b8aacf13 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugCommandTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme.debug; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.injector.factory.Factory; import fr.xephi.authme.permission.DebugSectionPermissions; import fr.xephi.authme.permission.PermissionNode; @@ -12,10 +8,11 @@ import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.List; @@ -23,10 +20,10 @@ import static com.google.common.base.Preconditions.checkArgument; import static java.util.Collections.emptyList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.eq; @@ -45,8 +42,7 @@ * Test for {@link DebugCommand}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class DebugCommandTest { +class DebugCommandTest { /** * Number we test against if we expect an action to have been performed for each debug section. @@ -63,12 +59,10 @@ public class DebugCommandTest { @Mock private PermissionsManager permissionsManager; - @Captor - private ArgumentCaptor strCaptor; @BeforeEach @SuppressWarnings("unchecked") - public void initFactory() { + void initFactory() { given(debugSectionFactory.newInstance(any(Class.class))).willAnswer( invocation -> { Class classArgument = invocation.getArgument(0); @@ -78,7 +72,7 @@ public void initFactory() { } @Test - public void shouldListAllAvailableDebugSections() { + void shouldListAllAvailableDebugSections() { // given CommandSender sender = mock(CommandSender.class); given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(false); @@ -92,6 +86,7 @@ public void shouldListAllAvailableDebugSections() { verify(debugSectionFactory, atLeast(MIN_DEBUG_SECTIONS)).newInstance(any(Class.class)); verify(permissionsManager, atLeast(MIN_DEBUG_SECTIONS)).hasPermission(eq(sender), any(DebugSectionPermissions.class)); + ArgumentCaptor strCaptor = ArgumentCaptor.forClass(String.class); verify(sender, times(4)).sendMessage(strCaptor.capture()); assertThat(strCaptor.getAllValues(), contains( equalTo(ChatColor.BLUE + "AuthMe debug utils"), @@ -101,7 +96,7 @@ public void shouldListAllAvailableDebugSections() { } @Test - public void shouldNotListAnyDebugSection() { + void shouldNotListAnyDebugSection() { // given CommandSender sender = mock(CommandSender.class); given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(false); @@ -113,6 +108,7 @@ public void shouldNotListAnyDebugSection() { verify(debugSectionFactory, atLeast(MIN_DEBUG_SECTIONS)).newInstance(any(Class.class)); verify(permissionsManager, atLeast(MIN_DEBUG_SECTIONS)).hasPermission(eq(sender), any(DebugSectionPermissions.class)); + ArgumentCaptor strCaptor = ArgumentCaptor.forClass(String.class); verify(sender, times(3)).sendMessage(strCaptor.capture()); assertThat(strCaptor.getAllValues(), contains( equalTo(ChatColor.BLUE + "AuthMe debug utils"), @@ -121,7 +117,7 @@ public void shouldNotListAnyDebugSection() { } @Test - public void shouldRunSection() { + void shouldRunSection() { // given DebugSection section = spy(InputValidator.class); doNothing().when(section).execute(any(CommandSender.class), anyList()); @@ -141,7 +137,7 @@ public void shouldRunSection() { } @Test - public void shouldNotRunSectionForMissingPermission() { + void shouldNotRunSectionForMissingPermission() { // given DebugSection section = spy(InputValidator.class); // Mockito throws a runtime error if below we use the usual "given(factory.newInstance(...)).willReturn(...)" @@ -160,5 +156,3 @@ public void shouldNotRunSectionForMissingPermission() { verify(sender).sendMessage(argThat(containsString("You don't have permission"))); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java index 511f0f6143..f5be549df7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java @@ -10,22 +10,22 @@ import java.util.List; import java.util.Set; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; /** * Consistency tests for {@link DebugSection} implementors. */ -public class DebugSectionConsistencyTest { +class DebugSectionConsistencyTest { private static List> debugClasses; private static List debugSections; @BeforeAll - public static void collectClasses() { + static void collectClasses() { // TODO ljacqu 20171021: Improve ClassCollector (pass pkg by class, improve #getInstancesOfType's instantiation) ClassCollector classCollector = new ClassCollector( TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT + "command/executable/authme/debug"); @@ -35,7 +35,7 @@ public static void collectClasses() { } @Test - public void shouldAllBePackagePrivate() { + void shouldAllBePackagePrivate() { for (Class clazz : debugClasses) { if (clazz != DebugCommand.class) { assertThat(clazz + " should be package-private", @@ -45,7 +45,7 @@ public void shouldAllBePackagePrivate() { } @Test - public void shouldHaveDifferentSubcommandName() throws IllegalAccessException, InstantiationException { + void shouldHaveDifferentSubcommandName() { Set names = new HashSet<>(); for (DebugSection debugSection : debugSections) { if (!names.add(debugSection.getName())) { @@ -55,7 +55,7 @@ public void shouldHaveDifferentSubcommandName() throws IllegalAccessException, I } @Test - public void shouldAllHaveDescription() { + void shouldAllHaveDescription() { for (DebugSection debugSection : debugSections) { assertThat("Description of '" + debugSection.getClass() + "' may not be null", debugSection.getDescription(), not(nullValue())); @@ -70,4 +70,3 @@ private static DebugSection instantiate(Class clazz) { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java index 638b943b19..293ea4efd3 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java @@ -15,24 +15,24 @@ import java.util.Map; import java.util.function.Function; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; /** * Test for {@link DebugSectionUtils}. */ -public class DebugSectionUtilsTest { +class DebugSectionUtilsTest { @BeforeEach - public void initMockLogger() { + void initMockLogger() { TestHelper.setupLogger(); } @Test - public void shouldFormatLocation() { + void shouldFormatLocation() { // given / when String result = DebugSectionUtils.formatLocation(0.0, 10.248592, -18934.2349023, "Main"); @@ -41,7 +41,7 @@ public void shouldFormatLocation() { } @Test - public void shouldHandleNullWorld() { + void shouldHandleNullWorld() { // given Location location = new Location(null, 3.7777, 2.14156, 1); @@ -53,13 +53,13 @@ public void shouldHandleNullWorld() { } @Test - public void shouldHandleNullLocation() { + void shouldHandleNullLocation() { // given / when / then assertThat(DebugSectionUtils.formatLocation(null), equalTo("null")); } @Test - public void shouldFetchMapInLimboService() { + void shouldFetchMapInLimboService() { // given LimboService limboService = mock(LimboService.class); Map limboMap = new HashMap<>(); @@ -73,7 +73,7 @@ public void shouldFetchMapInLimboService() { } @Test - public void shouldHandleErrorGracefully() { + void shouldHandleErrorGracefully() { // given LimboService limboService = mock(LimboService.class); Map limboMap = new HashMap<>(); @@ -81,7 +81,7 @@ public void shouldHandleErrorGracefully() { // when Object result = DebugSectionUtils.applyToLimboPlayersMap(limboService, map -> { - throw new IllegalStateException(); + throw new IllegalStateException(); }); // then @@ -89,7 +89,7 @@ public void shouldHandleErrorGracefully() { } @Test - public void shouldReturnSameDataSourceInstance() { + void shouldReturnSameDataSourceInstance() { // given DataSource dataSource = mock(DataSource.class); @@ -101,7 +101,7 @@ public void shouldReturnSameDataSourceInstance() { } @Test - public void shouldUnwrapCacheDataSource() { + void shouldUnwrapCacheDataSource() { // given DataSource source = mock(DataSource.class); PlayerCache playerCache = mock(PlayerCache.class); @@ -115,7 +115,7 @@ public void shouldUnwrapCacheDataSource() { } @Test - public void shouldCastOrReturnNull() { + void shouldCastOrReturnNull() { // given / when / then assertThat(DebugSectionUtils.castToTypeOrNull("test", String.class), equalTo("test")); assertThat(DebugSectionUtils.castToTypeOrNull("test", Integer.class), nullValue()); @@ -123,4 +123,3 @@ public void shouldCastOrReturnNull() { assertThat(DebugSectionUtils.castToTypeOrNull(5, Integer.class), equalTo(5)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/HasPermissionCheckerTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/HasPermissionCheckerTest.java index 52c73b0b37..8e307a8958 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/HasPermissionCheckerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/HasPermissionCheckerTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme.debug; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.ClassCollector; import fr.xephi.authme.TestHelper; import fr.xephi.authme.permission.AdminPermission; @@ -13,20 +9,21 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; @@ -37,8 +34,7 @@ * Test for {@link HasPermissionChecker}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class HasPermissionCheckerTest { +class HasPermissionCheckerTest { @InjectMocks private HasPermissionChecker hasPermissionChecker; @@ -48,11 +44,9 @@ public class HasPermissionCheckerTest { @Mock private BukkitService bukkitService; - @Captor - private ArgumentCaptor msgCaptor; @Test - public void shouldListAllPermissionNodeClasses() { + void shouldListAllPermissionNodeClasses() { // given List> permissionClasses = new ClassCollector(TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT) @@ -65,7 +59,7 @@ public void shouldListAllPermissionNodeClasses() { } @Test - public void shouldShowUsageInfo() { + void shouldShowUsageInfo() { // given CommandSender sender = mock(CommandSender.class); @@ -73,6 +67,7 @@ public void shouldShowUsageInfo() { hasPermissionChecker.execute(sender, emptyList()); // then + ArgumentCaptor msgCaptor = ArgumentCaptor.forClass(String.class); verify(sender, atLeast(2)).sendMessage(msgCaptor.capture()); assertThat( msgCaptor.getAllValues().stream().anyMatch(msg -> msg.contains("/authme debug perm bobby my.perm.node")), @@ -80,7 +75,7 @@ public void shouldShowUsageInfo() { } @Test - public void shouldShowSuccessfulTestWithRegularPlayer() { + void shouldShowSuccessfulTestWithRegularPlayer() { // given String name = "Chuck"; Player player = mock(Player.class); @@ -99,5 +94,3 @@ public void shouldShowSuccessfulTestWithRegularPlayer() { + "' has permission '" + permission.getNode() + "'"))); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerColumnsTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerColumnsTest.java index 798df206c7..46649651f2 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerColumnsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerColumnsTest.java @@ -5,17 +5,17 @@ import java.util.HashSet; import java.util.Set; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.fail; /** * Consistency test for {@link MySqlDefaultChanger.Columns} enum. */ -public class MySqlDefaultChangerColumnsTest { +class MySqlDefaultChangerColumnsTest { @Test - public void shouldAllHaveDifferentNameProperty() { + void shouldAllHaveDifferentNameProperty() { // given Set properties = new HashSet<>(); @@ -29,14 +29,14 @@ public void shouldAllHaveDifferentNameProperty() { } @Test - public void shouldHaveMatchingNullableAndNotNullDefinition() { + void shouldHaveMatchingNullableAndNotNullDefinition() { for (MySqlDefaultChanger.Columns col : MySqlDefaultChanger.Columns.values()) { verifyHasCorrespondingColumnDefinitions(col); } } @Test - public void shouldHaveMatchingDefaultValueInNotNullDefinition() { + void shouldHaveMatchingDefaultValueInNotNullDefinition() { for (MySqlDefaultChanger.Columns col : MySqlDefaultChanger.Columns.values()) { verifyHasSameDefaultValueInNotNullDefinition(col); } @@ -67,4 +67,3 @@ private void verifyHasSameDefaultValueInNotNullDefinition(MySqlDefaultChanger.Co } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerTest.java index f8d814b760..882402f498 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.executable.authme.debug; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import com.zaxxer.hikari.HikariDataSource; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; @@ -15,15 +11,17 @@ import fr.xephi.authme.settings.Settings; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.sql.Connection; import java.sql.SQLException; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -32,19 +30,18 @@ * Test for {@link MySqlDefaultChanger}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class MySqlDefaultChangerTest { +class MySqlDefaultChangerTest { @Mock private Settings settings; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldReturnMySqlConnection() throws SQLException { + void shouldReturnMySqlConnection() throws SQLException { // given Settings settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); @@ -63,7 +60,7 @@ public void shouldReturnMySqlConnection() throws SQLException { } @Test - public void shouldSetMySqlFieldOnInitialization() { + void shouldSetMySqlFieldOnInitialization() { // given MySQL mySql = mock(MySQL.class); MySqlDefaultChanger defaultChanger = createDefaultChanger(mySql); @@ -77,7 +74,7 @@ public void shouldSetMySqlFieldOnInitialization() { } @Test - public void shouldLeaveMySqlFieldToNullOnInitialization() { + void shouldLeaveMySqlFieldToNullOnInitialization() { // given DataSource dataSource = mock(DataSource.class); PlayerCache playerCache = mock(PlayerCache.class); @@ -99,5 +96,3 @@ private MySqlDefaultChanger createDefaultChanger(DataSource dataSource) { return defaultChanger; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/PlayerAuthViewerTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/PlayerAuthViewerTest.java index 3372116df8..6e8d6dde39 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/PlayerAuthViewerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/debug/PlayerAuthViewerTest.java @@ -1,23 +1,20 @@ package fr.xephi.authme.command.executable.authme.debug; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -28,19 +25,16 @@ * Test for {@link PlayerAuthViewer}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PlayerAuthViewerTest { +class PlayerAuthViewerTest { @InjectMocks private PlayerAuthViewer authViewer; @Mock private DataSource dataSource; - @Captor - private ArgumentCaptor textCaptor; @Test - public void shouldMakeExample() { + void shouldMakeExample() { // given CommandSender sender = mock(CommandSender.class); @@ -52,7 +46,7 @@ public void shouldMakeExample() { } @Test - public void shouldHandleMissingPlayer() { + void shouldHandleMissingPlayer() { // given CommandSender sender = mock(CommandSender.class); @@ -65,7 +59,7 @@ public void shouldHandleMissingPlayer() { } @Test - public void shouldDisplayAuthInfo() { + void shouldDisplayAuthInfo() { // given CommandSender sender = mock(CommandSender.class); PlayerAuth auth = PlayerAuth.builder().name("george").realName("George") @@ -79,6 +73,7 @@ public void shouldDisplayAuthInfo() { authViewer.execute(sender, Collections.singletonList("George")); // then + ArgumentCaptor textCaptor = ArgumentCaptor.forClass(String.class); verify(sender, atLeastOnce()).sendMessage(textCaptor.capture()); assertThat(textCaptor.getAllValues(), hasItem(containsString("Player george / George"))); assertThat(textCaptor.getAllValues(), hasItem(containsString("Registration: 2005-03-18T"))); @@ -87,7 +82,7 @@ public void shouldDisplayAuthInfo() { } @Test - public void shouldHandleCornerCases() { + void shouldHandleCornerCases() { // given CommandSender sender = mock(CommandSender.class); PlayerAuth auth = PlayerAuth.builder().name("tar") @@ -100,6 +95,7 @@ public void shouldHandleCornerCases() { authViewer.execute(sender, Collections.singletonList("Tar")); // then + ArgumentCaptor textCaptor = ArgumentCaptor.forClass(String.class); verify(sender, atLeastOnce()).sendMessage(textCaptor.capture()); assertThat(textCaptor.getAllValues(), hasItem(containsString("Player tar / Player"))); assertThat(textCaptor.getAllValues(), hasItem(containsString("Registration: Not available (0)"))); @@ -108,5 +104,3 @@ public void shouldHandleCornerCases() { assertThat(textCaptor.getAllValues(), hasItem(containsString("TOTP code (partial): ''"))); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessageAndHelpSectionConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessageAndHelpSectionConsistencyTest.java index 1dd2b8df2d..6920633427 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessageAndHelpSectionConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessageAndHelpSectionConsistencyTest.java @@ -6,17 +6,17 @@ import java.util.HashSet; import java.util.Set; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.fail; /** * Test for enums {@link HelpMessage} and {@link HelpSection}. */ -public class HelpMessageAndHelpSectionConsistencyTest { +class HelpMessageAndHelpSectionConsistencyTest { @Test - public void shouldHaveUniqueNonEmptyKeys() { + void shouldHaveUniqueNonEmptyKeys() { // given Set keys = new HashSet<>(); @@ -37,4 +37,3 @@ public void shouldHaveUniqueNonEmptyKeys() { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java index 0e9cfb3982..c508603ba2 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java @@ -15,22 +15,22 @@ import java.util.Collection; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; /** * Tests that /messages/help_en.yml contains texts that correspond * to the texts provided in the CommandDescription. */ -public class HelpMessagesConsistencyTest { +class HelpMessagesConsistencyTest { private static final File DEFAULT_MESSAGES_FILE = TestHelper.getJarFile("/" + MessagePathHelper.createHelpMessageFilePath(MessagePathHelper.DEFAULT_LANGUAGE)); @Test - public void shouldHaveIdenticalTexts() { + void shouldHaveIdenticalTexts() { // given CommandDescription description = getAuthMeRegisterDescription(); FileConfiguration configuration = YamlConfiguration.loadConfiguration(DEFAULT_MESSAGES_FILE); @@ -50,7 +50,7 @@ public void shouldHaveIdenticalTexts() { * only contains an entry for one command as to provide an example. */ @Test - public void shouldOnlyHaveDescriptionForOneCommand() { + void shouldOnlyHaveDescriptionForOneCommand() { // given FileConfiguration configuration = YamlConfiguration.loadConfiguration(DEFAULT_MESSAGES_FILE); @@ -63,7 +63,7 @@ public void shouldOnlyHaveDescriptionForOneCommand() { } @Test - public void shouldHaveEntryForEachHelpMessageKey() { + void shouldHaveEntryForEachHelpMessageKey() { // given PropertyReader reader = new YamlFileReader(DEFAULT_MESSAGES_FILE); @@ -95,4 +95,3 @@ private static CommandDescription getAuthMeRegisterDescription() { .findFirst().get(); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java index 62b5fe9fdb..b2d970e8c8 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java @@ -13,35 +13,35 @@ import fr.xephi.authme.settings.properties.PluginSettings; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.util.Collection; import static fr.xephi.authme.command.TestCommandsUtil.getCommandWithLabel; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link HelpMessagesService}. */ -public class HelpMessagesServiceTest { +class HelpMessagesServiceTest { private static final String TEST_FILE = TestHelper.PROJECT_ROOT + "command/help/help_test.yml"; private static final Collection COMMANDS = TestCommandsUtil.generateCommands(); private HelpMessagesService helpMessagesService; - public TempFolder temporaryFolder = new TempFolder(); - private File dataFolder; + + @TempDir + File dataFolder; @BeforeEach - public void initializeHandler() throws IOException { - dataFolder = temporaryFolder.newFolder(); + void initializeHandler() throws IOException { new File(dataFolder, "messages").mkdirs(); File messagesFile = new File(dataFolder, MessagePathHelper.createHelpMessageFilePath("test")); Files.copy(TestHelper.getJarFile(TEST_FILE), messagesFile); @@ -51,7 +51,7 @@ public void initializeHandler() throws IOException { } @Test - public void shouldReturnLocalizedCommand() { + void shouldReturnLocalizedCommand() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "authme", "register"); @@ -71,7 +71,7 @@ public void shouldReturnLocalizedCommand() { } @Test - public void shouldReturnLocalizedCommandWithDefaults() { + void shouldReturnLocalizedCommandWithDefaults() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "authme", "login"); @@ -87,7 +87,7 @@ public void shouldReturnLocalizedCommandWithDefaults() { } @Test - public void shouldReturnSameCommandForNoLocalization() { + void shouldReturnSameCommandForNoLocalization() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "email"); @@ -99,7 +99,7 @@ public void shouldReturnSameCommandForNoLocalization() { } @Test - public void shouldKeepChildrenInLocalCommand() { + void shouldKeepChildrenInLocalCommand() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "authme"); @@ -113,7 +113,7 @@ public void shouldKeepChildrenInLocalCommand() { } @Test - public void shouldGetTranslationsForSectionAndMessage() { + void shouldGetTranslationsForSectionAndMessage() { // given / when / then assertThat(helpMessagesService.getMessage(DefaultPermission.OP_ONLY), equalTo("only op")); assertThat(helpMessagesService.getMessage(HelpMessage.RESULT), equalTo("res.")); @@ -121,7 +121,7 @@ public void shouldGetTranslationsForSectionAndMessage() { } @Test - public void shouldGetLocalCommandDescription() { + void shouldGetLocalCommandDescription() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "authme", "register"); @@ -133,7 +133,7 @@ public void shouldGetLocalCommandDescription() { } @Test - public void shouldFallbackToDescriptionOnCommandObject() { + void shouldFallbackToDescriptionOnCommandObject() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "unregister"); @@ -155,5 +155,3 @@ private HelpMessagesFileHandler createMessagesFileHandler() { return messagesFileHandler; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java index c42aecec47..e9ad673f22 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.command.help; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.FoundCommandResult; import fr.xephi.authme.command.FoundResultStatus; @@ -14,11 +10,13 @@ import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.Mock; -import static org.mockito.AdditionalAnswers.returnsFirstArg; +import org.mockito.internal.stubbing.answers.ReturnsArgumentAt; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collection; @@ -36,15 +34,16 @@ import static fr.xephi.authme.command.help.HelpProvider.SHOW_DESCRIPTION; import static fr.xephi.authme.command.help.HelpProvider.SHOW_LONG_DESCRIPTION; import static fr.xephi.authme.command.help.HelpProvider.SHOW_PERMISSIONS; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -52,12 +51,11 @@ /** * Test for {@link HelpProvider}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class HelpProviderTest { +@ExtendWith(MockitoExtension.class) +class HelpProviderTest { private static Collection commands; - @InjectDelayed private HelpProvider helpProvider; @Mock private PermissionsManager permissionsManager; @@ -65,21 +63,20 @@ public class HelpProviderTest { private HelpMessagesService helpMessagesService; @Mock private CommandSender sender; - @Captor - private ArgumentCaptor captor; @BeforeAll - public static void setUpCommands() { + static void setUpCommands() { commands = TestCommandsUtil.generateCommands(); } - @BeforeInjecting - public void setInitialSettings() { + @BeforeEach + void initializeHelpProvider() { setDefaultHelpMessages(helpMessagesService); + helpProvider = new HelpProvider(permissionsManager, helpMessagesService); } @Test - public void shouldShowLongDescription() { + void shouldShowLongDescription() { // given CommandDescription command = getCommandWithLabel(commands, "authme", "login"); FoundCommandResult result = newFoundResult(command, Arrays.asList("authme", "login")); @@ -98,7 +95,7 @@ public void shouldShowLongDescription() { } @Test - public void shouldShowArguments() { + void shouldShowArguments() { // given CommandDescription command = getCommandWithLabel(commands, "authme", "register"); FoundCommandResult result = newFoundResult(command, Arrays.asList("authme", "reg")); @@ -116,7 +113,7 @@ public void shouldShowArguments() { } @Test - public void shouldShowSpecifyIfArgumentIsOptional() { + void shouldShowSpecifyIfArgumentIsOptional() { // given CommandDescription command = getCommandWithLabel(commands, "email"); FoundCommandResult result = newFoundResult(command, Collections.singletonList("email")); @@ -132,7 +129,7 @@ public void shouldShowSpecifyIfArgumentIsOptional() { /** Verifies that the "Arguments:" line is not shown if the command has no arguments. */ @Test - public void shouldNotShowAnythingIfCommandHasNoArguments() { + void shouldNotShowAnythingIfCommandHasNoArguments() { // given CommandDescription command = getCommandWithLabel(commands, "authme"); FoundCommandResult result = newFoundResult(command, Collections.singletonList("authme")); @@ -146,7 +143,7 @@ public void shouldNotShowAnythingIfCommandHasNoArguments() { } @Test - public void shouldShowAndEvaluatePermissions() { + void shouldShowAndEvaluatePermissions() { // given CommandDescription command = getCommandWithLabel(commands, "unregister"); FoundCommandResult result = newFoundResult(command, Collections.singletonList("unreg")); @@ -168,7 +165,7 @@ public void shouldShowAndEvaluatePermissions() { } @Test - public void shouldShowAndEvaluateForbiddenPermissions() { + void shouldShowAndEvaluateForbiddenPermissions() { // given CommandDescription command = getCommandWithLabel(commands, "unregister"); FoundCommandResult result = newFoundResult(command, Collections.singletonList("unregister")); @@ -190,7 +187,7 @@ public void shouldShowAndEvaluateForbiddenPermissions() { } @Test - public void shouldNotShowAnythingForEmptyPermissions() { + void shouldNotShowAnythingForEmptyPermissions() { // given CommandDescription command = getCommandWithLabel(commands, "authme"); FoundCommandResult result = newFoundResult(command, Collections.singletonList("authme")); @@ -204,7 +201,7 @@ public void shouldNotShowAnythingForEmptyPermissions() { } @Test - public void shouldNotShowAnythingForNullPermissionsOnCommand() { + void shouldNotShowAnythingForNullPermissionsOnCommand() { // given CommandDescription command = mock(CommandDescription.class); given(command.getPermission()).willReturn(null); @@ -220,7 +217,7 @@ public void shouldNotShowAnythingForNullPermissionsOnCommand() { } @Test - public void shouldShowAlternatives() { + void shouldShowAlternatives() { // given CommandDescription command = getCommandWithLabel(commands, "authme", "register"); FoundCommandResult result = newFoundResult(command, Arrays.asList("authme", "reg")); @@ -237,7 +234,7 @@ public void shouldShowAlternatives() { } @Test - public void shouldNotShowAnythingIfHasNoAlternatives() { + void shouldNotShowAnythingIfHasNoAlternatives() { // given CommandDescription command = getCommandWithLabel(commands, "authme", "login"); FoundCommandResult result = newFoundResult(command, Arrays.asList("authme", "login")); @@ -251,7 +248,7 @@ public void shouldNotShowAnythingIfHasNoAlternatives() { } @Test - public void shouldShowChildren() { + void shouldShowChildren() { // given CommandDescription command = getCommandWithLabel(commands, "authme"); FoundCommandResult result = newFoundResult(command, Collections.singletonList("authme")); @@ -272,7 +269,7 @@ public void shouldShowChildren() { } @Test - public void shouldNotShowCommandsTitleForCommandWithNoChildren() { + void shouldNotShowCommandsTitleForCommandWithNoChildren() { // given CommandDescription command = getCommandWithLabel(commands, "authme", "register"); FoundCommandResult result = newFoundResult(command, Collections.singletonList("authme")); @@ -286,7 +283,7 @@ public void shouldNotShowCommandsTitleForCommandWithNoChildren() { } @Test - public void shouldHandleUnboundFoundCommandResult() { + void shouldHandleUnboundFoundCommandResult() { // given FoundCommandResult result = new FoundCommandResult(null, Arrays.asList("authme", "test"), Collections.emptyList(), 0.0, FoundResultStatus.UNKNOWN_LABEL); @@ -305,7 +302,7 @@ public void shouldHandleUnboundFoundCommandResult() { * (e.g. suggest "register command" for /authme ragister), we need to check the labels and construct a correct list */ @Test - public void shouldShowCommandSyntaxWithCorrectLabels() { + void shouldShowCommandSyntaxWithCorrectLabels() { // given CommandDescription command = getCommandWithLabel(commands, "authme", "register"); FoundCommandResult result = newFoundResult(command, Arrays.asList("authme", "ragister")); @@ -321,7 +318,7 @@ public void shouldShowCommandSyntaxWithCorrectLabels() { } @Test - public void shouldRetainCorrectLabels() { + void shouldRetainCorrectLabels() { // given List labels = Arrays.asList("authme", "reg"); CommandDescription command = getCommandWithLabel(commands, "authme", "register"); @@ -334,7 +331,7 @@ public void shouldRetainCorrectLabels() { } @Test - public void shouldReplaceIncorrectLabels() { + void shouldReplaceIncorrectLabels() { // given List labels = Arrays.asList("authme", "wrong"); CommandDescription command = getCommandWithLabel(commands, "authme", "register"); @@ -347,7 +344,7 @@ public void shouldReplaceIncorrectLabels() { } @Test - public void shouldDisableSectionsWithEmptyTranslations() { + void shouldDisableSectionsWithEmptyTranslations() { // given given(helpMessagesService.getMessage(HelpSection.DETAILED_DESCRIPTION)).willReturn(""); given(helpMessagesService.getMessage(HelpSection.ALTERNATIVES)).willReturn(""); @@ -371,7 +368,7 @@ public void shouldDisableSectionsWithEmptyTranslations() { } @Test - public void shouldNotReturnAnythingForAllDisabledSections() { + void shouldNotReturnAnythingForAllDisabledSections() { // given given(helpMessagesService.getMessage(HelpSection.COMMAND)).willReturn(""); given(helpMessagesService.getMessage(HelpSection.ALTERNATIVES)).willReturn(""); @@ -388,7 +385,7 @@ public void shouldNotReturnAnythingForAllDisabledSections() { } @Test - public void shouldSkipEmptyHeader() { + void shouldSkipEmptyHeader() { // given given(helpMessagesService.getMessage(HelpMessage.HEADER)).willReturn(""); CommandDescription command = getCommandWithLabel(commands, "authme", "register"); @@ -404,7 +401,7 @@ public void shouldSkipEmptyHeader() { } @Test - public void shouldShowAlternativesForRootCommand() { + void shouldShowAlternativesForRootCommand() { // given CommandDescription command = getCommandWithLabel(commands, "unregister"); FoundCommandResult result = newFoundResult(command, Collections.singletonList("unreg")); @@ -439,32 +436,31 @@ private static String removeColors(String str) { } return str; } - - private List getLines(CommandSender sender) { + + private static List getLines(CommandSender sender) { + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(sender, atLeastOnce()).sendMessage(captor.capture()); return captor.getAllValues().stream().map(s -> removeColors(s)).collect(Collectors.toList()); } private static void setDefaultHelpMessages(HelpMessagesService helpMessagesService) { - given(helpMessagesService.buildLocalizedDescription(any(CommandDescription.class))) - .willAnswer(returnsFirstArg()); + lenient().when(helpMessagesService.buildLocalizedDescription(any(CommandDescription.class))) + .thenAnswer(new ReturnsArgumentAt(0)); for (HelpMessage key : HelpMessage.values()) { String text = key.name().replace("_", " ").toLowerCase(Locale.ROOT); - given(helpMessagesService.getMessage(key)) - .willReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); + lenient().when(helpMessagesService.getMessage(key)) + .thenReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); } for (DefaultPermission permission : DefaultPermission.values()) { String text = permission.name().replace("_", " ").toLowerCase(Locale.ROOT); - given(helpMessagesService.getMessage(permission)) - .willReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); + lenient().when(helpMessagesService.getMessage(permission)) + .thenReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); } for (HelpSection section : HelpSection.values()) { String text = section.name().replace("_", " ").toLowerCase(Locale.ROOT); - given(helpMessagesService.getMessage(section)) - .willReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); + lenient().when(helpMessagesService.getMessage(section)) + .thenReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); } } } - - From 7c7c5078771e590ea9fee4c3fb17181193e30ae7 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Thu, 23 Apr 2026 09:59:28 +0200 Subject: [PATCH 2/5] JUnit 5 cleanup for package data and datasource --- .../QuickCommandsProtectionManagerTest.java | 17 ++--- .../xephi/authme/data/TempbanManagerTest.java | 36 ++++----- .../data/VerificationCodeManagerTest.java | 35 ++++----- .../authme/data/auth/PlayerAuthTest.java | 9 +-- .../data/captcha/LoginCaptchaManagerTest.java | 19 +++-- .../RegistrationCaptchaManagerTest.java | 11 ++- .../limbo/AllowFlightRestoreTypeTest.java | 13 ++-- .../limbo/LimboPlayerTaskManagerTest.java | 33 ++++----- .../data/limbo/LimboServiceHelperTest.java | 23 +++--- .../authme/data/limbo/LimboServiceTest.java | 73 ++++++++++--------- .../limbo/WalkFlySpeedRestoreTypeTest.java | 16 ++-- ...istributedFilesPersistenceHandlerTest.java | 42 +++++------ ...IndividualFilesPersistenceHandlerTest.java | 39 +++++----- .../persistence/LimboPersistenceTest.java | 34 ++++----- .../persistence/LimboPersistenceTypeTest.java | 9 +-- .../persistence/SegmentNameBuilderTest.java | 21 +++--- .../limbo/persistence/SegmentSizeTest.java | 7 +- .../AbstractDataSourceIntegrationTest.java | 62 ++++++++-------- .../AbstractResourceClosingTest.java | 70 ++++++++---------- ...tractSqlDataSourceResourceClosingTest.java | 18 +++-- .../datasource/MySqlIntegrationTest.java | 11 ++- .../datasource/MySqlResourceClosingTest.java | 2 +- .../datasource/PostgreSqlIntegrationTest.java | 11 ++- .../PostgreSqlResourceClosingTest.java | 3 +- .../datasource/SQLiteIntegrationTest.java | 17 ++--- .../datasource/SQLiteResourceClosingTest.java | 5 +- .../SqLiteMigraterIntegrationTest.java | 22 +++--- .../datasource/SqlDataSourceUtilsTest.java | 25 +++---- .../AbstractDataSourceConverterTest.java | 10 +-- ...ractMySqlExtensionResourceClosingTest.java | 12 +-- .../Ipb4ExtensionResourceClosingTest.java | 2 +- .../mysqlextensions/NoOpExtensionTest.java | 15 ++-- .../PhpBbExtensionResourceClosingTest.java | 2 +- ...WordpressExtensionResourceClosingTest.java | 2 +- .../XfBcryptExtensionResourceClosingTest.java | 2 +- 35 files changed, 330 insertions(+), 398 deletions(-) diff --git a/authme-core/src/test/java/fr/xephi/authme/data/QuickCommandsProtectionManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/QuickCommandsProtectionManagerTest.java index 9352d060f9..bb912aa308 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/QuickCommandsProtectionManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/QuickCommandsProtectionManagerTest.java @@ -1,19 +1,17 @@ package fr.xephi.authme.data; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ProtectionSettings; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -21,8 +19,7 @@ * Test for {@link QuickCommandsProtectionManager}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class QuickCommandsProtectionManagerTest { +class QuickCommandsProtectionManagerTest { @Mock private Settings settings; @@ -31,7 +28,7 @@ public class QuickCommandsProtectionManagerTest { private PermissionsManager permissionsManager; @Test - public void shouldAllowCommand() { + void shouldAllowCommand() { // given String playername = "PlayerName"; Player player = mockPlayerWithName(playername); @@ -53,7 +50,7 @@ public void shouldAllowCommand() { } @Test - public void shouldDenyCommand() { + void shouldDenyCommand() { // given String name = "TestName1"; Player player = mockPlayerWithName(name); @@ -81,5 +78,3 @@ private static Player mockPlayerWithName(String name) { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java index 652f04664e..d0091b4049 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.data; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.message.MessageKey; @@ -14,9 +10,10 @@ import fr.xephi.authme.util.expiring.TimedCounter; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Calendar; import java.util.Date; @@ -25,11 +22,10 @@ import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunOnGlobalRegion; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTask; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -40,8 +36,7 @@ * Test for {@link TempbanManager}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class TempbanManagerTest { +class TempbanManagerTest { private static final long DATE_TOLERANCE_MILLISECONDS = 200L; private static final long TEST_EXPIRATION_THRESHOLD = 120_000L; @@ -51,11 +46,9 @@ public class TempbanManagerTest { @Mock private Messages messages; - @Captor - private ArgumentCaptor captor; @Test - public void shouldAddCounts() { + void shouldAddCounts() { // given Settings settings = mockSettings(3, 60, ""); TempbanManager manager = new TempbanManager(bukkitService, messages, settings); @@ -75,7 +68,7 @@ public void shouldAddCounts() { } @Test - public void shouldIncreaseAndResetCount() { + void shouldIncreaseAndResetCount() { // given String address = "192.168.1.2"; Settings settings = mockSettings(3, 60, ""); @@ -99,7 +92,7 @@ public void shouldIncreaseAndResetCount() { } @Test - public void shouldNotIncreaseCountForDisabledTempban() { + void shouldNotIncreaseCountForDisabledTempban() { // given String address = "192.168.1.3"; Settings settings = mockSettings(1, 5, ""); @@ -115,7 +108,7 @@ public void shouldNotIncreaseCountForDisabledTempban() { } @Test - public void shouldNotCheckCountIfTempbanIsDisabled() { + void shouldNotCheckCountIfTempbanIsDisabled() { // given String address = "192.168.1.4"; Settings settings = mockSettings(1, 5, ""); @@ -136,7 +129,7 @@ public void shouldNotCheckCountIfTempbanIsDisabled() { } @Test - public void shouldNotIssueBanIfDisabled() { + void shouldNotIssueBanIfDisabled() { // given Settings settings = mockSettings(0, 0, ""); given(settings.getProperty(SecuritySettings.TEMPBAN_ON_MAX_LOGINS)).willReturn(false); @@ -151,7 +144,7 @@ public void shouldNotIssueBanIfDisabled() { } @Test - public void shouldBanPlayerIp() { + void shouldBanPlayerIp() { // given Player player = mock(Player.class); String ip = "123.45.67.89"; @@ -168,6 +161,7 @@ public void shouldBanPlayerIp() { // then verify(player).kickPlayer(banReason); + ArgumentCaptor captor = ArgumentCaptor.forClass(Date.class); verify(bukkitService).banIp(eq(ip), eq(banReason), captor.capture(), eq("AuthMe")); // Compute the expected expiration date and check that the actual date is within the difference tolerance @@ -178,7 +172,7 @@ public void shouldBanPlayerIp() { } @Test - public void shouldBanPlayerIpCustom() { + void shouldBanPlayerIpCustom() { // given Player player = mock(Player.class); given(player.getName()).willReturn("Bob"); @@ -197,7 +191,7 @@ public void shouldBanPlayerIpCustom() { } @Test - public void shouldResetCountAfterBan() { + void shouldResetCountAfterBan() { // given Player player = mock(Player.class); String ip = "22.44.66.88"; @@ -221,7 +215,7 @@ public void shouldResetCountAfterBan() { } @Test - public void shouldPerformCleanup() { + void shouldPerformCleanup() { // given Map> counts = new HashMap<>(); TimedCounter counter1 = mockCounter(); @@ -272,5 +266,3 @@ private static TimedCounter mockCounter() { return mock(TimedCounter.class); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/VerificationCodeManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/VerificationCodeManagerTest.java index 55ebe1d4bd..9bdfc20d41 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/VerificationCodeManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/VerificationCodeManagerTest.java @@ -16,11 +16,8 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; @@ -29,7 +26,6 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -37,8 +33,7 @@ * Test for {@link VerificationCodeManager}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class VerificationCodeManagerTest { +class VerificationCodeManagerTest { @Mock private Settings settings; @@ -59,14 +54,14 @@ public class VerificationCodeManagerTest { private ArgumentCaptor runnableCaptor; @BeforeEach - public void setUpBasicBehavior() { - given(emailService.hasAllInformation()).willReturn(true); + void setUpBasicBehavior() { given(settings.getProperty(SecuritySettings.VERIFICATION_CODE_EXPIRATION_MINUTES)).willReturn(1); } @Test - public void shouldRequireVerification() { + void shouldRequireVerification() { // given + given(emailService.hasAllInformation()).willReturn(true); String name1 = "ILoveTests"; Player player1 = mockPlayerWithName(name1); given(dataSource.getEmail(name1)).willReturn(DataSourceValueImpl.of("ilovetests@test.com")); @@ -89,7 +84,7 @@ public void shouldRequireVerification() { } @Test - public void shouldNotRequireVerificationIfEmailSettingsAreIncomplete() { + void shouldNotRequireVerificationIfEmailSettingsAreIncomplete() { // given given(emailService.hasAllInformation()).willReturn(false); VerificationCodeManager codeManager = createCodeManager(); @@ -104,8 +99,9 @@ public void shouldNotRequireVerificationIfEmailSettingsAreIncomplete() { } @Test - public void shouldNotRequireVerificationForMissingPermission() { + void shouldNotRequireVerificationForMissingPermission() { // given + given(emailService.hasAllInformation()).willReturn(true); Player player = mockPlayerWithName("ILoveTests"); given(permissionsManager.hasPermission(player, PlayerPermission.VERIFICATION_CODE)).willReturn(false); VerificationCodeManager codeManager = createCodeManager(); @@ -120,8 +116,9 @@ public void shouldNotRequireVerificationForMissingPermission() { } @Test - public void shouldGenerateCode() { + void shouldGenerateCode() { // given + given(emailService.hasAllInformation()).willReturn(true); String player = "ILoveTests"; String email = "ilovetests@test.com"; given(dataSource.getEmail(player)).willReturn(DataSourceValueImpl.of(email)); @@ -140,8 +137,9 @@ public void shouldGenerateCode() { } @Test - public void shouldRequireCode() { + void shouldRequireCode() { // given + given(emailService.hasAllInformation()).willReturn(true); String player = "ILoveTests"; String email = "ilovetests@test.com"; given(dataSource.getEmail(player)).willReturn(DataSourceValueImpl.of(email)); @@ -160,8 +158,9 @@ public void shouldRequireCode() { } @Test - public void shouldVerifyCode() { + void shouldVerifyCode() { // given + given(emailService.hasAllInformation()).willReturn(true); String player = "ILoveTests"; String code = "193458"; String email = "ilovetests@test.com"; @@ -181,7 +180,7 @@ public void shouldVerifyCode() { } @Test - public void shouldLookupEmailOnlyInAsyncTask() { + void shouldLookupEmailOnlyInAsyncTask() { // given String player = "ILoveTests"; String email = "ilovetests@test.com"; @@ -204,7 +203,7 @@ public void shouldLookupEmailOnlyInAsyncTask() { } @Test - public void shouldNotScheduleDuplicateCodeGenerationWhilePending() { + void shouldNotScheduleDuplicateCodeGenerationWhilePending() { // given String player = "ILoveTests"; VerificationCodeManager codeManager = createCodeManager(); @@ -214,7 +213,7 @@ public void shouldNotScheduleDuplicateCodeGenerationWhilePending() { codeManager.codeExistOrGenerateNew(player); // then - verify(bukkitService, times(1)).runTaskAsynchronously(any(Runnable.class)); + verify(bukkitService).runTaskAsynchronously(any(Runnable.class)); verifyNoInteractions(dataSource); verify(emailService, only()).hasAllInformation(); } @@ -229,5 +228,3 @@ private static Player mockPlayerWithName(String name) { return player; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/auth/PlayerAuthTest.java b/authme-core/src/test/java/fr/xephi/authme/data/auth/PlayerAuthTest.java index 292674ac22..679dc52a0e 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/auth/PlayerAuthTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/auth/PlayerAuthTest.java @@ -10,10 +10,10 @@ /** * Test for {@link PlayerAuth} and its builder. */ -public class PlayerAuthTest { +class PlayerAuthTest { @Test - public void shouldRemoveDatabaseDefaults() { + void shouldRemoveDatabaseDefaults() { // given / when PlayerAuth auth = PlayerAuth.builder() .name("Bobby") @@ -32,7 +32,7 @@ public void shouldRemoveDatabaseDefaults() { } @Test - public void shouldThrowForMissingName() { + void shouldThrowForMissingName() { try { // given / when PlayerAuth.builder() @@ -48,7 +48,7 @@ public void shouldThrowForMissingName() { } @Test - public void shouldCreatePlayerAuthWithNullValues() { + void shouldCreatePlayerAuthWithNullValues() { // given / when PlayerAuth auth = PlayerAuth.builder() .name("Charlie") @@ -67,4 +67,3 @@ public void shouldCreatePlayerAuthWithNullValues() { assertThat(auth.getPitch(), equalTo(123.004f)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/captcha/LoginCaptchaManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/captcha/LoginCaptchaManagerTest.java index 19d09171c3..e612bd8bb0 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/captcha/LoginCaptchaManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/captcha/LoginCaptchaManagerTest.java @@ -10,19 +10,19 @@ import java.util.Locale; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link LoginCaptchaManager}. */ -public class LoginCaptchaManagerTest { +class LoginCaptchaManagerTest { @Test - public void shouldAddCounts() { + void shouldAddCounts() { // given Settings settings = mockSettings(3, 4); LoginCaptchaManager manager = new LoginCaptchaManager(settings); @@ -41,7 +41,7 @@ public void shouldAddCounts() { } @Test - public void shouldCreateAndCheckCaptcha() { + void shouldCreateAndCheckCaptcha() { // given String name = "Miner"; Player player = mock(Player.class); @@ -61,7 +61,7 @@ public void shouldCreateAndCheckCaptcha() { } @Test - public void shouldGenerateNewCodeOnFailure() { + void shouldGenerateNewCodeOnFailure() { // given String name = "Tarheel"; Player player = mock(Player.class); @@ -80,7 +80,7 @@ public void shouldGenerateNewCodeOnFailure() { } @Test - public void shouldHaveSameCodeAfterGeneration() { + void shouldHaveSameCodeAfterGeneration() { // given String player = "Tester"; Settings settings = mockSettings(1, 5); @@ -98,7 +98,7 @@ public void shouldHaveSameCodeAfterGeneration() { } @Test - public void shouldIncreaseAndResetCount() { + void shouldIncreaseAndResetCount() { // given String player = "plaYer"; Settings settings = mockSettings(2, 3); @@ -121,7 +121,7 @@ public void shouldIncreaseAndResetCount() { } @Test - public void shouldNotIncreaseCountForDisabledCaptcha() { + void shouldNotIncreaseCountForDisabledCaptcha() { // given String player = "someone_"; Settings settings = mockSettings(1, 3); @@ -137,7 +137,7 @@ public void shouldNotIncreaseCountForDisabledCaptcha() { } @Test - public void shouldNotCheckCountIfCaptchaIsDisabled() { + void shouldNotCheckCountIfCaptchaIsDisabled() { // given String player = "Robert001"; Settings settings = mockSettings(1, 5); @@ -172,4 +172,3 @@ private static void assertHasCount(LoginCaptchaManager manager, String player, I assertThat(playerCounts.get(player.toLowerCase(Locale.ROOT)), equalTo(count)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/captcha/RegistrationCaptchaManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/captcha/RegistrationCaptchaManagerTest.java index b532a05f6a..a0ef35bcac 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/captcha/RegistrationCaptchaManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/captcha/RegistrationCaptchaManagerTest.java @@ -8,18 +8,18 @@ import org.junit.jupiter.api.Test; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link RegistrationCaptchaManager}. */ -public class RegistrationCaptchaManagerTest { +class RegistrationCaptchaManagerTest { @Test - public void shouldBeDisabled() { + void shouldBeDisabled() { // given Settings settings = mock(Settings.class); // Return false first time, and true after that @@ -37,7 +37,7 @@ public void shouldBeDisabled() { } @Test - public void shouldVerifyCodeSuccessfully() { + void shouldVerifyCodeSuccessfully() { // given Settings settings = mock(Settings.class); given(settings.getProperty(SecuritySettings.ENABLE_CAPTCHA_FOR_REGISTRATION)).willReturn(true); @@ -60,7 +60,7 @@ public void shouldVerifyCodeSuccessfully() { } @Test - public void shouldGenerateAndRetrieveCode() { + void shouldGenerateAndRetrieveCode() { // given Settings settings = mock(Settings.class); given(settings.getProperty(SecuritySettings.ENABLE_CAPTCHA_FOR_REGISTRATION)).willReturn(true); @@ -91,4 +91,3 @@ private static ExpiringMap getCodeMap(RegistrationCaptchaManager return ReflectionTestUtils.getFieldValue(CaptchaCodeStorage.class, captchaStorage, "captchaCodes"); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/AllowFlightRestoreTypeTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/AllowFlightRestoreTypeTest.java index ac0b55aba2..efc7d75196 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/AllowFlightRestoreTypeTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/AllowFlightRestoreTypeTest.java @@ -11,10 +11,10 @@ /** * Test for {@link AllowFlightRestoreType}. */ -public class AllowFlightRestoreTypeTest { +class AllowFlightRestoreTypeTest { @Test - public void shouldRestoreValue() { + void shouldRestoreValue() { // given LimboPlayer limboWithFly = newLimboWithAllowFlight(true); LimboPlayer limboWithoutFly = newLimboWithAllowFlight(false); @@ -31,7 +31,7 @@ public void shouldRestoreValue() { } @Test - public void shouldEnableFlight() { + void shouldEnableFlight() { // given LimboPlayer limboWithFly = newLimboWithAllowFlight(true); LimboPlayer limboWithoutFly = newLimboWithAllowFlight(false); @@ -49,7 +49,7 @@ public void shouldEnableFlight() { @Test - public void shouldDisableFlight() { + void shouldDisableFlight() { // given LimboPlayer limboWithFly = newLimboWithAllowFlight(true); LimboPlayer limboWithoutFly = newLimboWithAllowFlight(false); @@ -66,7 +66,7 @@ public void shouldDisableFlight() { } @Test - public void shouldNotInteractWithPlayer() { + void shouldNotInteractWithPlayer() { // given LimboPlayer limboWithFly = newLimboWithAllowFlight(true); LimboPlayer limboWithoutFly = newLimboWithAllowFlight(false); @@ -82,7 +82,7 @@ public void shouldNotInteractWithPlayer() { } @Test - public void shouldRemoveFlightExceptForNothingType() { + void shouldRemoveFlightExceptForNothingType() { // given AllowFlightRestoreType noInteractionType = AllowFlightRestoreType.NOTHING; @@ -107,4 +107,3 @@ private static LimboPlayer newLimboWithAllowFlight(boolean allowFlight) { return limbo; } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java index 0143ab626d..3977b181fd 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.data.limbo; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.captcha.RegistrationCaptchaManager; @@ -19,17 +15,19 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import static fr.xephi.authme.service.BukkitService.TICKS_PER_SECOND; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; @@ -42,8 +40,7 @@ * Test for {@link LimboPlayerTaskManager}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class LimboPlayerTaskManagerTest { +class LimboPlayerTaskManagerTest { @InjectMocks private LimboPlayerTaskManager limboPlayerTaskManager; @@ -64,12 +61,12 @@ public class LimboPlayerTaskManagerTest { private RegistrationCaptchaManager registrationCaptchaManager; @BeforeAll - public static void setupLogger() { + static void setupLogger() { TestHelper.setupLogger(); } @Test - public void shouldRegisterMessageTask() { + void shouldRegisterMessageTask() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -91,7 +88,7 @@ public void shouldRegisterMessageTask() { } @Test - public void shouldNotScheduleTaskForZeroAsInterval() { + void shouldNotScheduleTaskForZeroAsInterval() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -106,7 +103,7 @@ public void shouldNotScheduleTaskForZeroAsInterval() { } @Test - public void shouldCancelExistingMessageTask() { + void shouldCancelExistingMessageTask() { // given String name = "rats"; Player player = mock(Player.class); @@ -129,7 +126,7 @@ public void shouldCancelExistingMessageTask() { } @Test - public void shouldInitializeMessageTaskWithCaptchaMessage() { + void shouldInitializeMessageTaskWithCaptchaMessage() { // given String name = "race"; Player player = mock(Player.class); @@ -150,7 +147,7 @@ public void shouldInitializeMessageTaskWithCaptchaMessage() { } @Test - public void shouldRegisterLoginTimeoutTask() { + void shouldRegisterTimeoutTask() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -168,7 +165,7 @@ public void shouldRegisterLoginTimeoutTask() { } @Test - public void shouldRegisterRegisterTimeoutTask() { + void shouldNotRegisterTimeoutTaskForZeroTimeout() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -186,7 +183,7 @@ public void shouldRegisterRegisterTimeoutTask() { } @Test - public void shouldNotRegisterTimeoutTaskForZeroLoginTimeout() { + void shouldNotRegisterTimeoutTaskForZeroLoginTimeout() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -200,7 +197,7 @@ public void shouldNotRegisterTimeoutTaskForZeroLoginTimeout() { } @Test - public void shouldNotRegisterTimeoutTaskForZeroRegisterTimeout() { + void shouldNotRegisterTimeoutTaskForZeroRegisterTimeout() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -214,7 +211,7 @@ public void shouldNotRegisterTimeoutTaskForZeroRegisterTimeout() { } @Test - public void shouldCancelExistingTimeoutTask() { + void shouldCancelExistingTimeoutTask() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = new LimboPlayer(null, false, Collections.emptyList(), true, 0.3f, 0.1f); @@ -235,5 +232,3 @@ public void shouldCancelExistingTimeoutTask() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java index 21e65f6532..ab734cfeae 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java @@ -1,24 +1,22 @@ package fr.xephi.authme.data.limbo; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import org.bukkit.World; import org.bukkit.Location; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.UUID; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -28,19 +26,18 @@ * Note: some methods are tested directly where they are used via {@link LimboServiceTest}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class LimboServiceHelperTest { +class LimboServiceHelperTest { @InjectMocks private LimboServiceHelper limboServiceHelper; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldMergeLimboPlayers() { + void shouldMergeLimboPlayers() { // given Location newLocation = mock(Location.class); LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList(new UserGroup("grp-new")), false, 0.0f, 0.0f); @@ -61,7 +58,7 @@ public void shouldMergeLimboPlayers() { } @Test - public void shouldFallBackToNewLimboForMissingData() { + void shouldFallBackToNewLimboForMissingData() { // given Location newLocation = mock(Location.class); LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList(new UserGroup("grp-new")), true, 0.3f, 0.0f); @@ -81,7 +78,7 @@ public void shouldFallBackToNewLimboForMissingData() { } @Test - public void shouldMergeEnderPearlRestoreData() { + void shouldMergeEnderPearlRestoreData() { // given World world = mock(World.class); Location oldLocation = new Location(world, 1.0, 2.0, 3.0); @@ -113,7 +110,7 @@ public void shouldMergeEnderPearlRestoreData() { } @Test - public void shouldHandleNullInputs() { + void shouldHandleNullInputs() { // given LimboPlayer limbo = mock(LimboPlayer.class); @@ -129,5 +126,3 @@ public void shouldHandleNullInputs() { assertThat(result3, nullValue()); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java index 7910196aa2..605bf6bb46 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.data.limbo; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.persistence.LimboPersistence; @@ -16,31 +13,34 @@ import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.EnderPearl; -import org.bukkit.entity.Player; import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collection; import java.util.Collections; -import java.util.List; import java.util.Map; import java.util.UUID; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; @@ -49,13 +49,13 @@ /** * Test for {@link LimboService}, and {@link LimboServiceHelper}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class LimboServiceTest { +@ExtendWith(MockitoExtension.class) +class LimboServiceTest { - @InjectDelayed + @InjectMocks private LimboService limboService; - @InjectDelayed + @InjectMocks private LimboServiceHelper limboServiceHelper; @Mock @@ -85,15 +85,12 @@ public static void initLogger() { } @BeforeEach - public void mockSettings() { - given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); - given(settings.getProperty(LimboSettings.RECREATE_ENDER_PEARLS)).willReturn(true); - given(teleportationService.consumeOriginalJoinLocation(anyString(), any())) - .willAnswer(invocation -> invocation.getArgument(1)); + void mockSettings() { + ReflectionTestUtils.setField(limboService, "helper", limboServiceHelper); } @Test - public void shouldCreateLimboPlayer() { + void shouldCreateLimboPlayer() { // given Player player = newPlayer("Bobby", true, 0.3f, false, 0.2f); Location playerLoc = mock(Location.class); @@ -101,6 +98,9 @@ public void shouldCreateLimboPlayer() { given(permissionsManager.hasGroupSupport()).willReturn(true); given(permissionsManager.getGroups(player)).willReturn(Collections.singletonList(new UserGroup("permgrwp"))); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.ENABLE); + given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); + given(teleportationService.consumeOriginalJoinLocation(anyString(), any(Location.class))) + .willAnswer(invocation -> invocation.getArgument(1)); // when limboService.createLimboPlayer(player, true); @@ -125,13 +125,16 @@ public void shouldCreateLimboPlayer() { } @Test - public void shouldNotKeepOpStatusForUnregisteredPlayer() { + void shouldNotKeepOpStatusForUnregisteredPlayer() { // given Player player = newPlayer("CharleS", true, 0.1f, true, 0.4f); Location playerLoc = mock(Location.class); given(spawnLoader.getPlayerLocationOrSpawn(player)).willReturn(playerLoc); given(permissionsManager.hasGroupSupport()).willReturn(false); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.RESTORE); + given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); + given(teleportationService.consumeOriginalJoinLocation(anyString(), any(Location.class))) + .willAnswer(invocation -> invocation.getArgument(1)); // when limboService.createLimboPlayer(player, false); @@ -156,12 +159,13 @@ public void shouldNotKeepOpStatusForUnregisteredPlayer() { } @Test - public void shouldClearTasksOnAlreadyExistingLimbo() { + void shouldClearTasksOnAlreadyExistingLimbo() { // given LimboPlayer existingLimbo = mock(LimboPlayer.class); getLimboMap().put("carlos", existingLimbo); Player player = newPlayer("Carlos"); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.ENABLE); + given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); // when limboService.createLimboPlayer(player, false); @@ -175,7 +179,7 @@ public void shouldClearTasksOnAlreadyExistingLimbo() { } @Test - public void shouldUseRememberedJoinLocationWhenCreatingLimboPlayer() { + void shouldUseRememberedJoinLocationWhenCreatingLimboPlayer() { // given Player player = newPlayer("Bobby", true, 0.3f, false, 0.2f); Location fallbackLocation = mock(Location.class); @@ -185,6 +189,7 @@ public void shouldUseRememberedJoinLocationWhenCreatingLimboPlayer() { .willReturn(rememberedJoinLocation); given(permissionsManager.hasGroupSupport()).willReturn(false); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.ENABLE); + given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); // when limboService.createLimboPlayer(player, true); @@ -194,7 +199,7 @@ public void shouldUseRememberedJoinLocationWhenCreatingLimboPlayer() { } @Test - public void shouldRestoreData() { + void shouldRestoreData() { // given LimboPlayer limbo = Mockito.spy(convertToLimboPlayer( newPlayer("John", true, 0.4f, false, 0.0f), null, Collections.emptyList())); @@ -220,7 +225,7 @@ public void shouldRestoreData() { } @Test - public void shouldHandleMissingLimboPlayerWhileRestoring() { + void shouldHandleMissingLimboPlayerWhileRestoring() { // given Player player = newPlayer("Test"); @@ -236,7 +241,7 @@ public void shouldHandleMissingLimboPlayerWhileRestoring() { } @Test - public void shouldRemoveDiskLimboEvenWhenNoInMemoryLimboExists() { + void shouldRemoveDiskLimboEvenWhenNoInMemoryLimboExists() { // given - simulates race condition: player quit before createLimboPlayer ran Player player = newPlayer("Speedy"); // no entry in memory map for this player @@ -250,7 +255,7 @@ public void shouldRemoveDiskLimboEvenWhenNoInMemoryLimboExists() { } @Test - public void shouldReplaceTasks() { + void shouldReplaceTasks() { // given LimboPlayer limbo = mock(LimboPlayer.class); getLimboMap().put("jeff", limbo); @@ -267,7 +272,7 @@ public void shouldReplaceTasks() { } @Test - public void shouldRecreateMissingEnderPearls() { + void shouldRecreateMissingEnderPearls() { // given Player player = newPlayer("Pearlie"); Server server = mock(Server.class); @@ -287,6 +292,8 @@ public void shouldRecreateMissingEnderPearls() { limbo.setEnderPearls(Collections.singletonList(new EnderPearlRestoreData(pearlUuid, pearlLocation, pearlVelocity))); getLimboMap().put("pearlie", limbo); + given(settings.getProperty(LimboSettings.RECREATE_ENDER_PEARLS)).willReturn(true); + // when limboService.restoreEntities(player); @@ -298,7 +305,7 @@ public void shouldRecreateMissingEnderPearls() { } @Test - public void shouldNotRecreateMissingEnderPearlsWhenDisabledInConfig() { + void shouldNotRecreateMissingEnderPearlsWhenDisabledInConfig() { // given given(settings.getProperty(LimboSettings.RECREATE_ENDER_PEARLS)).willReturn(false); @@ -327,7 +334,7 @@ public void shouldNotRecreateMissingEnderPearlsWhenDisabledInConfig() { } @Test - public void shouldHandleMissingLimboForReplaceTasks() { + void shouldHandleMissingLimboForReplaceTasks() { // given Player player = newPlayer("ghost"); @@ -341,16 +348,16 @@ public void shouldHandleMissingLimboForReplaceTasks() { private static Player newPlayer(String name) { Player player = mock(Player.class); - given(player.getName()).willReturn(name); + lenient().when(player.getName()).thenReturn(name); return player; } private static Player newPlayer(String name, boolean isOp, float walkSpeed, boolean canFly, float flySpeed) { Player player = newPlayer(name); - given(player.isOp()).willReturn(isOp); - given(player.getWalkSpeed()).willReturn(walkSpeed); - given(player.getAllowFlight()).willReturn(canFly); - given(player.getFlySpeed()).willReturn(flySpeed); + lenient().when(player.isOp()).thenReturn(isOp); + lenient().when(player.getWalkSpeed()).thenReturn(walkSpeed); + lenient().when(player.getAllowFlight()).thenReturn(canFly); + lenient().when(player.getFlySpeed()).thenReturn(flySpeed); return player; } @@ -363,5 +370,3 @@ private Map getLimboMap() { return ReflectionTestUtils.getFieldValue(LimboService.class, limboService, "entries"); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java index c348c377c8..bb857a381b 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java @@ -20,11 +20,11 @@ /** * Test for {@link WalkFlySpeedRestoreType}. */ -public class WalkFlySpeedRestoreTypeTest { +class WalkFlySpeedRestoreTypeTest { - @ParameterizedTest(name = "{0}") + @ParameterizedTest @MethodSource("buildParams") - public void shouldRestoreToExpectedValue(TestParameters parameters) { + void shouldRestoreToExpectedValue(TestParameters parameters) { // given LimboPlayer limbo = mock(LimboPlayer.class); given(limbo.getWalkSpeed()).willReturn(parameters.givenLimboWalkSpeed); @@ -43,8 +43,7 @@ public void shouldRestoreToExpectedValue(TestParameters parameters) { verify(player).setFlySpeed(parameters.expectedFlySpeed); } - - public static List buildParams() { + private static List buildParams() { return Arrays.asList( create(RESTORE).withLimbo(0.1f, 0.4f).withPlayer(0.3f, 0.9f).expect(0.1f, 0.4f), create(RESTORE).withLimbo(0.9f, 0.2f).withPlayer(0.3f, 0.0f).expect(0.9f, 0.2f), @@ -70,19 +69,19 @@ private static final class TestParameters { private float givenPlayerFlySpeed; private float expectedWalkSpeed; private float expectedFlySpeed; - + TestParameters withLimbo(float walkSpeed, float flySpeed) { this.givenLimboWalkSpeed = walkSpeed; this.givenLimboFlySpeed = flySpeed; return this; } - + TestParameters withPlayer(float walkSpeed, float flySpeed) { this.givenPlayerWalkSpeed = walkSpeed; this.givenPlayerFlySpeed = flySpeed; return this; } - + TestParameters expect(float walkSpeed, float flySpeed) { this.expectedWalkSpeed = walkSpeed; this.expectedFlySpeed = flySpeed; @@ -95,4 +94,3 @@ public String toString() { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java index cf413fb67c..096b7d6eb6 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java @@ -1,14 +1,9 @@ package fr.xephi.authme.data.limbo.persistence; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.UserGroup; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.LimboSettings; @@ -17,9 +12,12 @@ import org.bukkit.entity.Player; import org.hamcrest.Matcher; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -37,13 +35,14 @@ import static org.hamcrest.Matchers.nullValue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; /** * Test for {@link DistributedFilesPersistenceHandler}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class DistributedFilesPersistenceHandlerTest { +@ExtendWith(MockitoExtension.class) +class DistributedFilesPersistenceHandlerTest { /** Player is in seg32-10110 and should be migrated into seg16-f. */ private static final UUID MIGRATED_UUID = fromString("f6a97c88-7c8f-c12e-4931-6206d4ca067d"); @@ -72,27 +71,24 @@ public class DistributedFilesPersistenceHandlerTest { private static final UUID UNKNOWN_UUID2 = fromString("84d1cc0b-8f12-d04a-e7ba-a067d05cdc39"); - @InjectDelayed private DistributedFilesPersistenceHandler persistenceHandler; @Mock private Settings settings; @Mock private BukkitService bukkitService; - @DataFolder - private File dataFolder; + @TempDir + File dataFolder; private File playerDataFolder; - public TempFolder temporaryFolder = new TempFolder(); @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void setUpClasses() throws IOException { + @BeforeEach + void setUpClasses() throws IOException { given(settings.getProperty(LimboSettings.DISTRIBUTION_SIZE)).willReturn(SegmentSize.SIXTEEN); - dataFolder = temporaryFolder.newFolder(); playerDataFolder = new File(dataFolder, "playerdata"); playerDataFolder.mkdir(); @@ -105,16 +101,18 @@ public void setUpClasses() throws IOException { given(bukkitService.getWorld(anyString())) .willAnswer(invocation -> { World world = mock(World.class); - given(world.getName()).willReturn(invocation.getArgument(0)); + lenient().when(world.getName()).thenReturn(invocation.getArgument(0)); return world; }); + + persistenceHandler = new DistributedFilesPersistenceHandler(dataFolder, bukkitService, settings); } // Note ljacqu 20170314: These tests are a little slow to set up; therefore we sometimes // test things in one test that would traditionally belong into two separate tests @Test - public void shouldMigrateOldSegmentFilesOnStartup() { + void shouldMigrateOldSegmentFilesOnStartup() { // Ensure that only the files of the current segmenting scheme remain assertThat(playerDataFolder.list(), arrayContainingInAnyOrder("seg16-8-limbo.json", "seg16-f-limbo.json")); @@ -130,7 +128,7 @@ public void shouldMigrateOldSegmentFilesOnStartup() { } @Test - public void shouldRemovePlayer() { + void shouldRemovePlayer() { // given Player playerToRemove = mockPlayerWithUuid(UUID_STAFF); Player unknownPlayerToRemove = mockPlayerWithUuid(UNKNOWN_UUID); @@ -150,7 +148,7 @@ public void shouldRemovePlayer() { } @Test - public void shouldAddPlayer() { + void shouldAddPlayer() { // given Player uuidToAdd1 = mockPlayerWithUuid(UNKNOWN_UUID); Location location1 = mockLocation("1world"); @@ -178,7 +176,7 @@ public void shouldAddPlayer() { } @Test - public void shouldHandleReadErrorGracefully() throws IOException { + void shouldHandleReadErrorGracefully() throws IOException { // given // assumption File invalidFile = new File(playerDataFolder, "seg16-4-limbo.json"); @@ -211,5 +209,3 @@ private static Location mockLocation(String worldName) { return location; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java index 4b04ec17d7..ff382f6c4a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java @@ -1,23 +1,21 @@ package fr.xephi.authme.data.limbo.persistence; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.EnderPearlRestoreData; import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.UserGroup; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.util.FileUtils; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.util.Vector; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -25,47 +23,46 @@ import java.util.Collections; import java.util.UUID; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link IndividualFilesPersistenceHandler}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class IndividualFilesPersistenceHandlerTest { +@ExtendWith(MockitoExtension.class) +class IndividualFilesPersistenceHandlerTest { private static final UUID SAMPLE_UUID = UUID.nameUUIDFromBytes("PersistenceTest".getBytes()); private static final String SOURCE_FOLDER = TestHelper.PROJECT_ROOT + "data/backup/"; - @InjectDelayed private IndividualFilesPersistenceHandler handler; @Mock private BukkitService bukkitService; - @DataFolder - private File dataFolder; - public TempFolder temporaryFolder = new TempFolder(); + @TempDir + File dataFolder; - @BeforeInjecting - public void copyTestFiles() throws IOException { - dataFolder = temporaryFolder.newFolder(); + @BeforeEach + void copyTestFilesAndInitHandler() throws IOException { File playerFolder = new File(dataFolder, FileUtils.makePath("playerdata", SAMPLE_UUID.toString())); if (!playerFolder.mkdirs()) { throw new IllegalStateException("Cannot create '" + playerFolder.getAbsolutePath() + "'"); } Files.copy(TestHelper.getJarPath(FileUtils.makePath(SOURCE_FOLDER, "sample-folder", "data.json")), new File(playerFolder, "data.json").toPath()); + + handler = new IndividualFilesPersistenceHandler(dataFolder, bukkitService); } @Test - public void shouldReadDataFromFile() { + void shouldReadDataFromFile() { // given Player player = mock(Player.class); given(player.getUniqueId()).willReturn(SAMPLE_UUID); @@ -92,7 +89,7 @@ public void shouldReadDataFromFile() { } @Test - public void shouldReturnNullForUnavailablePlayer() { + void shouldReturnNullForUnavailablePlayer() { // given Player player = mock(Player.class); given(player.getUniqueId()).willReturn(UUID.nameUUIDFromBytes("other-player".getBytes())); @@ -105,7 +102,7 @@ public void shouldReturnNullForUnavailablePlayer() { } @Test - public void shouldSavePlayerData() { + void shouldSavePlayerData() { // given Player player = mock(Player.class); UUID uuid = UUID.nameUUIDFromBytes("New player".getBytes()); @@ -127,7 +124,7 @@ public void shouldSavePlayerData() { } @Test - public void shouldPersistEnderPearlRestoreData() { + void shouldPersistEnderPearlRestoreData() { // given Player player = mock(Player.class); UUID uuid = UUID.nameUUIDFromBytes("Pearl player".getBytes()); @@ -160,5 +157,3 @@ public void shouldPersistEnderPearlRestoreData() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java index 70f1d9bac3..9b89a71edc 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java @@ -1,10 +1,6 @@ package fr.xephi.authme.data.limbo.persistence; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; import ch.jalu.injector.factory.Factory; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.LimboPlayer; @@ -13,8 +9,11 @@ import org.bukkit.entity.Player; import org.hamcrest.Matcher; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.logging.Logger; @@ -37,11 +36,9 @@ /** * Test for {@link LimboPersistence}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class LimboPersistenceTest { +@ExtendWith(MockitoExtension.class) +class LimboPersistenceTest { - @SuppressWarnings("unused") - @InjectDelayed private LimboPersistence limboPersistence; @Mock @@ -51,26 +48,27 @@ public class LimboPersistenceTest { private Settings settings; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } - @BeforeInjecting + @BeforeEach @SuppressWarnings("unchecked") - public void setUpMocks() { + void setUpMocksAndLimboPersistence() { given(settings.getProperty(LimboSettings.LIMBO_PERSISTENCE_TYPE)).willReturn(LimboPersistenceType.DISABLED); given(handlerFactory.newInstance(any(Class.class))) .willAnswer(invocation -> mock((Class) invocation.getArgument(0))); + limboPersistence = new LimboPersistence(settings, handlerFactory); } @Test - public void shouldInitializeProperly() { + void shouldInitializeProperly() { // given / when / then assertThat(getHandler(), instanceOf(NoOpPersistenceHandler.class)); } @Test - public void shouldDelegateToHandler() { + void shouldDelegateToHandler() { // given Player player = mock(Player.class); LimboPersistenceHandler handler = getHandler(); @@ -90,7 +88,7 @@ public void shouldDelegateToHandler() { } @Test - public void shouldReloadProperly() { + void shouldReloadProperly() { // given given(settings.getProperty(LimboSettings.LIMBO_PERSISTENCE_TYPE)) .willReturn(LimboPersistenceType.INDIVIDUAL_FILES); @@ -103,7 +101,7 @@ public void shouldReloadProperly() { } @Test - public void shouldHandleExceptionWhenGettingLimbo() { + void shouldHandleExceptionWhenGettingLimbo() { // given Player player = mock(Player.class); Logger logger = TestHelper.setupLogger(); @@ -119,7 +117,7 @@ public void shouldHandleExceptionWhenGettingLimbo() { } @Test - public void shouldHandleExceptionWhenSavingLimbo() { + void shouldHandleExceptionWhenSavingLimbo() { // given Player player = mock(Player.class); LimboPlayer limbo = mock(LimboPlayer.class); @@ -135,7 +133,7 @@ public void shouldHandleExceptionWhenSavingLimbo() { } @Test - public void shouldHandleExceptionWhenRemovingLimbo() { + void shouldHandleExceptionWhenRemovingLimbo() { // given Player player = mock(Player.class); Logger logger = TestHelper.setupLogger(); @@ -157,5 +155,3 @@ private static Matcher notNullAndDifferentFrom(T o) { return both(not(sameInstance(o))).and(not(nullValue())); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTypeTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTypeTest.java index cf0fb2d314..487e05ce15 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTypeTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTypeTest.java @@ -5,8 +5,8 @@ import java.util.HashSet; import java.util.Set; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -14,10 +14,10 @@ /** * Test for {@link LimboPersistenceType}. */ -public class LimboPersistenceTypeTest { +class LimboPersistenceTypeTest { @Test - public void shouldHaveUniqueImplementationClasses() { + void shouldHaveUniqueImplementationClasses() { // given Set> classes = new HashSet<>(); @@ -31,7 +31,7 @@ public void shouldHaveUniqueImplementationClasses() { } @Test - public void shouldHaveTypeReturnedFromImplementationClass() { + void shouldHaveTypeReturnedFromImplementationClass() { for (LimboPersistenceType persistenceType : LimboPersistenceType.values()) { // given LimboPersistenceHandler implementationMock = mock(persistenceType.getImplementationClass()); @@ -46,4 +46,3 @@ public void shouldHaveTypeReturnedFromImplementationClass() { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java index 222442a1c5..a0289e3999 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java @@ -12,21 +12,21 @@ import static fr.xephi.authme.data.limbo.persistence.SegmentSize.SIXTY_FOUR; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.THIRTY_TWO; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.TWO_FIFTY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link SegmentNameBuilder}. */ -public class SegmentNameBuilderTest { +class SegmentNameBuilderTest { /** * Checks that using a given segment size really produces as many segments as defined. * E.g. if we partition with {@link SegmentSize#EIGHT} we expect eight different buckets. */ @Test - public void shouldCreatePromisedSizeOfSegments() { + void shouldCreatePromisedSizeOfSegments() { for (SegmentSize part : SegmentSize.values()) { // Perform this check only for `length` <= 5 because the test creates all hex numbers with `length` digits. if (part.getLength() <= 5) { @@ -62,7 +62,7 @@ private static String toPaddedHex(int dec, int padLength) { } @Test - public void shouldCreateOneSegment() { + void shouldCreateOneSegment() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(ONE); @@ -73,7 +73,7 @@ public void shouldCreateOneSegment() { } @Test - public void shouldCreateFourSegments() { + void shouldCreateFourSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(FOUR); @@ -84,7 +84,7 @@ public void shouldCreateFourSegments() { } @Test - public void shouldCreateEightSegments() { + void shouldCreateEightSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(EIGHT); @@ -96,7 +96,7 @@ public void shouldCreateEightSegments() { } @Test - public void shouldCreateSixteenSegments() { + void shouldCreateSixteenSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(SIXTEEN); @@ -107,7 +107,7 @@ public void shouldCreateSixteenSegments() { } @Test - public void shouldCreateThirtyTwoSegments() { + void shouldCreateThirtyTwoSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(THIRTY_TWO); @@ -118,7 +118,7 @@ public void shouldCreateThirtyTwoSegments() { } @Test - public void shouldCreateSixtyFourSegments() { + void shouldCreateSixtyFourSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(SIXTY_FOUR); @@ -129,7 +129,7 @@ public void shouldCreateSixtyFourSegments() { } @Test - public void shouldCreate256Segments() { + void shouldCreate256Segments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(TWO_FIFTY); @@ -139,4 +139,3 @@ public void shouldCreate256Segments() { assertThat(nameBuilder.createSegmentName("7122f"), equalTo("seg256-71")); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentSizeTest.java b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentSizeTest.java index 272777f8b1..4ecee772f6 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentSizeTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentSizeTest.java @@ -14,10 +14,10 @@ /** * Test for {@link SegmentSize}. */ -public class SegmentSizeTest { +class SegmentSizeTest { @Test - public void shouldHaveDistributionThatIsPowerOf2() { + void shouldHaveDistributionThatIsPowerOf2() { // given Set allowedDistributions = ImmutableSet.of(1, 2, 4, 8, 16); @@ -30,7 +30,7 @@ public void shouldHaveDistributionThatIsPowerOf2() { } @Test - public void shouldHaveDifferentSegmentSizes() { + void shouldHaveDifferentSegmentSizes() { // given Set segmentTotals = new HashSet<>(); @@ -45,4 +45,3 @@ public void shouldHaveDifferentSegmentSizes() { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractDataSourceIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractDataSourceIntegrationTest.java index ddd992bb12..3caae01788 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractDataSourceIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractDataSourceIntegrationTest.java @@ -17,6 +17,7 @@ import static fr.xephi.authme.AuthMeMatchers.hasAuthBasicData; import static fr.xephi.authme.AuthMeMatchers.hasAuthLocation; import static fr.xephi.authme.AuthMeMatchers.hasRegistrationInfo; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; @@ -25,22 +26,20 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Abstract class for data source integration tests. */ public abstract class AbstractDataSourceIntegrationTest { - protected DataSource getDataSource() { + private DataSource getDataSource() { return getDataSource("salt"); } protected abstract DataSource getDataSource(String saltColumn); @Test - public void shouldReturnIfAuthIsAvailableOrNot() { + void shouldReturnIfAuthIsAvailableOrNot() { // given DataSource dataSource = getDataSource(); @@ -56,7 +55,7 @@ public void shouldReturnIfAuthIsAvailableOrNot() { } @Test - public void shouldReturnPassword() { + void shouldReturnPassword() { // given DataSource dataSource = getDataSource(); @@ -72,7 +71,7 @@ public void shouldReturnPassword() { } @Test - public void shouldReturnPasswordWithEmptySaltColumn() { + void shouldReturnPasswordWithEmptySaltColumn() { // given DataSource dataSource = getDataSource(""); @@ -88,7 +87,7 @@ public void shouldReturnPasswordWithEmptySaltColumn() { } @Test - public void shouldGetAuth() { + void shouldGetAuth() { // given DataSource dataSource = getDataSource(); @@ -116,7 +115,7 @@ public void shouldGetAuth() { } @Test - public void shouldCountAuthsByEmail() { + void shouldCountAuthsByEmail() { // given DataSource dataSource = getDataSource(); @@ -135,7 +134,7 @@ public void shouldCountAuthsByEmail() { } @Test - public void shouldReturnAllAuths() { + void shouldReturnAllAuths() { // given DataSource dataSource = getDataSource(); @@ -154,7 +153,7 @@ public void shouldReturnAllAuths() { } @Test - public void shouldUpdatePassword() { + void shouldUpdatePassword() { // given DataSource dataSource = getDataSource(); HashedPassword newHash = new HashedPassword("new_hash"); @@ -170,7 +169,7 @@ public void shouldUpdatePassword() { } @Test - public void shouldUpdatePasswordWithNoSalt() { + void shouldUpdatePasswordWithNoSalt() { // given DataSource dataSource = getDataSource(""); HashedPassword newHash = new HashedPassword("new_hash", "1241"); @@ -186,7 +185,7 @@ public void shouldUpdatePasswordWithNoSalt() { } @Test - public void shouldUpdatePasswordWithPlayerAuth() { + void shouldUpdatePasswordWithPlayerAuth() { // given DataSource dataSource = getDataSource("salt"); PlayerAuth bobbyAuth = PlayerAuth.builder().name("bobby").password(new HashedPassword("tt", "cc")).build(); @@ -203,7 +202,7 @@ public void shouldUpdatePasswordWithPlayerAuth() { } @Test - public void shouldRemovePlayerAuth() { + void shouldRemovePlayerAuth() { // given DataSource dataSource = getDataSource(); @@ -218,7 +217,7 @@ public void shouldRemovePlayerAuth() { } @Test - public void shouldUpdateSession() { + void shouldUpdateSession() { // given DataSource dataSource = getDataSource(); PlayerAuth bobby = PlayerAuth.builder() @@ -236,7 +235,7 @@ public void shouldUpdateSession() { } @Test - public void shouldUpdateLastLoc() { + void shouldUpdateLastLoc() { // given DataSource dataSource = getDataSource(); PlayerAuth user = PlayerAuth.builder() @@ -252,11 +251,11 @@ public void shouldUpdateLastLoc() { } @Test - public void shouldDeletePlayers() { + void shouldDeletePlayers() { // given DataSource dataSource = getDataSource(); Set playersToDelete = new HashSet<>(Arrays.asList("bobby", "doesNotExist")); - assumeTrue(dataSource.getAccountsRegistered() == 2); + assertThat(dataSource.getAccountsRegistered(), equalTo(2)); // Make sure we start as expected // when dataSource.purgeRecords(playersToDelete); @@ -268,7 +267,7 @@ public void shouldDeletePlayers() { } @Test - public void shouldUpdateEmail() { + void shouldUpdateEmail() { // given DataSource dataSource = getDataSource(); String email = "new-user@mail.tld"; @@ -286,7 +285,7 @@ public void shouldUpdateEmail() { } @Test - public void shouldCountAuths() { + void shouldCountAuths() { // given DataSource dataSource = getDataSource(); @@ -303,7 +302,7 @@ public void shouldCountAuths() { } @Test - public void shouldGetAllUsersByIp() { + void shouldGetAllUsersByIp() { // given DataSource dataSource = getDataSource(); @@ -327,7 +326,7 @@ public void shouldGetAllUsersByIp() { } @Test - public void shouldUpdateRealName() { + void shouldUpdateRealName() { // given DataSource dataSource = getDataSource(); @@ -342,7 +341,7 @@ public void shouldUpdateRealName() { } @Test - public void shouldGetRecordsToPurge() { + void shouldGetRecordsToPurge() { // given DataSource dataSource = getDataSource(); // 1453242857 -> user, 1449136800 -> bobby @@ -374,7 +373,7 @@ public void shouldGetRecordsToPurge() { } @Test - public void shouldPerformOperationsOnIsLoggedColumnSuccessfully() { + void shouldPerformOperationsOnIsLoggedColumnSuccessfully() { DataSource dataSource = getDataSource(); // on startup no one should be marked as logged assertThat(dataSource.isLogged("user"), equalTo(false)); @@ -404,7 +403,7 @@ public void shouldPerformOperationsOnIsLoggedColumnSuccessfully() { } @Test - public void shouldPerformPurgeOperation() { + void shouldPerformPurgeOperation() { // given List names = Arrays.asList("Bobby", "USER", "DoesnotExist"); DataSource dataSource = getDataSource(); @@ -417,7 +416,7 @@ public void shouldPerformPurgeOperation() { } @Test - public void shouldFetchEmail() { + void shouldFetchEmail() { // given String user1 = "user"; String user2 = "Bogus"; @@ -433,7 +432,7 @@ public void shouldFetchEmail() { } @Test - public void shouldGetLoggedPlayersWithoutEmail() { + void shouldGetLoggedPlayersWithoutEmail() { // given DataSource dataSource = getDataSource(); dataSource.setLogged("bobby"); @@ -447,7 +446,7 @@ public void shouldGetLoggedPlayersWithoutEmail() { } @Test - public void shouldGrantAndRetrieveSessionFlag() { + void shouldGrantAndRetrieveSessionFlag() { // given DataSource dataSource = getDataSource(); @@ -462,7 +461,7 @@ public void shouldGrantAndRetrieveSessionFlag() { } @Test - public void shouldRevokeSession() { + void shouldRevokeSession() { // given DataSource dataSource = getDataSource(); dataSource.grantSession("bobby"); @@ -479,7 +478,7 @@ public void shouldRevokeSession() { } @Test - public void shouldGetRecentlyLoggedInPlayers() { + void shouldGetRecentlyLoggedInPlayers() { // given DataSource dataSource = getDataSource(); String[] names = {"user3", "user8", "user2", "user4", "user7", @@ -505,7 +504,7 @@ public void shouldGetRecentlyLoggedInPlayers() { } @Test - public void shouldSetTotpKey() { + void shouldSetTotpKey() { // given DataSource dataSource = getDataSource(); String newTotpKey = "My new TOTP key"; @@ -519,7 +518,7 @@ public void shouldSetTotpKey() { } @Test - public void shouldRemoveTotpKey() { + void shouldRemoveTotpKey() { // given DataSource dataSource = getDataSource(); @@ -533,4 +532,3 @@ public void shouldRemoveTotpKey() { assertThat(dataSource.getAuth("user").getTotpKey(), nullValue()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java index 6d93c266ce..8ad51ce929 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java @@ -6,8 +6,8 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.security.crypts.HashedPassword; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.TestFactory; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -27,7 +27,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; @@ -44,49 +43,45 @@ * which is set to create additional mocks on demand for Statement and ResultSet objects. * This test ensures that all such objects that are created will be closed again by * keeping a list of mocks ({@link #closeables}) and then verifying that all have been - * closed ({@link #verifyHaveMocksBeenClosed()}). + * closed ({@link #verifyHaveMocksBeenClosed(Method)}). */ public abstract class AbstractResourceClosingTest { /** Collection of values to use to call methods with the parameters they expect. */ private static final Map, Object> PARAM_VALUES = getDefaultParameters(); - /** The DataSource method to test. */ - private Method method; - /** Keeps track of the closeables which are created during the tested call. */ private List closeables = new ArrayList<>(); private boolean hasCreatedConnection = false; @BeforeAll - public static void initializeLogger() { + static void initializeLogger() { TestHelper.setupLogger(); } - @TestFactory - public List shouldCloseResources() { - return getMethodsToTest().stream() - .map(method -> DynamicTest.dynamicTest(method.getName(), () -> assertResourcesClosed(method))) - .collect(Collectors.toList()); - } - - protected final void assertResourcesClosed(Method method) throws IllegalAccessException, InvocationTargetException { - this.method = method; - this.closeables = new ArrayList<>(); - this.hasCreatedConnection = false; + /** + * The actual test -- executes the method given through the constructor and then verifies that all + * AutoCloseable mocks it constructed have been closed. + */ + @ParameterizedTest(name = "{1}") + @MethodSource("createParameters") + // Note ljacqu 20160227: The name parameter is necessary as we pass it from the arguments source method; + // we use the method name in the annotation to name the test sensibly + void shouldCloseResources(Method method, String name) throws IllegalAccessException, InvocationTargetException { method.invoke(getObjectUnderTest(), buildParamListForMethod(method)); - verifyHaveMocksBeenClosed(); + verifyHaveMocksBeenClosed(method); } protected abstract Object getObjectUnderTest(); - protected abstract Collection getMethodsToTest(); - /** * Verify that all AutoCloseables that have been created during the method execution have been closed. */ - private void verifyHaveMocksBeenClosed() { + private void verifyHaveMocksBeenClosed(Method method) { + if (closeables.isEmpty()) { + System.out.println("Note: detected no AutoCloseables for method '" + method.getName() + "'"); + } try { for (AutoCloseable autoCloseable : closeables) { verify(autoCloseable).close(); @@ -193,27 +188,21 @@ protected Connection initConnection() { /* Create Answer that returns a PreparedStatement mock. */ private Answer preparedStatementAnswer() { - return new Answer() { - @Override - public PreparedStatement answer(InvocationOnMock invocation) throws SQLException { - PreparedStatement pst = mock(PreparedStatement.class); - closeables.add(pst); - given(pst.executeQuery()).willAnswer(resultSetAnswer()); - given(pst.executeQuery(anyString())).willAnswer(resultSetAnswer()); - return pst; - } + return invocation -> { + PreparedStatement pst = mock(PreparedStatement.class); + closeables.add(pst); + given(pst.executeQuery()).willAnswer(resultSetAnswer()); + given(pst.executeQuery(anyString())).willAnswer(resultSetAnswer()); + return pst; }; } /* Create Answer that returns a ResultSet mock. */ - private Answer resultSetAnswer() throws SQLException { - return new Answer() { - @Override - public ResultSet answer(InvocationOnMock invocation) throws Throwable { - ResultSet rs = initResultSet(); - closeables.add(rs); - return rs; - } + private Answer resultSetAnswer() { + return invocation -> { + ResultSet rs = initResultSet(); + closeables.add(rs); + return rs; }; } @@ -244,4 +233,3 @@ public Boolean answer(InvocationOnMock invocation) { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractSqlDataSourceResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractSqlDataSourceResourceClosingTest.java index 1ebaefbc63..fd83fb70b3 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractSqlDataSourceResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/AbstractSqlDataSourceResourceClosingTest.java @@ -27,7 +27,7 @@ public abstract class AbstractSqlDataSourceResourceClosingTest extends AbstractR private static Settings settings; @BeforeAll - public static void initializeSettings() { + static void initializeSettings() { settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); TestHelper.setupLogger(); @@ -44,9 +44,18 @@ protected DataSource getObjectUnderTest() { /* Create a DataSource instance with the given mock settings and mock connection. */ protected abstract DataSource createDataSource(Settings settings, Connection connection) throws Exception; - @Override - protected Collection getMethodsToTest() { - return getDataSourceMethods(); + /** + * Initialization method -- provides the parameters to run the test with by scanning all DataSource methods. + * + * @return Test parameters + */ + public static Collection createParameters() { + List methods = getDataSourceMethods(); + List data = new ArrayList<>(); + for (Method method : methods) { + data.add(new Object[]{method, method.getName()}); + } + return data; } /* Get all methods of the DataSource interface, minus the ones in the ignored list. */ @@ -56,4 +65,3 @@ private static List getDataSourceMethods() { .collect(Collectors.toList()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/MySqlIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/MySqlIntegrationTest.java index 12314faa5b..5978fca375 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/MySqlIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/MySqlIntegrationTest.java @@ -7,8 +7,8 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import java.io.IOException; import java.nio.file.Files; @@ -23,7 +23,7 @@ /** * Integration test for {@link MySQL}. */ -public class MySqlIntegrationTest extends AbstractDataSourceIntegrationTest { +class MySqlIntegrationTest extends AbstractDataSourceIntegrationTest { /** Mock of a settings instance. */ private static Settings settings; @@ -36,7 +36,7 @@ public class MySqlIntegrationTest extends AbstractDataSourceIntegrationTest { * Set up the settings mock to return specific values for database settings and load {@link #sqlInitialize}. */ @BeforeAll - public static void initializeSettings() throws IOException, ClassNotFoundException { + static void initializeSettings() throws IOException, ClassNotFoundException { // Check that we have an H2 driver Class.forName("org.h2.jdbcx.JdbcDataSource"); @@ -51,7 +51,7 @@ public static void initializeSettings() throws IOException, ClassNotFoundExcepti } @BeforeEach - public void initializeConnectionAndTable() throws SQLException { + void initializeConnectionAndTable() throws SQLException { HikariConfig config = new HikariConfig(); config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); config.setConnectionTestQuery("VALUES 1"); @@ -71,7 +71,7 @@ public void initializeConnectionAndTable() throws SQLException { } @AfterEach - public void closeConnection() { + void closeConnection() { silentClose(hikariSource); } @@ -92,4 +92,3 @@ private static void silentClose(HikariDataSource con) { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/MySqlResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/MySqlResourceClosingTest.java index a794bb4fb3..fcc75643cc 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/MySqlResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/MySqlResourceClosingTest.java @@ -14,7 +14,7 @@ /** * Resource closing test for {@link MySQL}. */ -public class MySqlResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { +class MySqlResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { @Override protected DataSource createDataSource(Settings settings, Connection connection) throws Exception { diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/PostgreSqlIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/PostgreSqlIntegrationTest.java index 22acfb6f1a..6d5afb53d9 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/PostgreSqlIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/PostgreSqlIntegrationTest.java @@ -7,8 +7,8 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import java.io.IOException; import java.nio.file.Files; @@ -23,7 +23,7 @@ /** * Integration test for {@link PostgreSqlDataSource}. */ -public class PostgreSqlIntegrationTest extends AbstractDataSourceIntegrationTest { +class PostgreSqlIntegrationTest extends AbstractDataSourceIntegrationTest { /** Mock of a settings instance. */ private static Settings settings; @@ -36,7 +36,7 @@ public class PostgreSqlIntegrationTest extends AbstractDataSourceIntegrationTest * Set up the settings mock to return specific values for database settings and load {@link #sqlInitialize}. */ @BeforeAll - public static void initializeSettings() throws IOException, ClassNotFoundException { + static void initializeSettings() throws IOException, ClassNotFoundException { // Check that we have an H2 driver Class.forName("org.h2.jdbcx.JdbcDataSource"); @@ -51,7 +51,7 @@ public static void initializeSettings() throws IOException, ClassNotFoundExcepti } @BeforeEach - public void initializeConnectionAndTable() throws SQLException { + void initializeConnectionAndTable() throws SQLException { HikariConfig config = new HikariConfig(); config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); config.setConnectionTestQuery("VALUES 1"); @@ -69,7 +69,7 @@ public void initializeConnectionAndTable() throws SQLException { } @AfterEach - public void closeConnection() { + void closeConnection() { silentClose(hikariSource); } @@ -90,4 +90,3 @@ private static void silentClose(HikariDataSource con) { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/PostgreSqlResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/PostgreSqlResourceClosingTest.java index 85d14febb3..56e7cb1008 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/PostgreSqlResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/PostgreSqlResourceClosingTest.java @@ -14,7 +14,7 @@ /** * Resource closing test for {@link PostgreSqlDataSource}. */ -public class PostgreSqlResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { +class PostgreSqlResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { @Override protected DataSource createDataSource(Settings settings, Connection connection) throws Exception { @@ -24,5 +24,4 @@ protected DataSource createDataSource(Settings settings, Connection connection) given(extensionsFactory.buildExtension(any(Columns.class))).willReturn(mock(MySqlExtension.class)); return new PostgreSqlDataSource(settings, hikariDataSource, extensionsFactory); } - } diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java index 9e426b5e5d..3675a71863 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java @@ -6,8 +6,8 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -18,15 +18,15 @@ import java.sql.SQLException; import java.sql.Statement; -import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Integration test for {@link SQLite}. */ -public class SQLiteIntegrationTest extends AbstractDataSourceIntegrationTest { +class SQLiteIntegrationTest extends AbstractDataSourceIntegrationTest { /** Mock of a settings instance. */ private static Settings settings; @@ -39,7 +39,7 @@ public class SQLiteIntegrationTest extends AbstractDataSourceIntegrationTest { * Set up the settings mock to return specific values for database settings and load {@link #sqlInitialize}. */ @BeforeAll - public static void initializeSettings() throws IOException, ClassNotFoundException { + static void initializeSettings() throws IOException, ClassNotFoundException { // Check that we have an implementation for SQLite Class.forName("org.sqlite.JDBC"); @@ -56,7 +56,7 @@ public static void initializeSettings() throws IOException, ClassNotFoundExcepti } @BeforeEach - public void initializeConnectionAndTable() throws SQLException { + void initializeConnectionAndTable() throws SQLException { Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:"); try (Statement st = connection.createStatement()) { st.execute("DROP TABLE IF EXISTS authme"); @@ -68,12 +68,12 @@ public void initializeConnectionAndTable() throws SQLException { } @AfterEach - public void closeConnection() { + void closeConnection() { silentClose(con); } @Test - public void shouldSetUpTableIfMissing() throws SQLException { + void shouldSetUpTableIfMissing() throws SQLException { // given Statement st = con.createStatement(); // table is absent @@ -90,7 +90,7 @@ public void shouldSetUpTableIfMissing() throws SQLException { } @Test - public void shouldCreateMissingColumns() throws SQLException { + void shouldCreateMissingColumns() throws SQLException { // given Statement st = con.createStatement(); // drop table and create one with only some of the columns: SQLite doesn't support ALTER TABLE t DROP COLUMN c @@ -133,4 +133,3 @@ private static void silentClose(Connection con) { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/SQLiteResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/SQLiteResourceClosingTest.java index 6f8346511e..8fd6779baa 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/SQLiteResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/SQLiteResourceClosingTest.java @@ -7,11 +7,10 @@ /** * Resource closing test for {@link SQLite}. */ -public class SQLiteResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { +class SQLiteResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { @Override - protected DataSource createDataSource(Settings settings, Connection connection) throws Exception { + protected DataSource createDataSource(Settings settings, Connection connection) { return new SQLite(settings, null, connection); } - } diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/SqLiteMigraterIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/SqLiteMigraterIntegrationTest.java index 41f6cb3b99..bb014cfd17 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/SqLiteMigraterIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/SqLiteMigraterIntegrationTest.java @@ -5,9 +5,10 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.settings.Settings; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -19,41 +20,44 @@ import static fr.xephi.authme.AuthMeMatchers.hasAuthBasicData; import static fr.xephi.authme.AuthMeMatchers.hasAuthLocation; import static fr.xephi.authme.datasource.SqlDataSourceTestUtil.createSqlite; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; /** * Integration test for {@link SqLiteMigrater}. Uses a real SQLite database. */ -public class SqLiteMigraterIntegrationTest { +class SqLiteMigraterIntegrationTest { - private File dataFolder; + @TempDir + File dataFolder; private SQLite sqLite; - public TempFolder temporaryFolder = new TempFolder(); @BeforeEach - public void setup() throws SQLException, IOException, NoSuchMethodException { + void setup() throws SQLException, IOException { TestHelper.setupLogger(); Settings settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); File sqliteDbFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "datasource/sqlite.april2016.db"); - dataFolder = temporaryFolder.newFolder(); File tempFile = new File(dataFolder, "authme.db"); Files.copy(sqliteDbFile, tempFile); Connection con = DriverManager.getConnection("jdbc:sqlite:" + tempFile.getPath()); sqLite = createSqlite(settings, dataFolder, con); + } + @AfterEach + void close() { + sqLite.closeConnection(); } @Test - public void shouldRun() throws ClassNotFoundException, SQLException { + void shouldRun() throws SQLException { // given / when sqLite.setup(); sqLite.migrateIfNeeded(); @@ -100,5 +104,3 @@ private static PlayerAuth getByNameOrFail(String name, List auths) { .findFirst().orElseThrow(() -> new IllegalStateException("No PlayerAuth with name '" + name + "'")); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/SqlDataSourceUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/SqlDataSourceUtilsTest.java index 1ad54ff94f..db75a7bbdd 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/SqlDataSourceUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/SqlDataSourceUtilsTest.java @@ -9,10 +9,10 @@ import java.sql.SQLException; import java.util.logging.Logger; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -22,17 +22,17 @@ /** * Test for {@link SqlDataSourceUtils}. */ -public class SqlDataSourceUtilsTest { +class SqlDataSourceUtilsTest { private Logger logger; @BeforeEach - public void initLogger() { + void initLogger() { logger = TestHelper.setupLogger(); } @Test - public void shouldLogException() { + void shouldLogException() { // given String msg = "Hocus pocus did not work"; SQLException ex = new SQLException(msg); @@ -45,7 +45,7 @@ public void shouldLogException() { } @Test - public void shouldFetchNullableStatus() throws SQLException { + void shouldFetchNullableStatus() throws SQLException { // given String tableName = "data"; String columnName = "category"; @@ -63,7 +63,7 @@ public void shouldFetchNullableStatus() throws SQLException { } @Test - public void shouldReturnFalseForUnknownNullableStatus() throws SQLException { + void shouldReturnFalseForUnknownNullableStatus() throws SQLException { // given String tableName = "comments"; String columnName = "author"; @@ -81,7 +81,7 @@ public void shouldReturnFalseForUnknownNullableStatus() throws SQLException { } @Test - public void shouldThrowForUnknownColumnInNullableCheck() throws SQLException { + void shouldThrowForUnknownColumnInNullableCheck() throws SQLException { // given String tableName = "data"; String columnName = "unknown"; @@ -90,13 +90,13 @@ public void shouldThrowForUnknownColumnInNullableCheck() throws SQLException { DatabaseMetaData metaData = mock(DatabaseMetaData.class); given(metaData.getColumns(null, null, tableName, columnName)).willReturn(resultSet); - // when + // when / then assertThrows(IllegalStateException.class, () -> SqlDataSourceUtils.isNotNullColumn(metaData, tableName, columnName)); } @Test - public void shouldGetDefaultValue() throws SQLException { + void shouldGetDefaultValue() throws SQLException { // given String tableName = "data"; String columnName = "category"; @@ -114,7 +114,7 @@ public void shouldGetDefaultValue() throws SQLException { } @Test - public void shouldThrowForUnknownColumnInDefaultValueRetrieval() throws SQLException { + void shouldThrowForUnknownColumnInDefaultValueRetrieval() throws SQLException { // given String tableName = "data"; String columnName = "unknown"; @@ -123,13 +123,13 @@ public void shouldThrowForUnknownColumnInDefaultValueRetrieval() throws SQLExcep DatabaseMetaData metaData = mock(DatabaseMetaData.class); given(metaData.getColumns(null, null, tableName, columnName)).willReturn(resultSet); - // when + // when / then assertThrows(IllegalStateException.class, () -> SqlDataSourceUtils.getColumnDefaultValue(metaData, tableName, columnName)); } @Test - public void shouldHandleNullDefaultValue() throws SQLException { + void shouldHandleNullDefaultValue() throws SQLException { // given String tableName = "data"; String columnName = "category"; @@ -146,4 +146,3 @@ public void shouldHandleNullDefaultValue() throws SQLException { assertThat(defaultValue, nullValue()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverterTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverterTest.java index f398e6f210..b1b0c7e452 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverterTest.java @@ -28,15 +28,15 @@ /** * Test for {@link AbstractDataSourceConverter}. */ -public class AbstractDataSourceConverterTest { +class AbstractDataSourceConverterTest { @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldThrowForDestinationTypeMismatch() { + void shouldThrowForDestinationTypeMismatch() { // given DataSource destination = mock(DataSource.class); given(destination.getType()).willReturn(DataSourceType.MYSQL); @@ -55,7 +55,7 @@ public void shouldThrowForDestinationTypeMismatch() { } @Test - public void shouldHandleSourceThrowingException() { + void shouldHandleSourceThrowingException() { // given DataSource source = mock(DataSource.class); DataSource destination = mock(DataSource.class); @@ -76,7 +76,7 @@ public void shouldHandleSourceThrowingException() { } @Test - public void shouldConvertAndSkipExistingPlayers() { + void shouldConvertAndSkipExistingPlayers() { // given DataSource source = mock(DataSource.class); DataSource destination = mock(DataSource.class); diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/AbstractMySqlExtensionResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/AbstractMySqlExtensionResourceClosingTest.java index cb3a74fd41..3c8889e468 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/AbstractMySqlExtensionResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/AbstractMySqlExtensionResourceClosingTest.java @@ -6,9 +6,7 @@ import fr.xephi.authme.settings.Settings; import org.junit.jupiter.api.BeforeAll; -import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.Collection; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -24,7 +22,7 @@ public abstract class AbstractMySqlExtensionResourceClosingTest extends Abstract private static Columns columns; @BeforeAll - public static void initSettings() { + static void initSettings() { settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); columns = new Columns(settings); @@ -37,13 +35,6 @@ protected MySqlExtension getObjectUnderTest() { protected abstract MySqlExtension createExtension(Settings settings, Columns columns); - @Override - protected Collection getMethodsToTest() { - return Arrays.stream(MySqlExtension.class.getDeclaredMethods()) - .filter(m -> Modifier.isPublic(m.getModifiers())) - .collect(Collectors.toList()); - } - public static List createParameters() { return Arrays.stream(MySqlExtension.class.getDeclaredMethods()) .filter(m -> Modifier.isPublic(m.getModifiers())) @@ -51,4 +42,3 @@ public static List createParameters() { .collect(Collectors.toList()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/Ipb4ExtensionResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/Ipb4ExtensionResourceClosingTest.java index 4a2d7f1e27..e2398f13a7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/Ipb4ExtensionResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/Ipb4ExtensionResourceClosingTest.java @@ -6,7 +6,7 @@ /** * Resource closing test for {@link Ipb4Extension}. */ -public class Ipb4ExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { +class Ipb4ExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { @Override protected MySqlExtension createExtension(Settings settings, Columns columns) { diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/NoOpExtensionTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/NoOpExtensionTest.java index aadcc23c4b..0317401fc4 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/NoOpExtensionTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/NoOpExtensionTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.datasource.mysqlextensions; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.Columns; @@ -11,6 +7,8 @@ import fr.xephi.authme.settings.Settings; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.sql.Connection; import java.sql.SQLException; @@ -22,13 +20,12 @@ * Test for {@link NoOpExtension}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class NoOpExtensionTest { +class NoOpExtensionTest { private NoOpExtension extension; @BeforeEach - public void createExtension() { + void createExtension() { Settings settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); Columns columns = new Columns(settings); @@ -36,7 +33,7 @@ public void createExtension() { } @Test - public void shouldNotHaveAnyInteractionsWithConnection() throws SQLException { + void shouldNotHaveAnyInteractionsWithConnection() throws SQLException { // given Connection connection = mock(Connection.class); PlayerAuth auth = mock(PlayerAuth.class); @@ -55,5 +52,3 @@ public void shouldNotHaveAnyInteractionsWithConnection() throws SQLException { verifyNoInteractions(connection, auth); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/PhpBbExtensionResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/PhpBbExtensionResourceClosingTest.java index 1156dde9f6..64a252c966 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/PhpBbExtensionResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/PhpBbExtensionResourceClosingTest.java @@ -6,7 +6,7 @@ /** * Resource closing test for {@link PhpBbExtension}. */ -public class PhpBbExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { +class PhpBbExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { @Override protected MySqlExtension createExtension(Settings settings, Columns columns) { diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/WordpressExtensionResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/WordpressExtensionResourceClosingTest.java index 20a51a6f43..62e737dc88 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/WordpressExtensionResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/WordpressExtensionResourceClosingTest.java @@ -6,7 +6,7 @@ /** * Resource closing test for {@link WordpressExtension}. */ -public class WordpressExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { +class WordpressExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { @Override protected MySqlExtension createExtension(Settings settings, Columns columns) { diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/XfBcryptExtensionResourceClosingTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/XfBcryptExtensionResourceClosingTest.java index 33a3c53e45..aa7f3ab4f3 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/XfBcryptExtensionResourceClosingTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/mysqlextensions/XfBcryptExtensionResourceClosingTest.java @@ -6,7 +6,7 @@ /** * Resource closing test for {@link XfBcryptExtension}. */ -public class XfBcryptExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { +class XfBcryptExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { @Override protected MySqlExtension createExtension(Settings settings, Columns columns) { From d84400c3eddcdf47282b464fb4f6a6df4b690dc9 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Thu, 23 Apr 2026 10:22:44 +0200 Subject: [PATCH 3/5] JUnit cleanup for packages events, initialization, listener --- .../authme/events/EventsConsistencyTest.java | 11 +- .../authme/initialization/TaskCloserTest.java | 11 +- .../authme/listener/BlockListenerTest.java | 19 +-- .../authme/listener/EntityListenerTest.java | 39 +++-- .../listener/ListenerConsistencyTest.java | 15 +- .../authme/listener/ListenerServiceTest.java | 43 +++--- .../authme/listener/OnJoinVerifierTest.java | 111 +++++++------- .../authme/listener/PlayerListenerTest.java | 144 +++++++++--------- .../authme/listener/ServerListenerTest.java | 17 +-- 9 files changed, 194 insertions(+), 216 deletions(-) diff --git a/authme-core/src/test/java/fr/xephi/authme/events/EventsConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/events/EventsConsistencyTest.java index 3e35d85411..0830361772 100644 --- a/authme-core/src/test/java/fr/xephi/authme/events/EventsConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/events/EventsConsistencyTest.java @@ -10,20 +10,20 @@ import java.lang.reflect.Modifier; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * Checks the consistency of the AuthMe event classes. */ -public class EventsConsistencyTest { +class EventsConsistencyTest { private static final String EVENTS_FOLDER = TestHelper.PROJECT_ROOT + "events/"; private static List> classes; @BeforeAll - public static void scanEventClasses() { + static void scanEventClasses() { ClassCollector classCollector = new ClassCollector(TestHelper.SOURCES_FOLDER, EVENTS_FOLDER); classes = classCollector.collectClasses(Event.class); @@ -33,7 +33,7 @@ public static void scanEventClasses() { } @Test - public void shouldExtendFromCustomEvent() { + void shouldExtendFromCustomEvent() { for (Class clazz : classes) { assertThat("Class " + clazz.getSimpleName() + " is subtype of CustomEvent", CustomEvent.class.isAssignableFrom(clazz), equalTo(true)); @@ -46,7 +46,7 @@ public void shouldExtendFromCustomEvent() { * is not instantiable (abstract class). */ @Test - public void shouldHaveStaticEventHandlerMethod() { + void shouldHaveStaticEventHandlerMethod() { for (Class clazz : classes) { Method handlerListMethod = null; try { @@ -67,4 +67,3 @@ private static boolean canBeInstantiated(Class clazz) { return !clazz.isInterface() && !clazz.isEnum() && !Modifier.isAbstract(clazz.getModifiers()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/initialization/TaskCloserTest.java b/authme-core/src/test/java/fr/xephi/authme/initialization/TaskCloserTest.java index 941a2ebf04..9016ff1fbe 100644 --- a/authme-core/src/test/java/fr/xephi/authme/initialization/TaskCloserTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/initialization/TaskCloserTest.java @@ -37,8 +37,7 @@ * Test for {@link TaskCloser}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class TaskCloserTest { +class TaskCloserTest { private static final int[] ACTIVE_WORKERS_ID = {2, 5}; @@ -55,7 +54,7 @@ public class TaskCloserTest { private ArgumentCaptor taskIds; @BeforeEach - public void initAuthMe() { + void initAuthMe() { Server server = mock(Server.class); given(server.getScheduler()).willReturn(bukkitScheduler); given(authMe.getServer()).willReturn(server); @@ -64,7 +63,7 @@ public void initAuthMe() { } @Test - public void shouldWaitForTasksToClose() throws InterruptedException { + void shouldWaitForTasksToClose() throws InterruptedException { // given doNothing().when(taskCloser).sleep(); // avoid sleeping in tests mockActiveWorkers(); @@ -85,7 +84,7 @@ public void shouldWaitForTasksToClose() throws InterruptedException { } @Test - public void shouldAbortForNeverEndingTask() throws InterruptedException { + void shouldAbortForNeverEndingTask() throws InterruptedException { // given doNothing().when(taskCloser).sleep(); // avoid sleeping in tests mockActiveWorkers(); @@ -104,7 +103,7 @@ public void shouldAbortForNeverEndingTask() throws InterruptedException { } @Test - public void shouldStopForInterruptedThread() throws InterruptedException, ExecutionException { + void shouldStopForInterruptedThread() throws InterruptedException, ExecutionException { // Note ljacqu 20160827: This test must be run in its own thread because we throw an InterruptedException. // Somehow the java.nio.Files API used in tests that are run subsequently don't like this and fail otherwise. ExecutorService executor = Executors.newSingleThreadExecutor(); diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/BlockListenerTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/BlockListenerTest.java index 8cbf90a986..e82b9e1474 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/BlockListenerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/BlockListenerTest.java @@ -1,15 +1,13 @@ package fr.xephi.authme.listener; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import org.bukkit.entity.Player; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -20,8 +18,7 @@ * Test for {@link BlockListener}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class BlockListenerTest { +class BlockListenerTest { @InjectMocks private BlockListener listener; @@ -30,7 +27,7 @@ public class BlockListenerTest { private ListenerService listenerService; @Test - public void shouldAllowPlaceEvent() { + void shouldAllowPlaceEvent() { // given Player player = mock(Player.class); BlockPlaceEvent event = mock(BlockPlaceEvent.class); @@ -46,7 +43,7 @@ public void shouldAllowPlaceEvent() { } @Test - public void shouldDenyPlaceEvent() { + void shouldDenyPlaceEvent() { // given Player player = mock(Player.class); BlockPlaceEvent event = mock(BlockPlaceEvent.class); @@ -63,7 +60,7 @@ public void shouldDenyPlaceEvent() { } @Test - public void shouldAllowBreakEvent() { + void shouldAllowBreakEvent() { // given Player player = mock(Player.class); BlockBreakEvent event = mock(BlockBreakEvent.class); @@ -79,7 +76,7 @@ public void shouldAllowBreakEvent() { } @Test - public void shouldDenyBreakEvent() { + void shouldDenyBreakEvent() { // given Player player = mock(Player.class); BlockBreakEvent event = mock(BlockBreakEvent.class); @@ -96,5 +93,3 @@ public void shouldDenyBreakEvent() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java index bf8fd2b6a2..e56353f84d 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.listener; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; @@ -17,12 +13,14 @@ import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.projectiles.ProjectileSource; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.listener.EventCancelVerifier.withServiceMock; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -35,8 +33,7 @@ * Test for {@link EntityListener}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class EntityListenerTest { +class EntityListenerTest { @InjectMocks private EntityListener listener; @@ -45,7 +42,7 @@ public class EntityListenerTest { private ListenerService listenerService; @Test - public void shouldHandleSimpleEvents() { + void shouldHandleSimpleEvents() { withServiceMock(listenerService) .check(listener::onFoodLevelChange, FoodLevelChangeEvent.class) .check(listener::onShoot, EntityShootBowEvent.class) @@ -54,7 +51,7 @@ public void shouldHandleSimpleEvents() { } @Test - public void shouldCancelRegainHealthEvent() { + void shouldCancelRegainHealthEvent() { // given EntityRegainHealthEvent event = mock(EntityRegainHealthEvent.class); given(listenerService.shouldCancelEvent(event)).willReturn(true); @@ -69,7 +66,7 @@ public void shouldCancelRegainHealthEvent() { } @Test - public void shouldNotCancelRegainedHealth() { + void shouldNotCancelRegainedHealth() { // given EntityRegainHealthEvent event = mock(EntityRegainHealthEvent.class); given(listenerService.shouldCancelEvent(event)).willReturn(false); @@ -83,7 +80,7 @@ public void shouldNotCancelRegainedHealth() { } @Test - public void shouldCancelEntityDamageByEntityEvent() { + void shouldCancelEntityDamageByEntityEvent() { // given EntityDamageByEntityEvent event = mock(EntityDamageByEntityEvent.class); Entity player = mock(Player.class); @@ -99,7 +96,7 @@ public void shouldCancelEntityDamageByEntityEvent() { } @Test - public void shouldNotCancelEntityDamageByEntityEvent() { + void shouldNotCancelEntityDamageByEntityEvent() { // given EntityDamageByEntityEvent event = mock(EntityDamageByEntityEvent.class); Entity player = mock(Player.class); @@ -115,7 +112,7 @@ public void shouldNotCancelEntityDamageByEntityEvent() { } @Test - public void shouldCancelEntityDamageEvent() { + void shouldCancelEntityDamageEvent() { // given EntityDamageEvent event = mock(EntityDamageEvent.class); Entity entity = mock(Entity.class); @@ -133,7 +130,7 @@ public void shouldCancelEntityDamageEvent() { } @Test - public void shouldNotCancelEntityDamageEvent() { + void shouldNotCancelEntityDamageEvent() { // given EntityDamageEvent event = mock(EntityDamageEvent.class); given(listenerService.shouldCancelEvent(event)).willReturn(false); @@ -147,7 +144,7 @@ public void shouldNotCancelEntityDamageEvent() { } @Test - public void shouldAllowProjectileLaunchFromNonHuman() { + void shouldAllowProjectileLaunchFromNonHuman() { // given Projectile projectile = mock(Projectile.class); ProjectileSource source = mock(ProjectileSource.class); @@ -164,7 +161,7 @@ public void shouldAllowProjectileLaunchFromNonHuman() { } @Test - public void shouldAllowProjectileLaunchFromAuthedHuman() { + void shouldAllowProjectileLaunchFromAuthedHuman() { // given Projectile projectile = mock(Projectile.class); Player player = mock(Player.class); @@ -182,7 +179,7 @@ public void shouldAllowProjectileLaunchFromAuthedHuman() { } @Test - public void shouldRejectProjectileLaunchFromUnauthed() { + void shouldRejectProjectileLaunchFromUnauthed() { // given Projectile projectile = mock(Projectile.class); Player player = mock(Player.class); @@ -200,7 +197,7 @@ public void shouldRejectProjectileLaunchFromUnauthed() { } @Test - public void shouldHandleOldShooterMethod() { + void shouldHandleOldShooterMethod() { // given Projectile projectile = mock(Projectile.class); Player shooter = mock(Player.class); @@ -217,7 +214,7 @@ public void shouldHandleOldShooterMethod() { } @Test - public void shouldCancelEntityTargetEvent() { + void shouldCancelEntityTargetEvent() { // given EntityTargetEvent event = mock(EntityTargetEvent.class); Entity target = mock(Entity.class); @@ -233,7 +230,7 @@ public void shouldCancelEntityTargetEvent() { } @Test - public void shouldNotCancelEntityTargetEvent() { + void shouldNotCancelEntityTargetEvent() { // given EntityTargetEvent event = mock(EntityTargetEvent.class); Entity target = mock(Entity.class); @@ -248,5 +245,3 @@ public void shouldNotCancelEntityTargetEvent() { verify(event, only()).getTarget(); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/ListenerConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/ListenerConsistencyTest.java index 77350d1340..c953f80fca 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/ListenerConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/ListenerConsistencyTest.java @@ -15,20 +15,20 @@ import java.util.List; import java.util.Set; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; /** * Test for verifying that AuthMe listener methods are well-formed. */ -public final class ListenerConsistencyTest { +final class ListenerConsistencyTest { private static List> classes; @BeforeAll - public static void collectListenerClasses() { + static void collectListenerClasses() { ClassCollector collector = new ClassCollector(TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT + "listener"); classes = collector.collectClasses(Listener.class); @@ -38,14 +38,14 @@ public static void collectListenerClasses() { } @Test - public void shouldSetIgnoreCancelledToTrue() { + void shouldSetIgnoreCancelledToTrue() { for (Class listener : classes) { checkCanceledAttribute(listener); } } @Test - public void shouldHaveOnlyEventListenersAsPublicMembers() { + void shouldHaveOnlyEventListenersAsPublicMembers() { for (Class listener : classes) { checkPublicMethodsAreListeners(listener); } @@ -53,14 +53,14 @@ public void shouldHaveOnlyEventListenersAsPublicMembers() { // #367: Event listeners with EventPriority.MONITOR should not change events @Test - public void shouldNotHaveMonitorLevelEventHandlers() { + void shouldNotHaveMonitorLevelEventHandlers() { for (Class listener : classes) { verifyListenerIsNotUsingMonitorPriority(listener); } } @Test - public void shouldNotHaveMultipleMethodsWithSameName() { + void shouldNotHaveMultipleMethodsWithSameName() { Set events = new HashSet<>(); for (Class listener : classes) { for (Method method : listener.getDeclaredMethods()) { @@ -120,4 +120,3 @@ private static boolean isTestableMethod(Method method) { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java index 4b3e99f999..76cc97e8d1 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.listener; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.service.ValidationService; @@ -14,11 +10,14 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.entity.EntityEvent; import org.bukkit.event.player.PlayerEvent; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -27,10 +26,9 @@ /** * Test for {@link ListenerService}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class ListenerServiceTest { +@ExtendWith(MockitoExtension.class) +class ListenerServiceTest { - @InjectDelayed private ListenerService listenerService; @Mock @@ -45,13 +43,14 @@ public class ListenerServiceTest { @Mock private ValidationService validationService; - @BeforeInjecting - public void initializeDefaultSettings() { + @BeforeEach + void setUpMocksAndService() { given(settings.getProperty(RegistrationSettings.FORCE)).willReturn(true); + listenerService = new ListenerService(settings, dataSource, playerCache, validationService); } @Test - public void shouldHandleEventWithNullEntity() { + void shouldHandleEventWithNullEntity() { // given EntityEvent event = mock(EntityEvent.class); given(event.getEntity()).willReturn(null); @@ -64,7 +63,7 @@ public void shouldHandleEventWithNullEntity() { } @Test - public void shouldHandleEntityEventWithNonPlayerEntity() { + void shouldHandleEntityEventWithNonPlayerEntity() { // given EntityEvent event = mock(EntityEvent.class); given(event.getEntity()).willReturn(mock(Entity.class)); @@ -77,7 +76,7 @@ public void shouldHandleEntityEventWithNonPlayerEntity() { } @Test - public void shouldAllowAuthenticatedPlayer() { + void shouldAllowAuthenticatedPlayer() { // given String playerName = "Bobby"; Player player = mockPlayerWithName(playerName); @@ -95,7 +94,7 @@ public void shouldAllowAuthenticatedPlayer() { } @Test - public void shouldDenyUnLoggedPlayer() { + void shouldDenyUnLoggedPlayer() { // given String playerName = "Tester"; Player player = mockPlayerWithName(playerName); @@ -114,7 +113,7 @@ public void shouldDenyUnLoggedPlayer() { } @Test - public void shouldAllowUnloggedPlayerForOptionalRegistration() { + void shouldAllowUnloggedPlayerForOptionalRegistration() { // given String playerName = "myPlayer1"; Player player = mockPlayerWithName(playerName); @@ -134,7 +133,7 @@ public void shouldAllowUnloggedPlayerForOptionalRegistration() { } @Test - public void shouldAllowUnrestrictedName() { + void shouldAllowUnrestrictedName() { // given String playerName = "Npc2"; Player player = mockPlayerWithName(playerName); @@ -151,7 +150,7 @@ public void shouldAllowUnrestrictedName() { } @Test - public void shouldAllowNpcPlayer() { + void shouldAllowNpcPlayer() { // given String playerName = "other_npc"; Player player = mockPlayerWithName(playerName); @@ -169,7 +168,7 @@ public void shouldAllowNpcPlayer() { @Test // This simply forwards to shouldCancelEvent(Player), so the rest is already tested - public void shouldHandlePlayerEvent() { + void shouldHandlePlayerEvent() { // given String playerName = "example"; Player player = mockPlayerWithName(playerName); @@ -186,7 +185,7 @@ public void shouldHandlePlayerEvent() { } @Test - public void shouldHandlePlayerEventWithNullPlayer() { + void shouldHandlePlayerEventWithNullPlayer() { // given PlayerEvent event = new TestPlayerEvent(null); @@ -199,7 +198,7 @@ public void shouldHandlePlayerEventWithNullPlayer() { @Test // The previous tests verify most of shouldCancelEvent(Player) - public void shouldVerifyBasedOnPlayer() { + void shouldVerifyBasedOnPlayer() { // given String playerName = "player"; Player player = mockPlayerWithName(playerName); @@ -223,7 +222,7 @@ private static Player mockPlayerWithName(String name) { * Test implementation of {@link PlayerEvent}. */ private static final class TestPlayerEvent extends PlayerEvent { - public TestPlayerEvent(Player player) { + TestPlayerEvent(Player player) { super(player); } @@ -233,5 +232,3 @@ public HandlerList getHandlers() { } } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java index b9068c7f36..56898c4412 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.listener; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; @@ -26,9 +22,11 @@ import org.hamcrest.TypeSafeMatcher; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.function.Executable; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetAddress; import java.net.UnknownHostException; @@ -36,13 +34,12 @@ import java.util.Collections; import java.util.List; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -52,8 +49,7 @@ * Test for {@link OnJoinVerifier}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class OnJoinVerifierTest { +class OnJoinVerifierTest { @InjectMocks private OnJoinVerifier onJoinVerifier; @@ -76,12 +72,12 @@ public class OnJoinVerifierTest { private Server server; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldNotDoAnythingForNormalEvent() { + void shouldNotDoAnythingForNormalEvent() { // given PlayerLoginEvent event = mock(PlayerLoginEvent.class); given(event.getResult()).willReturn(PlayerLoginEvent.Result.ALLOWED); @@ -92,13 +88,12 @@ public void shouldNotDoAnythingForNormalEvent() { // then assertThat(result, equalTo(false)); verify(event).getResult(); - verify(event, atLeast(0)).getPlayer(); verifyNoMoreInteractions(event); verifyNoInteractions(bukkitService, dataSource, permissionsManager); } @Test - public void shouldRefuseNonVipPlayerForFullServer() { + void shouldRefuseNonVipPlayerForFullServer() { // given Player player = mock(Player.class); PlayerLoginEvent event = new PlayerLoginEvent(player, "hostname", null); @@ -119,7 +114,7 @@ public void shouldRefuseNonVipPlayerForFullServer() { } @Test - public void shouldKickNonVipForJoiningVipPlayer() { + void shouldKickNonVipForJoiningVipPlayer() { // given Player player = mock(Player.class); PlayerLoginEvent event = new PlayerLoginEvent(player, "hostname", null); @@ -145,7 +140,7 @@ public void shouldKickNonVipForJoiningVipPlayer() { } @Test - public void shouldKickVipPlayerIfNoPlayerCanBeKicked() { + void shouldKickVipPlayerIfNoPlayerCanBeKicked() { // given Player player = mock(Player.class); PlayerLoginEvent event = new PlayerLoginEvent(player, "hostname", null); @@ -169,7 +164,7 @@ public void shouldKickVipPlayerIfNoPlayerCanBeKicked() { } @Test - public void shouldReturnKickMessageForNonVipPlayerOnFullServer() { + void shouldReturnKickMessageForNonVipPlayerOnFullServer() { // given given(permissionsManager.hasPermissionOffline("RegularPlayer", PlayerStatePermission.IS_VIP)).willReturn(false); given(messages.retrieveSingle("RegularPlayer", MessageKey.KICK_FULL_SERVER)).willReturn("server is full"); @@ -183,21 +178,23 @@ public void shouldReturnKickMessageForNonVipPlayerOnFullServer() { } @Test - public void shouldKickNonRegistered() throws FailedVerificationException { + void shouldKickNonRegistered() { // given given(settings.getProperty(RestrictionSettings.KICK_NON_REGISTERED)).willReturn(true); - assertValidationException(() -> onJoinVerifier.checkKickNonRegistered(false), MessageKey.MUST_REGISTER_MESSAGE); + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkKickNonRegistered(false), + MessageKey.MUST_REGISTER_MESSAGE); } @Test - public void shouldNotKickRegisteredPlayer() throws FailedVerificationException { + void shouldNotKickRegisteredPlayer() throws FailedVerificationException { // given / when / then onJoinVerifier.checkKickNonRegistered(true); } @Test - public void shouldNotKickUnregisteredPlayer() throws FailedVerificationException { + void shouldNotKickUnregisteredPlayer() throws FailedVerificationException { // given given(settings.getProperty(RestrictionSettings.KICK_NON_REGISTERED)).willReturn(false); @@ -206,7 +203,7 @@ public void shouldNotKickUnregisteredPlayer() throws FailedVerificationException } @Test - public void shouldAllowValidName() throws FailedVerificationException { + void shouldAllowValidName() throws FailedVerificationException { // given given(settings.getProperty(RestrictionSettings.MIN_NICKNAME_LENGTH)).willReturn(4); given(settings.getProperty(RestrictionSettings.MAX_NICKNAME_LENGTH)).willReturn(8); @@ -218,41 +215,45 @@ public void shouldAllowValidName() throws FailedVerificationException { } @Test - public void shouldRejectTooLongName() throws FailedVerificationException { + void shouldRejectTooLongName() { // given given(settings.getProperty(RestrictionSettings.MAX_NICKNAME_LENGTH)).willReturn(8); given(settings.getProperty(RestrictionSettings.ALLOWED_NICKNAME_CHARACTERS)).willReturn("[a-zA-Z0-9]+"); onJoinVerifier.reload(); // @PostConstruct method - assertValidationException(() -> onJoinVerifier.checkIsValidName("longerthaneight"), + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkIsValidName("longerthaneight"), MessageKey.INVALID_NAME_LENGTH); } @Test - public void shouldRejectTooShortName() throws FailedVerificationException { + void shouldRejectTooShortName() { // given given(settings.getProperty(RestrictionSettings.MIN_NICKNAME_LENGTH)).willReturn(4); given(settings.getProperty(RestrictionSettings.MAX_NICKNAME_LENGTH)).willReturn(8); given(settings.getProperty(RestrictionSettings.ALLOWED_NICKNAME_CHARACTERS)).willReturn("[a-zA-Z0-9]+"); onJoinVerifier.reload(); // @PostConstruct method - assertValidationException(() -> onJoinVerifier.checkIsValidName("abc"), MessageKey.INVALID_NAME_LENGTH); + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkIsValidName("abc"), + MessageKey.INVALID_NAME_LENGTH); } @Test - public void shouldRejectNameWithInvalidCharacters() throws FailedVerificationException { + void shouldRejectNameWithInvalidCharacters() { // given given(settings.getProperty(RestrictionSettings.MIN_NICKNAME_LENGTH)).willReturn(4); given(settings.getProperty(RestrictionSettings.MAX_NICKNAME_LENGTH)).willReturn(8); given(settings.getProperty(RestrictionSettings.ALLOWED_NICKNAME_CHARACTERS)).willReturn("[a-zA-Z0-9]+"); onJoinVerifier.reload(); // @PostConstruct method - assertValidationException(() -> onJoinVerifier.checkIsValidName("Tester!"), + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkIsValidName("Tester!"), MessageKey.INVALID_NAME_CHARACTERS, "[a-zA-Z0-9]+"); } @Test - public void shouldAllowProperlyCasedName() throws FailedVerificationException { + void shouldAllowProperlyCasedName() throws FailedVerificationException { // given String name = "Bobby"; PlayerAuth auth = PlayerAuth.builder().name("bobby").realName("Bobby").build(); @@ -266,18 +267,21 @@ public void shouldAllowProperlyCasedName() throws FailedVerificationException { } @Test - public void shouldRejectNameWithWrongCasing() throws FailedVerificationException { + void shouldRejectNameWithWrongCasing() { // given String name = "Tester"; PlayerAuth auth = PlayerAuth.builder().name("tester").realName("testeR").build(); given(settings.getProperty(RegistrationSettings.PREVENT_OTHER_CASE)).willReturn(true); - assertValidationException(() -> onJoinVerifier.checkNameCasing(name, auth), + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkNameCasing(name, auth), MessageKey.INVALID_NAME_CASE, "testeR", "Tester"); + + verifyNoInteractions(dataSource); } @Test - public void shouldUpdateMissingRealName() throws FailedVerificationException { + void shouldUpdateMissingRealName() throws FailedVerificationException { // given String name = "Authme"; PlayerAuth auth = PlayerAuth.builder().name("authme").realName("").build(); @@ -291,7 +295,7 @@ public void shouldUpdateMissingRealName() throws FailedVerificationException { } @Test - public void shouldUpdateDefaultRealName() throws FailedVerificationException { + void shouldUpdateDefaultRealName() throws FailedVerificationException { // given String name = "SOMEONE"; PlayerAuth auth = PlayerAuth.builder().name("someone").realName("Player").build(); @@ -305,7 +309,7 @@ public void shouldUpdateDefaultRealName() throws FailedVerificationException { } @Test - public void shouldAcceptCasingMismatchForDisabledSetting() throws FailedVerificationException { + void shouldAcceptCasingMismatchForDisabledSetting() throws FailedVerificationException { // given String name = "Test"; PlayerAuth auth = PlayerAuth.builder().name("test").realName("TEST").build(); @@ -319,7 +323,7 @@ public void shouldAcceptCasingMismatchForDisabledSetting() throws FailedVerifica } @Test - public void shouldAcceptNameForUnregisteredAccount() throws FailedVerificationException { + void shouldAcceptNameForUnregisteredAccount() throws FailedVerificationException { // given String name = "MyPlayer"; PlayerAuth auth = null; @@ -332,7 +336,7 @@ public void shouldAcceptNameForUnregisteredAccount() throws FailedVerificationEx } @Test - public void shouldAcceptNameThatIsNotOnline() throws FailedVerificationException { + void shouldAcceptNameThatIsNotOnline() throws FailedVerificationException { // given String name = "bobby"; given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); @@ -346,7 +350,7 @@ public void shouldAcceptNameThatIsNotOnline() throws FailedVerificationException } @Test - public void shouldRejectNameAlreadyOnline() throws FailedVerificationException { + void shouldRejectNameAlreadyOnline() { // given String name = "Charlie"; @@ -355,12 +359,13 @@ public void shouldRejectNameAlreadyOnline() throws FailedVerificationException { given(bukkitService.getPlayerExact("Charlie")).willReturn(onlinePlayer); given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); - assertValidationException(() -> onJoinVerifier.checkSingleSession(name), + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkSingleSession(name), MessageKey.USERNAME_ALREADY_ONLINE_ERROR); } @Test - public void shouldAcceptAlreadyOnlineNameForDisabledSetting() throws FailedVerificationException { + void shouldAcceptAlreadyOnlineNameForDisabledSetting() throws FailedVerificationException { // given String name = "Felipe"; given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(false); @@ -373,7 +378,7 @@ public void shouldAcceptAlreadyOnlineNameForDisabledSetting() throws FailedVerif } @Test - public void shouldAllowUser() throws FailedVerificationException { + void shouldAllowUser() throws FailedVerificationException { // given String name = "Bobby"; boolean isAuthAvailable = false; @@ -389,7 +394,7 @@ public void shouldAllowUser() throws FailedVerificationException { } @Test - public void shouldAllowUserWithAuth() throws FailedVerificationException { + void shouldAllowUserWithAuth() throws FailedVerificationException { // given String name = "Lacey"; boolean isAuthAvailable = true; @@ -402,7 +407,7 @@ public void shouldAllowUserWithAuth() throws FailedVerificationException { } @Test - public void shouldAllowUserWithBypassPermission() throws FailedVerificationException { + void shouldAllowUserWithBypassPermission() throws FailedVerificationException { // given String name = "Steward"; boolean isAuthAvailable = false; @@ -417,7 +422,7 @@ public void shouldAllowUserWithBypassPermission() throws FailedVerificationExcep } @Test - public void shouldKickUserForFailedAntibotCheck() { + void shouldKickUserForFailedAntibotCheck() { // given String name = "D3"; boolean isAuthAvailable = false; @@ -439,7 +444,7 @@ public void shouldKickUserForFailedAntibotCheck() { * Tests various scenarios in which the country check should not take place. */ @Test - public void shouldNotCheckCountry() throws FailedVerificationException { + void shouldNotCheckCountry() throws FailedVerificationException { // given String name = "david"; String ip = "127.0.0.1"; @@ -456,7 +461,7 @@ public void shouldNotCheckCountry() throws FailedVerificationException { } @Test - public void shouldCheckAndAcceptUnregisteredPlayerCountry() throws FailedVerificationException { + void shouldCheckAndAcceptUnregisteredPlayerCountry() throws FailedVerificationException { // given String ip = "192.168.0.1"; String name = "lucas"; @@ -471,7 +476,7 @@ public void shouldCheckAndAcceptUnregisteredPlayerCountry() throws FailedVerific } @Test - public void shouldCheckAndAcceptRegisteredPlayerCountry() throws FailedVerificationException { + void shouldCheckAndAcceptRegisteredPlayerCountry() throws FailedVerificationException { // given String ip = "192.168.10.24"; String name = "gabriel"; @@ -487,19 +492,20 @@ public void shouldCheckAndAcceptRegisteredPlayerCountry() throws FailedVerificat } @Test - public void shouldThrowForBannedCountry() throws FailedVerificationException { + void shouldThrowForBannedCountry() { // given String ip = "192.168.40.0"; String name = "bob"; given(settings.getProperty(ProtectionSettings.ENABLE_PROTECTION)).willReturn(true); given(validationService.isCountryAdmitted(ip)).willReturn(false); - assertValidationException(() -> onJoinVerifier.checkPlayerCountry(name, ip, false), + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkPlayerCountry(name, ip, false), MessageKey.COUNTRY_BANNED_ERROR); } @Test - public void shouldAllowPlayerWithMatchingNameRestriction() throws FailedVerificationException { + void shouldAllowPlayerWithMatchingNameRestriction() throws FailedVerificationException { // given String name = "Bobby"; InetAddress address = createInetAddress("127.0.0.4"); @@ -514,19 +520,20 @@ public void shouldAllowPlayerWithMatchingNameRestriction() throws FailedVerifica } @Test - public void shouldKickPlayerWithUnmatchedNameRestriction() throws FailedVerificationException { + void shouldKickPlayerWithUnmatchedNameRestriction() { // given String name = "Bobby"; InetAddress address = createInetAddress("99.99.99.99"); given(validationService.fulfillsNameRestrictions(name, address)).willReturn(false); given(settings.getProperty(RestrictionSettings.BAN_UNKNOWN_IP)).willReturn(false); - assertValidationException(() -> onJoinVerifier.checkNameRestrictions(name, address), + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkNameRestrictions(name, address), MessageKey.NOT_OWNER_ERROR); } @Test - public void shouldBanIpWhenNameRestrictionFailsAndBanIsEnabled() { + void shouldBanIpWhenNameRestrictionFailsAndBanIsEnabled() { // given String name = "Bobby"; InetAddress address = createInetAddress("99.99.99.99"); @@ -553,7 +560,7 @@ private static InetAddress createInetAddress(String ip) { } } - private void assertValidationException(Executable executable, MessageKey messageKey, String... args) { + private void expectValidationExceptionWith(Executable executable, MessageKey messageKey, String... args) { FailedVerificationException exception = assertThrows(FailedVerificationException.class, executable); assertThat(exception, exceptionWithData(messageKey, args)); } @@ -575,5 +582,3 @@ public void describeTo(Description description) { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java index 8f766f0b6a..4b8441ee47 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java @@ -1,10 +1,5 @@ package fr.xephi.authme.listener; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.data.QuickCommandsProtectionManager; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.limbo.LimboService; @@ -13,10 +8,10 @@ import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; -import fr.xephi.authme.process.Management; import fr.xephi.authme.platform.ChatAdapter; import fr.xephi.authme.platform.PlatformAdapter; import fr.xephi.authme.platform.TeleportAdapter; +import fr.xephi.authme.process.Management; import fr.xephi.authme.service.AntiBotService; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.JoinMessageService; @@ -36,6 +31,7 @@ import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityAirChangeEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; @@ -54,16 +50,18 @@ import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerShearEntityEvent; import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.bukkit.inventory.InventoryView; -import org.spigotmc.event.player.PlayerSpawnLocationEvent; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.spigotmc.event.player.PlayerSpawnLocationEvent; import java.lang.reflect.Field; import java.net.InetAddress; @@ -105,8 +103,7 @@ * Test for {@link PlayerListener}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PlayerListenerTest { +class PlayerListenerTest { @InjectMocks private PlayerListener listener; @@ -149,7 +146,7 @@ public class PlayerListenerTest { private PlatformAdapter platformAdapter; @AfterEach - public void resetSpawnLocationTracker() throws ReflectiveOperationException { + void resetSpawnLocationTracker() throws ReflectiveOperationException { Field eventCalledField = SpawnLocationTracker.class.getDeclaredField("eventCalled"); eventCalledField.setAccessible(true); eventCalledField.setBoolean(null, false); @@ -160,7 +157,7 @@ public void resetSpawnLocationTracker() throws ReflectiveOperationException { * should be CANCELED when single session is enabled. */ @Test - public void shouldCancelKick() { + void shouldCancelKick() { // given given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); given(chatAdapter.getKickReason(any())).willAnswer(inv -> inv.getArgument(0, PlayerKickEvent.class).getReason()); @@ -176,7 +173,7 @@ public void shouldCancelKick() { } @Test - public void shouldNotCancelKick() { + void shouldNotCancelKick() { // given given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(false); String name = "Bobby"; @@ -194,7 +191,7 @@ public void shouldNotCancelKick() { } @Test - public void shouldNotCancelOrdinaryKick() { + void shouldNotCancelOrdinaryKick() { // given given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); given(chatAdapter.getKickReason(any())).willAnswer(inv -> inv.getArgument(0, PlayerKickEvent.class).getReason()); @@ -213,7 +210,7 @@ public void shouldNotCancelOrdinaryKick() { } @Test - public void shouldHandleSimpleCancelableEvents() { + void shouldHandleSimpleCancelableEvents() { withServiceMock(listenerService) .check(listener::onPlayerShear, PlayerShearEntityEvent.class) .check(listener::onPlayerFish, PlayerFishEvent.class) @@ -229,7 +226,7 @@ public void shouldHandleSimpleCancelableEvents() { } @Test - public void shouldCancelPickupItemForUnauthenticatedPlayer() { + void shouldCancelPickupItemForUnauthenticatedPlayer() { // given Player player = mock(Player.class); EntityPickupItemEvent event = mock(EntityPickupItemEvent.class); @@ -244,7 +241,7 @@ public void shouldCancelPickupItemForUnauthenticatedPlayer() { } @Test - public void shouldAllowPickupItemForAuthenticatedPlayer() { + void shouldAllowPickupItemForAuthenticatedPlayer() { // given Player player = mock(Player.class); EntityPickupItemEvent event = mock(EntityPickupItemEvent.class); @@ -259,7 +256,7 @@ public void shouldAllowPickupItemForAuthenticatedPlayer() { } @Test - public void shouldIgnorePickupItemForNonPlayer() { + void shouldIgnorePickupItemForNonPlayer() { // given EntityPickupItemEvent event = mock(EntityPickupItemEvent.class); given(event.getEntity()).willReturn(mock(org.bukkit.entity.LivingEntity.class)); @@ -273,7 +270,7 @@ public void shouldIgnorePickupItemForNonPlayer() { } @Test - public void shouldAllowEssentialsMotd() { + void shouldAllowEssentialsMotd() { // given given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(true); PlayerCommandPreprocessEvent event = mockCommandEvent("/MOTD"); @@ -287,7 +284,7 @@ public void shouldAllowEssentialsMotd() { } @Test - public void shouldNotStopAllowedCommand() { + void shouldNotStopAllowedCommand() { // given given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(true); given(settings.getProperty(RestrictionSettings.ALLOW_COMMANDS)).willReturn(newHashSet("/plugins", "/mail", "/msg")); @@ -302,7 +299,7 @@ public void shouldNotStopAllowedCommand() { } @Test - public void shouldNotCancelEventForAuthenticatedPlayer() { + void shouldNotCancelEventForAuthenticatedPlayer() { // given given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(false); given(settings.getProperty(RestrictionSettings.ALLOW_COMMANDS)).willReturn(Collections.emptySet()); @@ -324,7 +321,7 @@ public void shouldNotCancelEventForAuthenticatedPlayer() { } @Test - public void shouldCancelCommandEvent() { + void shouldCancelCommandEvent() { // given given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(false); given(settings.getProperty(RestrictionSettings.ALLOW_COMMANDS)).willReturn(newHashSet("/spawn", "/help")); @@ -343,7 +340,7 @@ public void shouldCancelCommandEvent() { } @Test - public void shouldCancelFastCommandEvent() { + void shouldCancelFastCommandEvent() { // given given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(false); given(settings.getProperty(RestrictionSettings.ALLOW_COMMANDS)).willReturn(newHashSet("/spawn", "/help")); @@ -360,7 +357,7 @@ public void shouldCancelFastCommandEvent() { } @Test - public void shouldAllowChat() { + void shouldAllowChat() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(true); AsyncPlayerChatEvent event = mock(AsyncPlayerChatEvent.class); @@ -373,7 +370,7 @@ public void shouldAllowChat() { } @Test - public void shouldCancelChatForUnauthedPlayer() { + void shouldCancelChatForUnauthedPlayer() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -391,7 +388,7 @@ public void shouldCancelChatForUnauthedPlayer() { } @Test - public void shouldSendChatToEveryone() { + void shouldSendChatToEveryone() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -409,7 +406,7 @@ public void shouldSendChatToEveryone() { } @Test - public void shouldHideChatFromUnauthed() { + void shouldHideChatFromUnauthed() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -430,7 +427,7 @@ public void shouldHideChatFromUnauthed() { } @Test - public void shouldCancelChatEventForNoRemainingRecipients() { + void shouldCancelChatEventForNoRemainingRecipients() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -450,7 +447,7 @@ public void shouldCancelChatEventForNoRemainingRecipients() { } @Test - public void shouldAllowChatForBypassPermission() { + void shouldAllowChatForBypassPermission() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -469,7 +466,7 @@ public void shouldAllowChatForBypassPermission() { } @Test - public void shouldAllowUnlimitedMovement() { + void shouldAllowUnlimitedMovement() { // given given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(true); given(settings.getProperty(RestrictionSettings.ALLOWED_MOVEMENT_RADIUS)).willReturn(0); @@ -485,7 +482,7 @@ public void shouldAllowUnlimitedMovement() { } @Test - public void shouldAllowFalling() { + void shouldAllowFalling() { // given given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); Player player = mock(Player.class); @@ -501,7 +498,7 @@ public void shouldAllowFalling() { } @Test - public void shouldAllowMovementForAuthedPlayer() { + void shouldAllowMovementForAuthedPlayer() { // given given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); Player player = mock(Player.class); @@ -519,7 +516,7 @@ public void shouldAllowMovementForAuthedPlayer() { } @Test - public void shouldCancelEventForDisabledUnauthedMovement() { + void shouldCancelEventForDisabledUnauthedMovement() { // given given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); Player player = mock(Player.class); @@ -538,7 +535,7 @@ public void shouldCancelEventForDisabledUnauthedMovement() { } @Test - public void shouldTeleportPlayerInDifferentWorldToSpawn() { + void shouldTeleportPlayerInDifferentWorldToSpawn() { // given given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(true); given(settings.getProperty(RestrictionSettings.ALLOWED_MOVEMENT_RADIUS)).willReturn(20); @@ -565,7 +562,7 @@ public void shouldTeleportPlayerInDifferentWorldToSpawn() { } @Test - public void shouldAllowMovementWithinRadius() { + void shouldAllowMovementWithinRadius() { // given given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(true); given(settings.getProperty(RestrictionSettings.ALLOWED_MOVEMENT_RADIUS)).willReturn(12); @@ -593,7 +590,7 @@ public void shouldAllowMovementWithinRadius() { } @Test - public void shouldRejectMovementOutsideOfRadius() { + void shouldRejectMovementOutsideOfRadius() { // given given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(true); given(settings.getProperty(RestrictionSettings.ALLOWED_MOVEMENT_RADIUS)).willReturn(12); @@ -621,7 +618,7 @@ public void shouldRejectMovementOutsideOfRadius() { } @Test - public void shouldIgnorePlayerRespawnForAuthenticatedPlayer() { + void shouldIgnorePlayerRespawnWithNoTeleport() { // given Player player = mock(Player.class); Location respawnLocation = mock(Location.class); @@ -637,7 +634,7 @@ public void shouldIgnorePlayerRespawnForAuthenticatedPlayer() { } @Test - public void shouldSkipTeleportOnRespawnWithNoTeleportButStillScheduleRestrictions() { + void shouldSkipTeleportOnRespawnWithNoTeleportButStillScheduleRestrictions() { // given Player player = mock(Player.class); Location respawnLocation = mock(Location.class); @@ -655,7 +652,7 @@ public void shouldSkipTeleportOnRespawnWithNoTeleportButStillScheduleRestriction } @Test - public void shouldIgnorePlayerRespawn() { + void shouldIgnorePlayerRespawn() { // given Player player = mock(Player.class); Location respawnLocation = mock(Location.class); @@ -671,7 +668,7 @@ public void shouldIgnorePlayerRespawn() { } @Test - public void shouldHandlePlayerRespawn() { + void shouldHandlePlayerRespawn() { // given Player player = mock(Player.class); Location originalLocation = mock(Location.class); @@ -693,7 +690,7 @@ public void shouldHandlePlayerRespawn() { } @Test - public void shouldIgnorePlayerRespawnUnloadedWorld() { + void shouldIgnorePlayerRespawnUnloadedWorld() { // given Player player = mock(Player.class); Location originalLocation = mock(Location.class); @@ -714,7 +711,7 @@ public void shouldIgnorePlayerRespawnUnloadedWorld() { } @Test - public void shouldHandlePlayerRespawnNoChanges() { + void shouldHandlePlayerRespawnNoChanges() { // given Player player = mock(Player.class); Location originalLocation = mock(Location.class); @@ -733,7 +730,7 @@ public void shouldHandlePlayerRespawnNoChanges() { } @Test - public void shouldHandlePlayerJoining() { + void shouldHandlePlayerJoining() { // given Player player = mock(Player.class); PlayerJoinEvent event = new PlayerJoinEvent(player, "join message"); @@ -747,7 +744,7 @@ public void shouldHandlePlayerJoining() { } @Test - public void shouldSetCustomSpawnLocationForLegacySpawnEvent() { + void shouldSetCustomSpawnLocationForLegacySpawnEvent() { // given Player player = mock(Player.class); Location originalSpawn = mock(Location.class); @@ -765,7 +762,7 @@ public void shouldSetCustomSpawnLocationForLegacySpawnEvent() { } @Test - public void shouldIgnoreLegacySpawnEventWhenPlatformUsesModernEvent() { + void shouldIgnoreLegacySpawnEventWhenPlatformUsesModernEvent() { // given PlayerSpawnLocationEvent event = spy(new PlayerSpawnLocationEvent(mock(Player.class), mock(Location.class))); given(platformAdapter.shouldHandlePlayerSpawnLocationEvent()).willReturn(false); @@ -779,7 +776,7 @@ public void shouldIgnoreLegacySpawnEventWhenPlatformUsesModernEvent() { } @Test - public void shouldNotInterfereWithUnrestrictedUser() throws FailedVerificationException { + void shouldNotInterfereWithUnrestrictedUser() throws FailedVerificationException { // given String name = "Player01"; Player player = mockPlayerWithName(name); @@ -798,7 +795,7 @@ public void shouldNotInterfereWithUnrestrictedUser() throws FailedVerificationEx } @Test - public void shouldStopHandlingForFullServer() throws FailedVerificationException { + void shouldStopHandlingForFullServer() throws FailedVerificationException { // given String name = "someone"; Player player = mockPlayerWithName(name); @@ -819,7 +816,7 @@ public void shouldStopHandlingForFullServer() throws FailedVerificationException } @Test - public void shouldStopHandlingEventForBadResult() throws FailedVerificationException { + void shouldStopHandlingEventForBadResult() throws FailedVerificationException { // given String name = "someone"; Player player = mockPlayerWithName(name); @@ -841,7 +838,7 @@ public void shouldStopHandlingEventForBadResult() throws FailedVerificationExcep } @Test - public void shouldIgnoreLegacyLoginEventWhenPlatformUsesModernEvents() { + void shouldIgnoreLegacyLoginEventWhenPlatformUsesModernEvents() { // given PlayerLoginEvent event = spy(new PlayerLoginEvent(mock(Player.class), "", null)); given(platformAdapter.shouldHandlePlayerLoginEvent()).willReturn(false); @@ -855,7 +852,7 @@ public void shouldIgnoreLegacyLoginEventWhenPlatformUsesModernEvents() { } @Test - public void shouldPerformAllJoinVerificationsSuccessfullyPreLoginLowest() throws FailedVerificationException { + void shouldPerformAllJoinVerificationsSuccessfullyPreLoginLowest() throws FailedVerificationException { // given String name = "someone"; UUID uniqueId = UUID.fromString("753493c9-33ba-4a4a-bf61-1bce9d3c9a71"); @@ -875,7 +872,7 @@ public void shouldPerformAllJoinVerificationsSuccessfullyPreLoginLowest() throws } @Test - public void shouldKickPreLoginLowestUnresolvedHostname() { + void shouldKickPreLoginLowestUnresolvedHostname() { // given String name = "someone"; UUID uniqueId = UUID.fromString("753493c9-33ba-4a4a-bf61-1bce9d3c9a71"); @@ -893,7 +890,7 @@ public void shouldKickPreLoginLowestUnresolvedHostname() { } @Test - public void shouldPerformAllJoinVerificationsSuccessfullyPreLoginHighest() throws FailedVerificationException { + void shouldPerformAllJoinVerificationsSuccessfullyPreLoginHighest() throws FailedVerificationException { // given String name = "someone"; UUID uniqueId = UUID.fromString("753493c9-33ba-4a4a-bf61-1bce9d3c9a71"); @@ -918,7 +915,7 @@ public void shouldPerformAllJoinVerificationsSuccessfullyPreLoginHighest() throw } @Test - public void shouldAbortPreLoginHighestForFailedNameRestriction() throws FailedVerificationException { + void shouldAbortPreLoginHighestForFailedNameRestriction() throws FailedVerificationException { // given String name = "restrictedPlayer"; UUID uniqueId = UUID.fromString("c60b7305-3a78-4f71-8a60-70a3f17e1c90"); @@ -942,7 +939,7 @@ public void shouldAbortPreLoginHighestForFailedNameRestriction() throws FailedVe } @Test - public void shouldPerformAllJoinVerificationsSuccessfullyLogin() { + void shouldPerformAllJoinVerificationsSuccessfullyLogin() { // given String name = "someone"; Player player = mockPlayerWithName(name); @@ -964,7 +961,7 @@ public void shouldPerformAllJoinVerificationsSuccessfullyLogin() { } @Test - public void shouldAbortPlayerJoinForInvalidName() throws FailedVerificationException { + void shouldAbortPlayerJoinForInvalidName() throws FailedVerificationException { // given String name = "inval!dName"; UUID uniqueId = UUID.fromString("753493c9-33ba-4a4a-bf61-1bce9d3c9a71"); @@ -990,7 +987,7 @@ public void shouldAbortPlayerJoinForInvalidName() throws FailedVerificationExcep } @Test - public void shouldRemoveMessageOnQuit() { + void shouldRemoveMessageOnQuit() { // given given(settings.getProperty(RegistrationSettings.REMOVE_LEAVE_MESSAGE)).willReturn(true); given(antiBotService.wasPlayerKicked(anyString())).willReturn(false); @@ -1008,7 +1005,7 @@ public void shouldRemoveMessageOnQuit() { } @Test - public void shouldRemoveMessageForUnloggedUser() { + void shouldRemoveMessageForUnloggedUser() { // given given(settings.getProperty(RegistrationSettings.REMOVE_LEAVE_MESSAGE)).willReturn(false); given(settings.getProperty(RegistrationSettings.REMOVE_UNLOGGED_LEAVE_MESSAGE)).willReturn(true); @@ -1028,7 +1025,7 @@ public void shouldRemoveMessageForUnloggedUser() { } @Test - public void shouldProcessPlayerAndKeepQuitMessage() { + void shouldProcessPlayerAndKeepQuitMessage() { // given String name = "Louis"; Player player = mockPlayerWithName(name); @@ -1050,7 +1047,7 @@ public void shouldProcessPlayerAndKeepQuitMessage() { @Test @SuppressWarnings("unchecked") - public void shouldSaveEnderPearlRestoreDataOnQuit() { + void shouldSaveEnderPearlRestoreDataOnQuit() { // given String name = "Pearlie"; Player player = mockPlayerWithName(name); @@ -1091,7 +1088,7 @@ public void shouldSaveEnderPearlRestoreDataOnQuit() { } @Test - public void shouldCancelInventoryClickEvent() { + void shouldCancelInventoryClickEvent() { // given InventoryClickEvent event = mock(InventoryClickEvent.class); HumanEntity player = mock(Player.class); @@ -1106,7 +1103,7 @@ public void shouldCancelInventoryClickEvent() { } @Test - public void shouldAllowInventoryClickEvent() { + void shouldAllowInventoryClickEvent() { // given InventoryClickEvent event = mock(InventoryClickEvent.class); HumanEntity player = mock(Player.class); @@ -1121,7 +1118,7 @@ public void shouldAllowInventoryClickEvent() { } @Test - public void shouldAllowSignChangeEvent() { + void shouldAllowSignChangeEvent() { // given SignChangeEvent event = mock(SignChangeEvent.class); Player player = mock(Player.class); @@ -1136,7 +1133,7 @@ public void shouldAllowSignChangeEvent() { } @Test - public void shouldCancelSignChangeEvent() { + void shouldCancelSignChangeEvent() { // given SignChangeEvent event = mock(SignChangeEvent.class); Player player = mock(Player.class); @@ -1151,7 +1148,7 @@ public void shouldCancelSignChangeEvent() { } @Test - public void shouldAllowInventoryOpen() { + void shouldAllowInventoryOpen() { // given HumanEntity player = mock(Player.class); InventoryView transaction = mock(InventoryView.class); @@ -1168,7 +1165,7 @@ public void shouldAllowInventoryOpen() { } @Test - public void shouldCancelInventoryOpen() { + void shouldCancelInventoryOpen() { // given HumanEntity player = mock(Player.class); InventoryView transaction = mock(InventoryView.class); @@ -1188,7 +1185,7 @@ public void shouldCancelInventoryOpen() { } @Test - public void shouldNotModifyJoinMessage() { + void shouldNotModifyJoinMessage() { // given Player player = mock(Player.class); String joinMsg = "The player joined"; @@ -1206,7 +1203,7 @@ public void shouldNotModifyJoinMessage() { } @Test - public void shouldRemoveJoinMessage() { + void shouldRemoveJoinMessage() { // given Player player = mock(Player.class); String joinMsg = "The player joined"; @@ -1222,7 +1219,7 @@ public void shouldRemoveJoinMessage() { } @Test - public void shouldUseCustomMessage() { + void shouldUseCustomMessage() { // given Player player = mock(Player.class); given(player.getName()).willReturn("doooew"); @@ -1243,7 +1240,7 @@ public void shouldUseCustomMessage() { } @Test - public void shouldDelayJoinMessage() { + void shouldDelayJoinMessage() { // given Player player = mock(Player.class); given(player.getName()).willReturn("thename0"); @@ -1264,13 +1261,13 @@ public void shouldDelayJoinMessage() { } @Test - public void shouldCancelPlayerEditBookEvent() { + void shouldCancelPlayerEditBookEvent() { withServiceMock(listenerService) .check(listener::onPlayerEditBook, PlayerEditBookEvent.class); } @Test - public void shouldCancelPlayerInteractAtEntityEvent() { + void shouldCancelPlayerInteractAtEntityEvent() { withServiceMock(listenerService) .check(listener::onPlayerInteractAtEntity, PlayerInteractAtEntityEvent.class); } @@ -1287,10 +1284,9 @@ private static Player mockPlayerWithName(String name) { * * @return Player mock */ - @SuppressWarnings("unchecked") private static Player playerWithMockedServer() { Server server = mock(Server.class); - given(server.getOnlinePlayers()).willReturn(Collections.EMPTY_LIST); + given(server.getOnlinePlayers()).willReturn(Collections.emptyList()); Player player = mock(Player.class); given(player.getServer()).willReturn(server); return player; @@ -1337,5 +1333,3 @@ public static InetAddress createInetAddress(String ip) { } } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/ServerListenerTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/ServerListenerTest.java index 57cea626a7..b5629d3853 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/ServerListenerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/ServerListenerTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.listener; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.listener.protocollib.ProtocolLibService; import fr.xephi.authme.permission.PermissionsManager; @@ -15,8 +11,10 @@ import org.bukkit.plugin.Plugin; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -29,8 +27,7 @@ * Test for {@link ServerListener}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class ServerListenerTest { +class ServerListenerTest { private static final String ESSENTIALS = "Essentials"; private static final String ESSENTIALS_SPAWN = "EssentialsSpawn"; @@ -54,12 +51,12 @@ public class ServerListenerTest { private SpawnLoader spawnLoader; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldForwardPluginNameOnEnable() { + void shouldForwardPluginNameOnEnable() { checkEnableHandling(ESSENTIALS, () -> verify(pluginHookService).tryHookToEssentials()); checkEnableHandling(ESSENTIALS_SPAWN, () -> verify(spawnLoader).loadEssentialsSpawn()); checkEnableHandling(CMI, () -> { @@ -72,7 +69,7 @@ public void shouldForwardPluginNameOnEnable() { } @Test - public void shouldForwardPluginNameOnDisable() { + void shouldForwardPluginNameOnDisable() { checkDisableHandling(ESSENTIALS, () -> verify(pluginHookService).unhookEssentials()); checkDisableHandling(ESSENTIALS_SPAWN, () -> verify(spawnLoader).unloadEssentialsSpawn()); checkDisableHandling(CMI, () -> { @@ -113,5 +110,3 @@ private static T mockEventWithPluginName(Class event return event; } } - - From df11ad9c183a9b2677801b2568b5e77794363629 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Thu, 23 Apr 2026 10:28:23 +0200 Subject: [PATCH 4/5] JUnit cleanup for packages mail, message --- .../test/java/fr/xephi/authme/TestHelper.java | 18 +++++ .../xephi/authme/mail/EmailServiceTest.java | 75 +++++++++---------- .../fr/xephi/authme/mail/SendMailSslTest.java | 56 +++++++------- .../message/HelpMessageConsistencyTest.java | 9 +-- .../message/MessageFilePlaceholderTest.java | 8 +- .../xephi/authme/message/MessageKeyTest.java | 9 +-- .../authme/message/MessagePathHelperTest.java | 15 ++-- .../message/MessagesFileConsistencyTest.java | 5 +- .../message/MessagesIntegrationTest.java | 60 +++++++-------- .../message/YamlTextFileCheckerTest.java | 9 +-- .../message/updater/MessageUpdaterTest.java | 39 +++++----- .../updater/MigraterYamlFileResourceTest.java | 18 ++--- .../updater/OldMessageKeysMigraterTest.java | 5 +- 13 files changed, 167 insertions(+), 159 deletions(-) diff --git a/authme-core/src/test/java/fr/xephi/authme/TestHelper.java b/authme-core/src/test/java/fr/xephi/authme/TestHelper.java index 11fd5ab35c..6c797fda12 100644 --- a/authme-core/src/test/java/fr/xephi/authme/TestHelper.java +++ b/authme-core/src/test/java/fr/xephi/authme/TestHelper.java @@ -6,6 +6,7 @@ import org.mockito.Mockito; import java.io.File; +import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; @@ -119,4 +120,21 @@ public static void returnDefaultsForAllProperties(Settings settings) { given(settings.getProperty(any(Property.class))) .willAnswer(invocation -> ((Property) invocation.getArgument(0)).getDefaultValue()); } + + /** + * Creates a file with the given name in the provided folder. Throws an exception if the file + * could not be created. + * + * @param folder the folder to create the file in + * @param filename the name of the file to create + * @return the created file + */ + public static File createFile(File folder, String filename) throws IOException { + File file = new File(folder, filename); + boolean created = file.createNewFile(); + if (!created) { + throw new IllegalStateException("Could not create file '" + filename + "' in " + folder); + } + return file; + } } diff --git a/authme-core/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java index 5535899e13..7a426a2ba3 100644 --- a/authme-core/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java @@ -1,11 +1,6 @@ package fr.xephi.authme.mail; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.PluginSettings; @@ -13,17 +8,18 @@ import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; -import java.io.IOException; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -37,49 +33,46 @@ /** * Test for {@link EmailService}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class EmailServiceTest { +@ExtendWith(MockitoExtension.class) +class EmailServiceTest { - @InjectDelayed private EmailService emailService; @Mock private Settings settings; @Mock private SendMailSsl sendMailSsl; - @Captor - private ArgumentCaptor messageCaptor; - @DataFolder - private File dataFolder; - public TempFolder temporaryFolder = new TempFolder(); + @TempDir + File dataFolder; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void initFields() throws IOException { - dataFolder = temporaryFolder.newFolder(); - given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); - given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("mail@example.org"); - given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); - given(sendMailSsl.hasAllInformation()).willReturn(true); + @BeforeEach + void initFieldsAndService() { + emailService = new EmailService(dataFolder, settings, sendMailSsl); } @Test - public void shouldHaveAllInformation() { - // given / when / then + void shouldHaveAllInformation() { + // given + given(sendMailSsl.hasAllInformation()).willReturn(true); + + // when / then assertThat(emailService.hasAllInformation(), equalTo(true)); } @Test - public void shouldSendPasswordMail() throws EmailException { + void shouldSendPasswordMail() throws EmailException { // given given(settings.getPasswordEmailMessage()) .willReturn("Hi , your new password for is "); given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); HtmlEmail email = mock(HtmlEmail.class); + given(sendMailSsl.hasAllInformation()).willReturn(true); given(sendMailSsl.initializeMail(anyString())).willReturn(email); given(sendMailSsl.sendEmail(anyString(), eq(email))).willReturn(true); @@ -89,14 +82,16 @@ public void shouldSendPasswordMail() throws EmailException { // then assertThat(result, equalTo(true)); verify(sendMailSsl).initializeMail("user@example.com"); + ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); assertThat(messageCaptor.getValue(), equalTo("Hi Player, your new password for serverName is new_password")); } @Test - public void shouldHandleMailCreationError() throws EmailException { + void shouldHandleMailCreationError() throws EmailException { // given + given(sendMailSsl.hasAllInformation()).willReturn(true); doThrow(EmailException.class).when(sendMailSsl).initializeMail(anyString()); // when @@ -109,10 +104,12 @@ public void shouldHandleMailCreationError() throws EmailException { } @Test - public void shouldHandleMailSendingFailure() throws EmailException { + void shouldHandleMailSendingFailure() throws EmailException { // given + given(sendMailSsl.hasAllInformation()).willReturn(true); given(settings.getPasswordEmailMessage()).willReturn("Hi , your new pass is "); given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); HtmlEmail email = mock(HtmlEmail.class); given(sendMailSsl.initializeMail(anyString())).willReturn(email); given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(false); @@ -123,14 +120,16 @@ public void shouldHandleMailSendingFailure() throws EmailException { // then assertThat(result, equalTo(false)); verify(sendMailSsl).initializeMail("user@example.com"); + ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); assertThat(messageCaptor.getValue(), equalTo("Hi bobby, your new pass is myPassw0rd")); } @Test - public void shouldSendRecoveryCode() throws EmailException { + void shouldSendRecoveryCode() throws EmailException { // given given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(7); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); given(settings.getRecoveryCodeEmailMessage()) .willReturn("Hi , your code on is (valid hours)"); HtmlEmail email = mock(HtmlEmail.class); @@ -143,12 +142,13 @@ public void shouldSendRecoveryCode() throws EmailException { // then assertThat(result, equalTo(true)); verify(sendMailSsl).initializeMail("tim@example.com"); + ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); assertThat(messageCaptor.getValue(), equalTo("Hi Timmy, your code on serverName is 12C56A (valid 7 hours)")); } @Test - public void shouldHandleMailCreationErrorForRecoveryCode() throws EmailException { + void shouldHandleMailCreationErrorForRecoveryCode() throws EmailException { // given given(sendMailSsl.initializeMail(anyString())).willThrow(EmailException.class); @@ -162,10 +162,11 @@ public void shouldHandleMailCreationErrorForRecoveryCode() throws EmailException } @Test - public void shouldHandleFailureToSendRecoveryCode() throws EmailException { + void shouldHandleFailureToSendRecoveryCode() throws EmailException { // given given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(7); - given(settings.getRecoveryCodeEmailMessage()).willReturn("Hi , your code is "); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("Server? I barely know her!"); + given(settings.getRecoveryCodeEmailMessage()).willReturn("Hi , your code is for "); EmailService sendMailSpy = spy(emailService); HtmlEmail email = mock(HtmlEmail.class); given(sendMailSsl.initializeMail(anyString())).willReturn(email); @@ -177,10 +178,8 @@ public void shouldHandleFailureToSendRecoveryCode() throws EmailException { // then assertThat(result, equalTo(false)); verify(sendMailSsl).initializeMail("user@example.com"); + ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); - assertThat(messageCaptor.getValue(), equalTo("Hi John, your code is 1DEF77")); + assertThat(messageCaptor.getValue(), equalTo("Hi John, your code is 1DEF77 for Server? I barely know her!")); } - } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java b/authme-core/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java index e7d4f0120d..8958830f2d 100644 --- a/authme-core/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.mail; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.settings.Settings; @@ -13,61 +9,61 @@ import org.apache.commons.mail.HtmlEmail; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -import java.io.IOException; import java.util.Properties; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; /** * Test for {@link SendMailSsl}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class SendMailSslTest { +@ExtendWith(MockitoExtension.class) +class SendMailSslTest { - @InjectDelayed + @InjectMocks private SendMailSsl sendMailSsl; @Mock private Settings settings; - public TempFolder temporaryFolder = new TempFolder(); @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void initFields() throws IOException { + @Test + void shouldHaveAllInformation() { + // given given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("mail@example.org"); given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); - given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); - given(settings.getProperty(EmailSettings.SSL_CHECK_SERVER_IDENTITY)).willReturn(true); - } - @Test - public void shouldHaveAllInformation() { - // given / when / then + // when / then assertThat(sendMailSsl.hasAllInformation(), equalTo(true)); } @Test - public void shouldCreateEmailObject() throws EmailException { + void shouldCreateEmailObject() throws EmailException { // given given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(465); String smtpHost = "mail.example.com"; given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost); String senderAccount = "sender@example.org"; given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderAccount); + given(settings.getProperty(EmailSettings.MAIL_ADDRESS)).willReturn(""); + given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); String senderName = "Server administration"; given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn(senderName); + given(settings.getProperty(EmailSettings.RECOVERY_MAIL_SUBJECT)).willReturn("Recover password"); + given(settings.getProperty(EmailSettings.SSL_CHECK_SERVER_IDENTITY)).willReturn(true); given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.DEBUG); // when @@ -84,17 +80,21 @@ public void shouldCreateEmailObject() throws EmailException { } @Test - public void shouldCreateEmailObjectWithAddress() throws EmailException { + void shouldCreateEmailObjectWithAddress() throws EmailException { // given given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(465); String smtpHost = "mail.example.com"; given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost); - String senderAccount = "exampleAccount"; + String senderAccount = "actualsender@example.com"; given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderAccount); String senderAddress = "mail@example.com"; given(settings.getProperty(EmailSettings.MAIL_ADDRESS)).willReturn(senderAddress); + given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); String senderName = "Server administration"; given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn(senderName); + given(settings.getProperty(EmailSettings.RECOVERY_MAIL_SUBJECT)).willReturn("Recover password"); + given(settings.getProperty(EmailSettings.SSL_CHECK_SERVER_IDENTITY)).willReturn(true); + given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); // when HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); @@ -110,7 +110,7 @@ public void shouldCreateEmailObjectWithAddress() throws EmailException { } @Test - public void shouldCreateEmailObjectWithOAuth2() throws EmailException { + void shouldCreateEmailObjectWithOAuth2() throws EmailException { // given given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(587); given(settings.getProperty(EmailSettings.OAUTH2_TOKEN)).willReturn("oAuth2 token"); @@ -118,6 +118,12 @@ public void shouldCreateEmailObjectWithOAuth2() throws EmailException { given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost); String senderMail = "sender@example.org"; given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderMail); + given(settings.getProperty(EmailSettings.MAIL_ADDRESS)).willReturn(""); + given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); + given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn("Admin"); + given(settings.getProperty(EmailSettings.RECOVERY_MAIL_SUBJECT)).willReturn("Ricóber chur pasword ése"); + given(settings.getProperty(EmailSettings.SSL_CHECK_SERVER_IDENTITY)).willReturn(true); + given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); // when HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); @@ -138,5 +144,3 @@ public void shouldCreateEmailObjectWithOAuth2() throws EmailException { assertThat(mailProperties.getProperty(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP), equalTo("oAuth2 token")); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java index 0ca214ee4b..682934f953 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java @@ -16,22 +16,22 @@ import java.util.stream.Collectors; import static fr.xephi.authme.message.MessagePathHelper.MESSAGES_FOLDER; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.emptyString; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * Tests that all help_xx.yml files contain all entries for * {@link HelpSection}, {@link HelpMessage} and {@link DefaultPermission}. */ -public class HelpMessageConsistencyTest { +class HelpMessageConsistencyTest { private List helpFiles; @BeforeEach - public void findHelpMessagesFiles() { + void findHelpMessagesFiles() { File folder = TestHelper.getJarFile("/" + MESSAGES_FOLDER); File[] files = folder.listFiles(); if (files == null || files.length == 0) { @@ -43,7 +43,7 @@ public void findHelpMessagesFiles() { } @Test - public void shouldHaveRequiredEntries() { + void shouldHaveRequiredEntries() { for (File file : helpFiles) { // given PropertyReader reader = new YamlFileReader(file); @@ -88,4 +88,3 @@ private static Matcher notEmptyString() { return both(not(emptyString())).and(not(nullValue())); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java b/authme-core/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java index a4b64addd5..90ed548e35 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java @@ -24,7 +24,7 @@ * Checks that the entries in messages_xx.yml files have the {@link MessageKey#getTags() placeholders} * that are defined for the given message. */ -public class MessageFilePlaceholderTest { +class MessageFilePlaceholderTest { /** Defines exclusions: a (key, tag) pair in this map will not be checked in the test. */ private static final Multimap EXCLUSIONS = ImmutableMultimap.builder() @@ -32,9 +32,10 @@ public class MessageFilePlaceholderTest { .putAll(MessageKey.MAX_REGISTER_EXCEEDED, "%max_acc", "%reg_count", "%reg_names") .build(); + // Note ljacqu 20170506: We pass the file name separately so we can use it as the test name @ParameterizedTest(name = "{1}") @MethodSource("buildParams") - public void shouldHaveAllPlaceholders(File messagesFile, String messagesFilename) { + void shouldHaveAllPlaceholders(File messagesFile, String messagesFilename) { // given PropertyReader reader = new YamlFileReader(messagesFile); List errors = new ArrayList<>(0); @@ -63,7 +64,7 @@ private List findMissingTags(MessageKey key, PropertyReader reader) { return Collections.emptyList(); } - public static Stream buildParams() { + static Stream buildParams() { File folder = TestHelper.getJarFile("/" + MESSAGES_FOLDER); File[] files = folder.listFiles(); @@ -81,4 +82,3 @@ public static Stream buildParams() { return messageFiles.stream(); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/MessageKeyTest.java b/authme-core/src/test/java/fr/xephi/authme/message/MessageKeyTest.java index c93bb58ebc..a30b153892 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/MessageKeyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/MessageKeyTest.java @@ -7,17 +7,17 @@ import java.util.HashSet; import java.util.Set; -import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.matchesPattern; import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link MessageKey}. */ -public class MessageKeyTest { +class MessageKeyTest { @Test - public void shouldHaveUniqueMessageKeys() { + void shouldHaveUniqueMessageKeys() { // given MessageKey[] messageKeys = MessageKey.values(); Set keys = new HashSet<>(); @@ -34,7 +34,7 @@ public void shouldHaveUniqueMessageKeys() { } @Test - public void shouldHaveWellFormedPlaceholders() { + void shouldHaveWellFormedPlaceholders() { // given MessageKey[] messageKeys = MessageKey.values(); @@ -47,4 +47,3 @@ public void shouldHaveWellFormedPlaceholders() { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java b/authme-core/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java index 77d3fbc4ca..76b7742ff2 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java @@ -3,31 +3,31 @@ import fr.xephi.authme.settings.properties.PluginSettings; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link MessagePathHelper}. */ -public class MessagePathHelperTest { +class MessagePathHelperTest { @Test - public void shouldHaveLanguageInSyncWithConfigurations() { + void shouldHaveLanguageInSyncWithConfigurations() { // given / when / then assertThat(MessagePathHelper.DEFAULT_LANGUAGE, equalTo(PluginSettings.MESSAGES_LANGUAGE.getDefaultValue())); assertThat(MessagePathHelper.DEFAULT_MESSAGES_FILE, equalTo(MessagePathHelper.createMessageFilePath(MessagePathHelper.DEFAULT_LANGUAGE))); } @Test - public void shouldBuildTextFilePaths() { + void shouldBuildTextFilePaths() { // given / when / then assertThat(MessagePathHelper.createMessageFilePath("qq"), equalTo(MessagePathHelper.MESSAGES_FOLDER + "messages_qq.yml")); assertThat(MessagePathHelper.createHelpMessageFilePath("qq"), equalTo(MessagePathHelper.MESSAGES_FOLDER + "help_qq.yml")); } @Test - public void shouldRecognizeIfIsMessagesFile() { + void shouldRecognizeIfIsMessagesFile() { // given / when / then assertThat(MessagePathHelper.isMessagesFile("messages_nl.yml"), equalTo(true)); assertThat(MessagePathHelper.isMessagesFile("messages_testtest.yml"), equalTo(true)); @@ -40,7 +40,7 @@ public void shouldRecognizeIfIsMessagesFile() { } @Test - public void shouldReturnLanguageForMessagesFile() { + void shouldReturnLanguageForMessagesFile() { // given / when / then assertThat(MessagePathHelper.getLanguageIfIsMessagesFile("messages_nl.yml"), equalTo("nl")); assertThat(MessagePathHelper.getLanguageIfIsMessagesFile("messages_testtest.yml"), equalTo("testtest")); @@ -53,7 +53,7 @@ public void shouldReturnLanguageForMessagesFile() { } @Test - public void shouldRecognizeIfIsHelpFile() { + void shouldRecognizeIfIsHelpFile() { // given / when / then assertThat(MessagePathHelper.isHelpFile("help_nl.yml"), equalTo(true)); assertThat(MessagePathHelper.isHelpFile("help_testtest.yml"), equalTo(true)); @@ -65,4 +65,3 @@ public void shouldRecognizeIfIsHelpFile() { assertThat(MessagePathHelper.isHelpFile(""), equalTo(false)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java index d93e892c6c..ee0ae647d6 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java @@ -17,12 +17,12 @@ *

* Translators can change the file name in {@link #MESSAGES_FILE} to validate their translation. */ -public class MessagesFileConsistencyTest { +class MessagesFileConsistencyTest { private static final String MESSAGES_FILE = MessagePathHelper.DEFAULT_MESSAGES_FILE; @Test - public void shouldHaveAllMessages() { + void shouldHaveAllMessages() { File file = TestHelper.getJarFile("/" + MESSAGES_FILE); PropertyReader reader = new YamlFileReader(file); List errors = new ArrayList<>(); @@ -59,4 +59,3 @@ private static void validateMessage(MessageKey messageKey, PropertyReader reader } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java index a1eec10967..8151416264 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java @@ -12,16 +12,13 @@ import fr.xephi.authme.util.expiring.Duration; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -29,11 +26,11 @@ import java.util.concurrent.TimeUnit; import java.util.logging.Logger; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -45,21 +42,18 @@ /** * Test for {@link Messages}. */ -@ExtendWith(MockitoExtension.class) -public class MessagesIntegrationTest { +class MessagesIntegrationTest { private static final String TEST_MESSAGES_LOCAL_PATH = "message/messages_test.yml"; private static final String YML_TEST_FILE = TestHelper.PROJECT_ROOT + TEST_MESSAGES_LOCAL_PATH; private Messages messages; private MessagesFileHandler messagesFileHandler; - @Captor - private ArgumentCaptor captor; - public TempFolder temporaryFolder = new TempFolder(); - private File dataFolder; + @TempDir + File dataFolder; @BeforeAll - public static void setup() { + static void setup() { TestHelper.setupLogger(); } @@ -72,8 +66,7 @@ public static void setup() { * file that should contain all messages, but again, for testing, it just contains a few. */ @BeforeEach - public void setUpMessages() throws IOException { - dataFolder = temporaryFolder.newFolder(); + void setUpMessages() throws IOException { File testFile = new File(dataFolder, MessagePathHelper.createMessageFilePath("test")); new File(dataFolder, MessagePathHelper.MESSAGES_FOLDER).mkdirs(); FileUtils.create(testFile); @@ -83,13 +76,13 @@ public void setUpMessages() throws IOException { messages = new Messages(messagesFileHandler); } - @AfterAll - public static void removeLoggerReferences() { + @AfterEach + void removeLoggerReferences() { ConsoleLogger.initialize(null, null); } @Test - public void shouldLoadMessageAndSplitAtNewLines() { + void shouldLoadMessageAndSplitAtNewLines() { // given MessageKey key = MessageKey.UNKNOWN_USER; CommandSender sender = mock(CommandSender.class); @@ -104,7 +97,7 @@ public void shouldLoadMessageAndSplitAtNewLines() { } @Test - public void shouldLoadMessageAsStringWithNewLines() { + void shouldLoadMessageAsStringWithNewLines() { // given MessageKey key = MessageKey.UNKNOWN_USER; CommandSender sender = mock(CommandSender.class); @@ -118,7 +111,7 @@ public void shouldLoadMessageAsStringWithNewLines() { } @Test - public void shouldFormatColorCodes() { + void shouldFormatColorCodes() { // given MessageKey key = MessageKey.LOGIN_SUCCESS; CommandSender sender = mock(CommandSender.class); @@ -133,7 +126,7 @@ public void shouldFormatColorCodes() { } @Test - public void shouldNotSendEmptyMessage() { + void shouldNotSendEmptyMessage() { // given MessageKey key = MessageKey.EMAIL_ALREADY_USED_ERROR; CommandSender sender = mock(CommandSender.class); @@ -147,7 +140,7 @@ public void shouldNotSendEmptyMessage() { } @Test - public void shouldSendMessageToPlayer() { + void shouldSendMessageToPlayer() { // given MessageKey key = MessageKey.LOGIN_SUCCESS; Player player = Mockito.mock(Player.class); @@ -162,7 +155,7 @@ public void shouldSendMessageToPlayer() { } @Test - public void shouldSendMultiLineMessageToPlayer() { + void shouldSendMultiLineMessageToPlayer() { // given MessageKey key = MessageKey.UNKNOWN_USER; Player player = Mockito.mock(Player.class); @@ -174,12 +167,13 @@ public void shouldSendMultiLineMessageToPlayer() { // then String[] lines = new String[]{"We've got", "new lines", "and ' apostrophes"}; + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(player, times(3)).sendMessage(captor.capture()); assertThat(captor.getAllValues(), contains(lines)); } @Test - public void shouldSendMessageToPlayerWithNameReplacement() { + void shouldSendMessageToPlayerWithNameReplacement() { // given MessageKey key = MessageKey.REGISTER_MESSAGE; Player player = Mockito.mock(Player.class); @@ -194,7 +188,7 @@ public void shouldSendMessageToPlayerWithNameReplacement() { } @Test - public void shouldSendMessageToPlayerWithTagReplacement() { + void shouldSendMessageToPlayerWithTagReplacement() { // given MessageKey key = MessageKey.CAPTCHA_WRONG_ERROR; CommandSender sender = Mockito.mock(CommandSender.class); @@ -208,7 +202,7 @@ public void shouldSendMessageToPlayerWithTagReplacement() { } @Test - public void shouldNotLogErrorForKeyWithNoTagReplacements() { + void shouldNotLogErrorForKeyWithNoTagReplacements() { // given MessageKey key = MessageKey.CAPTCHA_WRONG_ERROR; CommandSender sender = mock(CommandSender.class); @@ -222,7 +216,7 @@ public void shouldNotLogErrorForKeyWithNoTagReplacements() { } @Test - public void shouldLogErrorForInvalidReplacementCount() { + void shouldLogErrorForInvalidReplacementCount() { // given Logger logger = mock(Logger.class); ConsoleLogger.initialize(logger, null); @@ -238,7 +232,7 @@ public void shouldLogErrorForInvalidReplacementCount() { } @Test - public void shouldSendErrorForReplacementsOnKeyWithNoTags() { + void shouldSendErrorForReplacementsOnKeyWithNoTags() { // given Logger logger = mock(Logger.class); ConsoleLogger.initialize(logger, null); @@ -254,7 +248,7 @@ public void shouldSendErrorForReplacementsOnKeyWithNoTags() { } @Test - public void shouldNotUseMessageFromDefaultFile() { + void shouldNotUseMessageFromDefaultFile() { // given // Key is present in both files MessageKey key = MessageKey.WRONG_PASSWORD; @@ -269,7 +263,7 @@ public void shouldNotUseMessageFromDefaultFile() { } @Test - public void shouldRetrieveMessageWithReplacements() { + void shouldRetrieveMessageWithReplacements() { // given MessageKey key = MessageKey.CAPTCHA_WRONG_ERROR; CommandSender sender = mock(CommandSender.class); @@ -283,7 +277,7 @@ public void shouldRetrieveMessageWithReplacements() { } @Test - public void shouldFormatDurationObjects() throws IOException { + void shouldFormatDurationObjects() throws IOException { // given // Use the JAR's messages_en.yml file for this, so copy to the file we're using and reload the file handler File testFile = new File(dataFolder, MessagePathHelper.createMessageFilePath("test")); @@ -319,5 +313,3 @@ private MessagesFileHandler createMessagesFileHandler() { return messagesFileHandler; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java b/authme-core/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java index 8711abc258..0399e8e14c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java @@ -20,13 +20,13 @@ /** * Tests that all YML text files can be loaded. */ -public class YamlTextFileCheckerTest { +class YamlTextFileCheckerTest { /** Contains all files of the MESSAGES_FOLDER. */ private static File[] messageFiles; @BeforeAll - public static void loadMessagesFiles() { + static void loadMessagesFiles() { File folder = TestHelper.getJarFile("/" + MESSAGES_FOLDER); messageFiles = folder.listFiles(); if (messageFiles == null) { @@ -35,14 +35,14 @@ public static void loadMessagesFiles() { } @Test - public void testAllMessagesYmlFiles() { + void testAllMessagesYmlFiles() { checkFiles( MessagePathHelper::isMessagesFile, MessageKey.LOGIN_MESSAGE.getKey()); } @Test - public void testAllHelpYmlFiles() { + void testAllHelpYmlFiles() { checkFiles( MessagePathHelper::isHelpFile, HelpSection.ALTERNATIVES.getKey()); @@ -91,4 +91,3 @@ private void checkFile(File file, String mandatoryKey, List errors) { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java b/authme-core/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java index cde030411a..e6793bae73 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java @@ -8,7 +8,7 @@ import fr.xephi.authme.message.MessageKey; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -18,28 +18,31 @@ import java.util.Set; import java.util.stream.Collectors; +import static fr.xephi.authme.TestHelper.createFile; import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_MESSAGES_FILE; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link MessageUpdater}. */ -public class MessageUpdaterTest { +class MessageUpdaterTest { private MessageUpdater messageUpdater = new MessageUpdater(); - public TempFolder temporaryFolder = new TempFolder(); + + @TempDir + File temporaryFolder; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldNotUpdateDefaultFile() throws IOException { + void shouldNotUpdateDefaultFile() throws IOException { // given String messagesFilePath = DEFAULT_MESSAGES_FILE; - File messagesFile = temporaryFolder.newFile(); + File messagesFile = createFile(temporaryFolder, "fffff"); Files.copy(TestHelper.getJarFile("/" + messagesFilePath), messagesFile); long modifiedDate = messagesFile.lastModified(); @@ -50,13 +53,13 @@ public void shouldNotUpdateDefaultFile() throws IOException { assertThat(wasChanged, equalTo(false)); assertThat(messagesFile.lastModified(), equalTo(modifiedDate)); } - + @Test - public void shouldAddMissingKeys() throws IOException { + void shouldAddMissingKeys() throws IOException { // given - File messagesFile = temporaryFolder.newFile(); + File messagesFile = createFile(temporaryFolder, "file"); Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/messages_test.yml"), messagesFile); - + // when boolean wasChanged = messageUpdater.migrateAndSave(messagesFile, "does-not-exist", DEFAULT_MESSAGES_FILE); @@ -72,9 +75,9 @@ public void shouldAddMissingKeys() throws IOException { } @Test - public void shouldMigrateOldEntries() throws IOException { + void shouldMigrateOldEntries() throws IOException { // given - File messagesFile = temporaryFolder.newFile(); + File messagesFile = createFile(temporaryFolder, "messages.yml"); Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/messages_en_old.yml"), messagesFile); // when @@ -98,9 +101,9 @@ public void shouldMigrateOldEntries() throws IOException { } @Test - public void shouldPerformNewerMigrations() throws IOException { + void shouldPerformNewerMigrations() throws IOException { // given - File messagesFile = temporaryFolder.newFile(); + File messagesFile = createFile(temporaryFolder, "newFile"); Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/messages_test2.yml"), messagesFile); // when @@ -115,7 +118,7 @@ public void shouldPerformNewerMigrations() throws IOException { } @Test - public void shouldHaveAllKeysInConfigurationData() { + void shouldHaveAllKeysInConfigurationData() { // given Set messageKeysFromEnum = Arrays.stream(MessageKey.values()) .map(MessageKey::getKey) @@ -131,7 +134,7 @@ public void shouldHaveAllKeysInConfigurationData() { } @Test - public void shouldHaveCommentForAllRootPathsInConfigurationData() { + void shouldHaveCommentForAllRootPathsInConfigurationData() { // given Set rootPaths = Arrays.stream(MessageKey.values()) .map(key -> key.getKey().split("\\.")[0]) @@ -144,5 +147,3 @@ public void shouldHaveCommentForAllRootPathsInConfigurationData() { assertThat(comments.keySet(), equalTo(rootPaths)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/updater/MigraterYamlFileResourceTest.java b/authme-core/src/test/java/fr/xephi/authme/message/updater/MigraterYamlFileResourceTest.java index c2970449ef..60fcfec8ef 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/updater/MigraterYamlFileResourceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/updater/MigraterYamlFileResourceTest.java @@ -8,26 +8,28 @@ import com.google.common.io.Files; import fr.xephi.authme.TestHelper; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link MigraterYamlFileResource}. */ -public class MigraterYamlFileResourceTest { +class MigraterYamlFileResourceTest { private static final String CHINESE_MESSAGES_FILE = TestHelper.PROJECT_ROOT + "message/chinese_texts.yml"; - public TempFolder temporaryFolder = new TempFolder(); + + @TempDir + File temporaryFolder; @Test - public void shouldReadChineseFile() { + void shouldReadChineseFile() { // given File file = TestHelper.getJarFile(CHINESE_MESSAGES_FILE); MigraterYamlFileResource resource = new MigraterYamlFileResource(file); @@ -42,9 +44,9 @@ public void shouldReadChineseFile() { } @Test - public void shouldWriteWithCorrectCharset() throws IOException { + void shouldWriteWithCorrectCharset() throws IOException { // given - File file = temporaryFolder.newFile(); + File file = TestHelper.createFile(temporaryFolder, "messages"); Files.copy(TestHelper.getJarFile(CHINESE_MESSAGES_FILE), file); MigraterYamlFileResource resource = new MigraterYamlFileResource(file); ConfigurationData configurationData = buildConfigurationData(); @@ -70,5 +72,3 @@ private static ConfigurationData buildConfigurationData() { return ConfigurationDataBuilder.createConfiguration(properties); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/message/updater/OldMessageKeysMigraterTest.java b/authme-core/src/test/java/fr/xephi/authme/message/updater/OldMessageKeysMigraterTest.java index e803d7bd18..70101d699f 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/updater/OldMessageKeysMigraterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/updater/OldMessageKeysMigraterTest.java @@ -14,10 +14,10 @@ /** * Test for {@link OldMessageKeysMigrater}. */ -public class OldMessageKeysMigraterTest { +class OldMessageKeysMigraterTest { @Test - public void shouldHasOldKeysThatAreNewParentsFirstInMap() { + void shouldHasOldKeysThatAreNewParentsFirstInMap() { // given Set parentPaths = collectParentPathsFromMessageKeys(); Set encounteredParents = new HashSet<>(); @@ -39,4 +39,3 @@ private Set collectParentPathsFromMessageKeys() { .collect(Collectors.toSet()); } } - From 7e86f328a975957bf0cee8f42f51f6d6faf861eb Mon Sep 17 00:00:00 2001 From: ljacqu Date: Thu, 23 Apr 2026 10:41:41 +0200 Subject: [PATCH 5/5] Revert accidental method rename, remove unnecessary comment --- .../test/java/fr/xephi/authme/listener/PlayerListenerTest.java | 2 +- .../fr/xephi/authme/message/MessageFilePlaceholderTest.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java index 4b8441ee47..f48abb84e3 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java @@ -618,7 +618,7 @@ void shouldRejectMovementOutsideOfRadius() { } @Test - void shouldIgnorePlayerRespawnWithNoTeleport() { + void shouldIgnorePlayerRespawnForAuthenticatedPlayer() { // given Player player = mock(Player.class); Location respawnLocation = mock(Location.class); diff --git a/authme-core/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java b/authme-core/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java index 90ed548e35..a41ae06a7e 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java @@ -32,7 +32,6 @@ class MessageFilePlaceholderTest { .putAll(MessageKey.MAX_REGISTER_EXCEEDED, "%max_acc", "%reg_count", "%reg_names") .build(); - // Note ljacqu 20170506: We pass the file name separately so we can use it as the test name @ParameterizedTest(name = "{1}") @MethodSource("buildParams") void shouldHaveAllPlaceholders(File messagesFile, String messagesFilename) {