diff --git a/pom.xml b/pom.xml index a3f870e801..74bcc2f5ba 100644 --- a/pom.xml +++ b/pom.xml @@ -212,7 +212,7 @@ org.jacoco jacoco-maven-plugin - 0.8.8 + 0.8.11 pre-unit-test @@ -1010,30 +1010,36 @@ - junit - junit + org.junit.jupiter + junit-jupiter-engine test - 4.13.2 + 5.10.1 + + + org.junit.jupiter + junit-jupiter-params + test + 5.10.1 org.hamcrest - java-hamcrest + hamcrest test - 2.0.0.0 + 2.2 org.mockito mockito-core test - 4.8.1 - - - hamcrest-core - org.hamcrest - - + 4.11.0 + + + org.mockito + mockito-junit-jupiter + test + 4.11.0 diff --git a/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java b/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java index 994d967b29..02e7c9b419 100644 --- a/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java +++ b/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java @@ -24,7 +24,7 @@ public class HelpMessagesService { private final HelpMessagesFileHandler helpMessagesFileHandler; @Inject - HelpMessagesService(HelpMessagesFileHandler helpMessagesFileHandler) { + public HelpMessagesService(HelpMessagesFileHandler helpMessagesFileHandler) { this.helpMessagesFileHandler = helpMessagesFileHandler; } diff --git a/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java b/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java index 5e6fc2210d..114a582610 100644 --- a/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java @@ -12,7 +12,6 @@ import org.bukkit.configuration.file.YamlConfiguration; import javax.annotation.PostConstruct; -import javax.inject.Inject; import java.io.File; import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; @@ -24,18 +23,16 @@ public abstract class AbstractMessageFileHandler implements Reloadable { private final ConsoleLogger logger = ConsoleLoggerFactory.get(AbstractMessageFileHandler.class); - @DataFolder - @Inject - private File dataFolder; - - @Inject - private Settings settings; + private final File dataFolder; + private final Settings settings; private String filename; private FileConfiguration configuration; private final String defaultFile; - protected AbstractMessageFileHandler() { + protected AbstractMessageFileHandler(@DataFolder File dataFolder, Settings settings) { + this.dataFolder = dataFolder; + this.settings = settings; this.defaultFile = createFilePath(DEFAULT_LANGUAGE); } diff --git a/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java b/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java index 89dc522453..c0004ec08f 100644 --- a/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java @@ -1,12 +1,15 @@ package fr.xephi.authme.message; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.FileUtils; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import javax.inject.Inject; +import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; @@ -21,8 +24,9 @@ public class HelpMessagesFileHandler extends AbstractMessageFileHandler { private FileConfiguration defaultConfiguration; - @Inject // Trigger injection in the superclass - HelpMessagesFileHandler() { + @Inject + public HelpMessagesFileHandler(@DataFolder File dataFolder, Settings settings) { + super(dataFolder, settings); } /** diff --git a/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java b/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java index 18b7764642..f7a61ce83b 100644 --- a/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java @@ -1,10 +1,13 @@ package fr.xephi.authme.message; import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.message.updater.MessageUpdater; +import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.settings.Settings; import javax.inject.Inject; +import java.io.File; import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; @@ -15,10 +18,12 @@ public class MessagesFileHandler extends AbstractMessageFileHandler { private final ConsoleLogger logger = ConsoleLoggerFactory.get(MessagesFileHandler.class); - @Inject - private MessageUpdater messageUpdater; + private final MessageUpdater messageUpdater; - MessagesFileHandler() { + @Inject + MessagesFileHandler(@DataFolder File dataFolder, Settings settings, MessageUpdater messageUpdater) { + super(dataFolder, settings); + this.messageUpdater = messageUpdater; } @Override diff --git a/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java b/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java index e1c8c5ba76..2d1239244b 100644 --- a/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java +++ b/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java @@ -29,18 +29,19 @@ */ public class HelpTranslationGenerator { - @Inject - private CommandInitializer commandInitializer; - - @Inject - private HelpMessagesService helpMessagesService; + private final CommandInitializer commandInitializer; + private final HelpMessagesService helpMessagesService; + private final Settings settings; + private final File dataFolder; @Inject - private Settings settings; - - @DataFolder - @Inject - private File dataFolder; + HelpTranslationGenerator(CommandInitializer commandInitializer, HelpMessagesService helpMessagesService, + Settings settings, @DataFolder File dataFolder) { + this.commandInitializer = commandInitializer; + this.helpMessagesService = helpMessagesService; + this.settings = settings; + this.dataFolder = dataFolder; + } /** * Updates the help file to contain entries for all commands. diff --git a/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java b/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java index 290312bb54..f8cbe6af72 100644 --- a/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java +++ b/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java @@ -25,13 +25,12 @@ import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPluginLoader; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -39,9 +38,9 @@ import java.util.logging.Logger; import static fr.xephi.authme.settings.properties.AuthMeSettingsRetriever.buildConfigurationData; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; @@ -52,24 +51,18 @@ * Integration test verifying that all services can be initialized in {@link AuthMe} * with the {@link Injector}. */ -@RunWith(MockitoJUnitRunner.class) -public class AuthMeInitializationTest { +@ExtendWith(MockitoExtension.class) +class AuthMeInitializationTest { @Mock private Server server; - @Mock - private PluginManager pluginManager; - private AuthMe authMe; - private File dataFolder; - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File dataFolder; - @Before - public void initAuthMe() throws IOException { - dataFolder = temporaryFolder.newFolder(); + @BeforeEach + void initAuthMe() throws IOException { File settingsFile = new File(dataFolder, "config.yml"); given(server.getLogger()).willReturn(Logger.getAnonymousLogger()); JavaPluginLoader pluginLoader = new JavaPluginLoader(server); @@ -77,7 +70,6 @@ public void initAuthMe() throws IOException { // Mock / wire various Bukkit components ReflectionTestUtils.setField(Bukkit.class, null, "server", server); - given(server.getPluginManager()).willReturn(pluginManager); // PluginDescriptionFile is final: need to create a sample one PluginDescriptionFile descriptionFile = new PluginDescriptionFile( @@ -88,13 +80,15 @@ public void initAuthMe() throws IOException { } @Test - public void shouldInitializeAllServices() { + void shouldInitializeAllServices() { // given PropertyReader reader = mock(PropertyReader.class); PropertyResource resource = mock(PropertyResource.class); given(resource.createReader()).willReturn(reader); Settings settings = new Settings(dataFolder, resource, null, buildConfigurationData()); + PluginManager pluginManager = mock(PluginManager.class); + given(server.getPluginManager()).willReturn(pluginManager); TestHelper.setupLogger(); Injector injector = new InjectorBuilder() @@ -128,7 +122,7 @@ public void shouldInitializeAllServices() { } @Test - public void shouldHandlePrematureShutdownGracefully() { + void shouldHandlePrematureShutdownGracefully() { // given BukkitScheduler scheduler = mock(BukkitScheduler.class); given(server.getScheduler()).willReturn(scheduler); diff --git a/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java b/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java index f02b5dc9b2..b6452554d2 100644 --- a/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java @@ -16,7 +16,7 @@ import fr.xephi.authme.util.expiring.ExpiringMap; import fr.xephi.authme.util.expiring.ExpiringSet; import fr.xephi.authme.util.expiring.TimedCounter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.lang.reflect.Field; @@ -32,14 +32,14 @@ import java.util.Set; import java.util.stream.Collectors; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Contains consistency tests across all AuthMe classes. */ -public class ClassesConsistencyTest { +class ClassesConsistencyTest { /** Contains all production classes. */ private static final List> ALL_CLASSES = @@ -71,7 +71,7 @@ int.class, long.class, float.class, String.class, File.class, Enum.class, collec * Checks that there aren't two classes with the same name; this is confusing and should be avoided. */ @Test - public void shouldNotHaveSameName() { + void shouldNotHaveSameName() { // given Set names = new HashSet<>(); @@ -87,7 +87,7 @@ public void shouldNotHaveSameName() { * Checks that fields of classes are either private or static final fields of an immutable type. */ @Test - public void shouldHaveNonPrivateConstantsOnly() { + void shouldHaveNonPrivateConstantsOnly() { // given / when Set invalidFields = ALL_CLASSES.stream() .filter(clz -> !CLASSES_EXCLUDED_FROM_VISIBILITY_TEST.contains(clz)) @@ -145,7 +145,7 @@ private static String formatField(Field field) { * interface to regularly clean up expired data. */ @Test - public void shouldImplementHasCleanup() { + void shouldImplementHasCleanup() { // given / when / then for (Class clazz : ALL_CLASSES) { if (hasExpiringCollectionAsField(clazz) && !EXPIRING_STRUCTURES.contains(clazz)) { diff --git a/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java b/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java index e645922e7b..1e814536dc 100644 --- a/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java +++ b/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java @@ -2,26 +2,26 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Consistency test for the CodeClimate configuration file. */ -public class CodeClimateConfigTest { +class CodeClimateConfigTest { private static final String CONFIG_FILE = ".codeclimate.yml"; @Test - public void shouldHaveExistingClassesInExclusions() { + void shouldHaveExistingClassesInExclusions() { // given / when FileConfiguration configuration = YamlConfiguration.loadConfiguration(new File(CONFIG_FILE)); List excludePaths = configuration.getStringList("exclude_patterns"); diff --git a/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java b/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java index 3f334e471f..986266d631 100644 --- a/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java +++ b/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java @@ -4,15 +4,14 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.SecuritySettings; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.FileWriter; @@ -22,13 +21,13 @@ import java.util.List; import java.util.logging.Logger; +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.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; @@ -40,23 +39,22 @@ /** * Test for {@link ConsoleLogger}. */ -@RunWith(MockitoJUnitRunner.class) -public class ConsoleLoggerTest { +@ExtendWith(MockitoExtension.class) +class ConsoleLoggerTest { private ConsoleLogger consoleLogger; @Mock private Logger logger; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempFolder; private File logFile; - @Before - public void setMockLogger() throws IOException { - File folder = temporaryFolder.newFolder(); - File logFile = new File(folder, "authme.log"); + @BeforeEach + void setMockLogger() throws IOException { + File logFile = new File(tempFolder, "authme.log"); if (!logFile.createNewFile()) { throw new IOException("Could not create file '" + logFile.getPath() + "'"); } @@ -65,8 +63,8 @@ public void setMockLogger() throws IOException { this.consoleLogger = new ConsoleLogger("test"); } - @After - public void closeFileHandlers() { + @AfterEach + void closeFileHandlers() { ConsoleLogger.closeFileWriter(); } @@ -75,13 +73,13 @@ public void closeFileHandlers() { * is that we no longer enable logging to a file as the log file we've supplied will no longer * be around after this test class has finished. */ - @AfterClass - public static void resetConsoleToDefault() { + @AfterAll + static void resetConsoleToDefault() { ConsoleLogger.initializeSharedSettings(newSettings(false, LogLevel.INFO)); } @Test - public void shouldLogToFile() throws IOException { + void shouldLogToFile() throws IOException { // given Settings settings = newSettings(true, LogLevel.FINE); ConsoleLogger.initializeSharedSettings(settings); @@ -102,7 +100,7 @@ public void shouldLogToFile() throws IOException { } @Test - public void shouldNotLogToFile() { + void shouldNotLogToFile() { // given Settings settings = newSettings(false, LogLevel.DEBUG); ConsoleLogger.initializeSharedSettings(settings); @@ -120,9 +118,10 @@ public void shouldNotLogToFile() { } @Test - public void shouldLogStackTraceToFile() throws IOException { + void shouldLogStackTraceToFile() throws IOException { // given - Settings settings = newSettings(true, LogLevel.INFO); + Settings settings = mock(Settings.class); + given(settings.getProperty(SecuritySettings.USE_LOGGING)).willReturn(true); ConsoleLogger.initializeSharedSettings(settings); Exception e = new IllegalStateException("Test exception message"); @@ -146,7 +145,7 @@ public void shouldLogStackTraceToFile() throws IOException { } @Test - public void shouldSupportVariousDebugMethods() throws IOException { + void shouldSupportVariousDebugMethods() throws IOException { // given Settings settings = newSettings(true, LogLevel.DEBUG); ConsoleLogger.initializeSharedSettings(settings); @@ -174,7 +173,7 @@ public void shouldSupportVariousDebugMethods() throws IOException { } @Test - public void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException { + void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException { // given FileWriter fileWriter = mock(FileWriter.class); doThrow(new IOException("Error during flush")).when(fileWriter).flush(); @@ -190,7 +189,7 @@ public void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException { } @Test - public void shouldHandleExceptionOnFileWriterClose() throws IOException { + void shouldHandleExceptionOnFileWriterClose() throws IOException { // given FileWriter fileWriter = mock(FileWriter.class); doThrow(new IOException("Cannot close")).when(fileWriter).close(); diff --git a/src/test/java/fr/xephi/authme/IsEqualByReflectionMatcher.java b/src/test/java/fr/xephi/authme/IsEqualByReflectionMatcher.java index 2acf5ee708..0ce5b19ae5 100644 --- a/src/test/java/fr/xephi/authme/IsEqualByReflectionMatcher.java +++ b/src/test/java/fr/xephi/authme/IsEqualByReflectionMatcher.java @@ -10,7 +10,8 @@ import java.util.List; import java.util.Objects; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; + /** * Matcher which checks with reflection that all fields have the same value. diff --git a/src/test/java/fr/xephi/authme/TestHelper.java b/src/test/java/fr/xephi/authme/TestHelper.java index ad50c5119b..1afabe6b0c 100644 --- a/src/test/java/fr/xephi/authme/TestHelper.java +++ b/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; @@ -118,4 +119,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/src/test/java/fr/xephi/authme/api/v3/AuthMeApiTest.java b/src/test/java/fr/xephi/authme/api/v3/AuthMeApiTest.java index b52f7908b1..938b8b22bd 100644 --- a/src/test/java/fr/xephi/authme/api/v3/AuthMeApiTest.java +++ b/src/test/java/fr/xephi/authme/api/v3/AuthMeApiTest.java @@ -17,12 +17,12 @@ import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.time.Instant; import java.util.Arrays; @@ -51,8 +51,8 @@ /** * Test for {@link AuthMeApi}. */ -@RunWith(MockitoJUnitRunner.class) -public class AuthMeApiTest { +@ExtendWith(MockitoExtension.class) +class AuthMeApiTest { @InjectMocks private AuthMeApi api; @@ -73,7 +73,7 @@ public class AuthMeApiTest { private GeoIpService geoIpService; @Test - public void shouldReturnInstanceOrNull() { + void shouldReturnInstanceOrNull() { AuthMeApi result = AuthMeApi.getInstance(); assertThat(result, sameInstance(api)); @@ -82,7 +82,7 @@ public void shouldReturnInstanceOrNull() { } @Test - public void shouldReturnIfPlayerIsAuthenticated() { + void shouldReturnIfPlayerIsAuthenticated() { // given String name = "Bobby"; Player player = mockPlayerWithName(name); @@ -97,7 +97,7 @@ public void shouldReturnIfPlayerIsAuthenticated() { } @Test - public void shouldReturnIfPlayerIsNpc() { + void shouldReturnIfPlayerIsNpc() { // given Player player = mock(Player.class); given(player.hasMetadata("NPC")).willReturn(true); @@ -111,7 +111,7 @@ public void shouldReturnIfPlayerIsNpc() { } @Test - public void shouldReturnIfPlayerIsUnrestricted() { + void shouldReturnIfPlayerIsUnrestricted() { // given String name = "Tester"; Player player = mockPlayerWithName(name); @@ -126,7 +126,7 @@ public void shouldReturnIfPlayerIsUnrestricted() { } @Test - public void shouldGetLastLocation() { + void shouldGetLastLocation() { // given String name = "Gary"; Player player = mockPlayerWithName(name); @@ -158,7 +158,7 @@ public void shouldGetLastLocation() { } @Test - public void shouldGetLastIp() { + void shouldGetLastIp() { // given String name = "Gabriel"; Player player = mockPlayerWithName(name); @@ -176,7 +176,7 @@ public void shouldGetLastIp() { } @Test - public void shouldReturnNullAsLastIpForUnknownUser() { + void shouldReturnNullAsLastIpForUnknownUser() { // given String name = "Harrison"; given(playerCache.getAuth(name)).willReturn(null); @@ -192,7 +192,7 @@ public void shouldReturnNullAsLastIpForUnknownUser() { } @Test - public void shouldGetLastLogin() { + void shouldGetLastLogin() { // given String name = "David"; PlayerAuth auth = PlayerAuth.builder().name(name) @@ -209,7 +209,7 @@ public void shouldGetLastLogin() { } @Test - public void shouldHandleNullLastLogin() { + void shouldHandleNullLastLogin() { // given String name = "John"; PlayerAuth auth = PlayerAuth.builder().name(name) @@ -226,7 +226,7 @@ public void shouldHandleNullLastLogin() { } @Test - public void shouldGetLastLoginTime() { + void shouldGetLastLoginTime() { // given String name = "David"; PlayerAuth auth = PlayerAuth.builder().name(name) @@ -243,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) @@ -266,7 +269,7 @@ public void shouldHandleNullLastLoginTime() { } @Test - public void shouldReturnNullForUnavailablePlayer() { + void shouldReturnNullForUnavailablePlayer() { // given String name = "Numan"; Player player = mockPlayerWithName(name); @@ -280,7 +283,7 @@ public void shouldReturnNullForUnavailablePlayer() { } @Test - public void shouldCheckForRegisteredName() { + void shouldCheckForRegisteredName() { // given String name = "toaster"; given(dataSource.isAuthAvailable(name)).willReturn(true); @@ -293,7 +296,7 @@ public void shouldCheckForRegisteredName() { } @Test - public void shouldCheckPassword() { + void shouldCheckPassword() { // given String playerName = "Robert"; String password = "someSecretPhrase2983"; @@ -308,7 +311,7 @@ public void shouldCheckPassword() { } @Test - public void shouldReturnAuthNames() { + void shouldReturnAuthNames() { // given String[] names = {"bobby", "peter", "elisabeth", "craig"}; List auths = Arrays.stream(names) @@ -324,7 +327,7 @@ public void shouldReturnAuthNames() { } @Test - public void shouldReturnAuthRealNames() { + void shouldReturnAuthRealNames() { // given String[] names = {"Bobby", "peter", "Elisabeth", "CRAIG"}; List auths = Arrays.stream(names) @@ -340,7 +343,7 @@ public void shouldReturnAuthRealNames() { } @Test - public void shouldUnregisterPlayer() { + void shouldUnregisterPlayer() { // given Player player = mock(Player.class); String name = "Donald"; @@ -354,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); @@ -370,7 +373,7 @@ public void shouldUnregisterPlayerByName() { } @Test - public void shouldChangePassword() { + void shouldChangePassword() { // given String name = "Bobby12"; String password = "resetPw!"; @@ -383,7 +386,7 @@ public void shouldChangePassword() { } @Test - public void shouldReturnAuthMeInstance() { + void shouldReturnAuthMeInstance() { // given / when AuthMe result = api.getPlugin(); @@ -392,7 +395,7 @@ public void shouldReturnAuthMeInstance() { } @Test - public void shouldReturnVersion() { + void shouldReturnVersion() { // given / when String result = api.getPluginVersion(); @@ -401,7 +404,7 @@ public void shouldReturnVersion() { } @Test - public void shouldForceLogin() { + void shouldForceLogin() { // given Player player = mock(Player.class); @@ -413,7 +416,7 @@ public void shouldForceLogin() { } @Test - public void shouldForceLogout() { + void shouldForceLogout() { // given Player player = mock(Player.class); @@ -425,7 +428,7 @@ public void shouldForceLogout() { } @Test - public void shouldForceRegister() { + void shouldForceRegister() { // given Player player = mock(Player.class); String pass = "test235"; @@ -439,7 +442,7 @@ public void shouldForceRegister() { } @Test - public void shouldForceRegisterAndNotAutoLogin() { + void shouldForceRegisterAndNotAutoLogin() { // given Player player = mock(Player.class); String pass = "test235"; @@ -453,7 +456,7 @@ public void shouldForceRegisterAndNotAutoLogin() { } @Test - public void shouldRegisterPlayer() { + void shouldRegisterPlayer() { // given String name = "Marco"; String password = "myP4ss"; @@ -475,7 +478,7 @@ public void shouldRegisterPlayer() { } @Test - public void shouldNotRegisterAlreadyRegisteredPlayer() { + void shouldNotRegisterAlreadyRegisteredPlayer() { // given String name = "jonah"; given(dataSource.isAuthAvailable(name)).willReturn(true); @@ -490,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"); @@ -505,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"); @@ -521,7 +524,7 @@ public void shouldReturnGeoIpInfo() { } @Test - public void shouldReturnAuthMePlayerInfo() { + void shouldReturnAuthMePlayerInfo() { // given PlayerAuth auth = PlayerAuth.builder() .name("bobb") @@ -540,7 +543,7 @@ public void shouldReturnAuthMePlayerInfo() { } @Test - public void shouldReturnNullForNonExistentAuth() { + void shouldReturnNullForNonExistentAuth() { // given / when Optional result = api.getPlayerInfo("doesNotExist"); diff --git a/src/test/java/fr/xephi/authme/api/v3/AuthMePlayerImplTest.java b/src/test/java/fr/xephi/authme/api/v3/AuthMePlayerImplTest.java index aa8b50c953..a0ec516cee 100644 --- a/src/test/java/fr/xephi/authme/api/v3/AuthMePlayerImplTest.java +++ b/src/test/java/fr/xephi/authme/api/v3/AuthMePlayerImplTest.java @@ -4,7 +4,7 @@ import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Optional; @@ -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") diff --git a/src/test/java/fr/xephi/authme/command/CommandConsistencyTest.java b/src/test/java/fr/xephi/authme/command/CommandConsistencyTest.java index d2033d1bc0..4208ea368c 100644 --- a/src/test/java/fr/xephi/authme/command/CommandConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandConsistencyTest.java @@ -3,7 +3,7 @@ import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collection; @@ -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.junit.Assert.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(); diff --git a/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java b/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java index d80d8f8a56..3ac571d98c 100644 --- a/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java @@ -11,13 +11,13 @@ import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.command.CommandSender; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Mock; import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import java.util.Collections; @@ -30,8 +30,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.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; @@ -51,8 +51,8 @@ // Justification: It's more readable to use asList() everywhere in the test when we often generated two lists where one // often consists of only one element, e.g. myMethod(asList("authme"), asList("my", "args"), ...) @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") -@RunWith(MockitoJUnitRunner.class) -public class CommandHandlerTest { +@ExtendWith(MockitoExtension.class) +class CommandHandlerTest { private CommandHandler handler; @@ -69,9 +69,9 @@ public class CommandHandlerTest { private Map, ExecutableCommand> mockedCommands = new HashMap<>(); - @Before + @BeforeEach @SuppressWarnings("unchecked") - public void initializeCommandMapper() { + void initializeCommandMapper() { given(commandMapper.getCommandClasses()).willReturn(Sets.newHashSet( ExecutableCommand.class, TestLoginCommand.class, TestRegisterCommand.class, TestUnregisterCommand.class)); setInjectorToMockExecutableCommandClasses(); @@ -105,7 +105,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { @Test - public void shouldCallMappedCommandWithArgs() { + void shouldCallMappedCommandWithArgs() { // given String bukkitLabel = "Authme"; String[] bukkitArgs = {"Login", "myPass"}; @@ -128,7 +128,7 @@ public void shouldCallMappedCommandWithArgs() { } @Test - public void shouldNotCallExecutableCommandIfNoPermission() { + void shouldNotCallExecutableCommandIfNoPermission() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -147,7 +147,7 @@ public void shouldNotCallExecutableCommandIfNoPermission() { } @Test - public void shouldNotCallExecutableForWrongArguments() { + void shouldNotCallExecutableForWrongArguments() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -167,7 +167,7 @@ public void shouldNotCallExecutableForWrongArguments() { } @Test - public void shouldUseCustomMessageUponArgumentMismatch() { + void shouldUseCustomMessageUponArgumentMismatch() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -190,7 +190,7 @@ public void shouldUseCustomMessageUponArgumentMismatch() { } @Test - public void shouldNotCallExecutableForWrongArgumentsAndPermissionDenied() { + void shouldNotCallExecutableForWrongArgumentsAndPermissionDenied() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -210,7 +210,7 @@ public void shouldNotCallExecutableForWrongArgumentsAndPermissionDenied() { } @Test - public void shouldNotCallExecutableForFailedParsing() { + void shouldNotCallExecutableForFailedParsing() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -229,7 +229,7 @@ public void shouldNotCallExecutableForFailedParsing() { } @Test - public void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() { + void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -255,7 +255,7 @@ public void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() { } @Test - public void shouldNotCallExecutableForUnknownLabelAndNotSuggestCommand() { + void shouldNotCallExecutableForUnknownLabelAndNotSuggestCommand() { // given String bukkitLabel = "unreg"; String[] bukkitArgs = {"testPlayer"}; @@ -278,7 +278,7 @@ public void shouldNotCallExecutableForUnknownLabelAndNotSuggestCommand() { } @Test - public void shouldStripWhitespace() { + void shouldStripWhitespace() { // given String bukkitLabel = "AuthMe"; String[] bukkitArgs = {" ", "", "REGISTER", " ", "testArg", " "}; diff --git a/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java b/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java index 5cac2462a8..b5ffe60264 100644 --- a/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java @@ -1,8 +1,8 @@ package fr.xephi.authme.command; import fr.xephi.authme.util.StringUtils; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collection; @@ -15,15 +15,15 @@ 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.junit.Assert.assertThat; -import static org.junit.Assert.fail; +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. @@ -33,14 +33,14 @@ public class CommandInitializerTest { private static Collection commands; - @BeforeClass - public static void initializeCommandCollection() { + @BeforeAll + 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<>(); diff --git a/src/test/java/fr/xephi/authme/command/CommandMapperTest.java b/src/test/java/fr/xephi/authme/command/CommandMapperTest.java index 3a23cdc8ce..88b80cf21e 100644 --- a/src/test/java/fr/xephi/authme/command/CommandMapperTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandMapperTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.command; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -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; @@ -10,10 +7,12 @@ import fr.xephi.authme.permission.PermissionNode; import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.command.CommandSender; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.junit.Assert.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}. */ -@RunWith(DelayedInjectionRunner.class) -public class CommandMapperTest { +@ExtendWith(MockitoExtension.class) +class CommandMapperTest { private static List commands; - @InjectDelayed private CommandMapper mapper; @Mock @@ -51,21 +50,22 @@ public class CommandMapperTest { @Mock private CommandInitializer commandInitializer; - @BeforeClass - public static void setUpCommandHandler() { + @BeforeAll + 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(); diff --git a/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java b/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java index be17f6cfb6..1a2cb68564 100644 --- a/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java @@ -1,31 +1,31 @@ package fr.xephi.authme.command; import org.bukkit.ChatColor; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link CommandUtils}. */ -public class CommandUtilsTest { +class CommandUtilsTest { private static Collection commands; - @BeforeClass - public static void setUpTestCommands() { + @BeforeAll + 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"); diff --git a/src/test/java/fr/xephi/authme/command/PlayerCommandTest.java b/src/test/java/fr/xephi/authme/command/PlayerCommandTest.java index 4f0c999749..fa08be38d4 100644 --- a/src/test/java/fr/xephi/authme/command/PlayerCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/PlayerCommandTest.java @@ -3,7 +3,7 @@ import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -18,10 +18,10 @@ /** * Test for {@link PlayerCommand}. */ -public class PlayerCommandTest { +class PlayerCommandTest { @Test - public void shouldRejectNonPlayerSender() { + void shouldRejectNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); PlayerCommandImpl command = new PlayerCommandImpl(); @@ -34,7 +34,7 @@ public void shouldRejectNonPlayerSender() { } @Test - public void shouldCallRunCommandForPlayer() { + void shouldCallRunCommandForPlayer() { // given Player player = mock(Player.class); List arguments = Arrays.asList("arg1", "testarg2"); @@ -48,7 +48,7 @@ public void shouldCallRunCommandForPlayer() { } @Test - public void shouldRejectNonPlayerAndSendAlternative() { + void shouldRejectNonPlayerAndSendAlternative() { // given CommandSender sender = mock(CommandSender.class); PlayerCommandWithAlt command = new PlayerCommandWithAlt(); diff --git a/src/test/java/fr/xephi/authme/command/executable/HelpCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/HelpCommandTest.java index 33e0508e60..d8b9dea91d 100644 --- a/src/test/java/fr/xephi/authme/command/executable/HelpCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/HelpCommandTest.java @@ -6,12 +6,12 @@ import fr.xephi.authme.command.help.HelpProvider; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.List; @@ -26,8 +26,8 @@ import static fr.xephi.authme.command.help.HelpProvider.SHOW_DESCRIPTION; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -39,8 +39,8 @@ /** * Test for {@link HelpCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class HelpCommandTest { +@ExtendWith(MockitoExtension.class) +class HelpCommandTest { @InjectMocks private HelpCommand command; @@ -52,7 +52,7 @@ public class HelpCommandTest { private HelpProvider helpProvider; @Test - public void shouldHandleMissingBaseCommand() { + void shouldHandleMissingBaseCommand() { // given List arguments = asList("some", "command"); CommandSender sender = mock(CommandSender.class); @@ -68,7 +68,7 @@ public void shouldHandleMissingBaseCommand() { } @Test - public void shouldHandleWrongCommandWithSuggestion() { + void shouldHandleWrongCommandWithSuggestion() { // given List arguments = asList("authme", "ragister", "test"); CommandSender sender = mock(CommandSender.class); @@ -88,7 +88,7 @@ public void shouldHandleWrongCommandWithSuggestion() { } @Test - public void shouldHandleWrongCommandWithoutSuggestion() { + void shouldHandleWrongCommandWithoutSuggestion() { List arguments = asList("authme", "ragister", "test"); CommandSender sender = mock(CommandSender.class); FoundCommandResult foundCommandResult = new FoundCommandResult(null, asList("authme", "ragister"), @@ -106,7 +106,7 @@ public void shouldHandleWrongCommandWithoutSuggestion() { } @Test - public void shouldShowChildrenOfBaseCommand() { + void shouldShowChildrenOfBaseCommand() { List arguments = singletonList("authme"); CommandSender sender = mock(CommandSender.class); CommandDescription commandDescription = mock(CommandDescription.class); @@ -125,7 +125,7 @@ public void shouldShowChildrenOfBaseCommand() { } @Test - public void shouldShowDetailedHelpForChildCommand() { + void shouldShowDetailedHelpForChildCommand() { List arguments = asList("authme", "getpos"); CommandSender sender = mock(CommandSender.class); CommandDescription commandDescription = mock(CommandDescription.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/AccountsCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/AccountsCommandTest.java index 2fcb0e56e1..b744cde86e 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/AccountsCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/AccountsCommandTest.java @@ -6,20 +6,20 @@ import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +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.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -30,8 +30,8 @@ /** * Test for {@link AccountsCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class AccountsCommandTest { +@ExtendWith(MockitoExtension.class) +class AccountsCommandTest { @InjectMocks private AccountsCommand command; @@ -43,7 +43,7 @@ public class AccountsCommandTest { private BukkitService bukkitService; @Test - public void shouldGetAccountsOfCurrentUser() { + void shouldGetAccountsOfCurrentUser() { // given CommandSender sender = mock(CommandSender.class); given(sender.getName()).willReturn("Tester"); @@ -62,7 +62,7 @@ public void shouldGetAccountsOfCurrentUser() { } @Test - public void shouldReturnUnknownUserForNullAuth() { + void shouldReturnUnknownUserForNullAuth() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("SomeUser"); @@ -78,7 +78,7 @@ public void shouldReturnUnknownUserForNullAuth() { } @Test - public void shouldReturnUnregisteredMessageForEmptyAuthList() { + void shouldReturnUnregisteredMessageForEmptyAuthList() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("SomeUser"); @@ -95,7 +95,7 @@ public void shouldReturnUnregisteredMessageForEmptyAuthList() { } @Test - public void shouldReturnSingleAccountMessage() { + void shouldReturnSingleAccountMessage() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("SomeUser"); @@ -115,7 +115,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"); @@ -131,7 +131,7 @@ public void shouldReturnIpUnknown() { } @Test - public void shouldReturnSingleAccountForIpQuery() { + void shouldReturnSingleAccountForIpQuery() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("24.24.48.48"); @@ -147,7 +147,7 @@ public void shouldReturnSingleAccountForIpQuery() { } @Test - public void shouldReturnAccountListForIpQuery() { + void shouldReturnAccountListForIpQuery() { // given CommandSender sender = mock(CommandSender.class); List arguments = Collections.singletonList("98.76.41.122"); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/AuthMeCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/AuthMeCommandTest.java index 84ce1a9cc9..9c212ca512 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/AuthMeCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/AuthMeCommandTest.java @@ -2,13 +2,13 @@ import fr.xephi.authme.command.ExecutableCommand; import org.bukkit.command.CommandSender; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -16,10 +16,10 @@ /** * Test for {@link AuthMeCommand}. */ -public class AuthMeCommandTest { +class AuthMeCommandTest { @Test - public void shouldDisplayInformation() { + void shouldDisplayInformation() { // given ExecutableCommand command = new AuthMeCommand(); CommandSender sender = mock(CommandSender.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java index 2e1e0b5e82..5537aee925 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java @@ -2,11 +2,11 @@ import fr.xephi.authme.service.BackupService; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -16,8 +16,8 @@ /** * Test for {@link BackupCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class BackupCommandTest { +@ExtendWith(MockitoExtension.class) +class BackupCommandTest { @InjectMocks private BackupCommand command; @@ -26,7 +26,7 @@ public class BackupCommandTest { private BackupService backupService; @Test - public void shouldStartBackup() { + void shouldStartBackup() { // given CommandSender sender = mock(CommandSender.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/ChangePasswordAdminCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/ChangePasswordAdminCommandTest.java index 8e1a608155..95f0a968bf 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/ChangePasswordAdminCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/ChangePasswordAdminCommandTest.java @@ -6,11 +6,11 @@ import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.service.ValidationService.ValidationResult; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; @@ -22,8 +22,8 @@ /** * Test for {@link ChangePasswordAdminCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ChangePasswordAdminCommandTest { +@ExtendWith(MockitoExtension.class) +class ChangePasswordAdminCommandTest { @InjectMocks private ChangePasswordAdminCommand command; @@ -38,7 +38,7 @@ public class ChangePasswordAdminCommandTest { private Management management; @Test - public void shouldForwardRequestToManagement() { + void shouldForwardRequestToManagement() { // given String name = "theUser"; String pass = "newPassword"; @@ -54,7 +54,7 @@ public void shouldForwardRequestToManagement() { } @Test - public void shouldSendErrorToCommandSender() { + void shouldSendErrorToCommandSender() { // given String name = "theUser"; String pass = "newPassword"; diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/ConverterCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/ConverterCommandTest.java index cad80f9f05..7a37350660 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/ConverterCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/ConverterCommandTest.java @@ -8,12 +8,12 @@ import fr.xephi.authme.service.CommonService; import fr.xephi.authme.util.StringUtils; import org.bukkit.command.CommandSender; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.HashSet; @@ -22,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.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; @@ -37,8 +37,8 @@ /** * Test for {@link ConverterCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ConverterCommandTest { +@ExtendWith(MockitoExtension.class) +class ConverterCommandTest { @InjectMocks private ConverterCommand command; @@ -52,13 +52,13 @@ public class ConverterCommandTest { @Mock private Factory converterFactory; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldHandleUnknownConversionType() { + void shouldHandleUnknownConversionType() { // given CommandSender sender = mock(CommandSender.class); @@ -72,7 +72,7 @@ public void shouldHandleUnknownConversionType() { } @Test - public void shouldHandleCommandWithNoArgs() { + void shouldHandleCommandWithNoArgs() { // given CommandSender sender = mock(CommandSender.class); @@ -86,7 +86,7 @@ public void shouldHandleCommandWithNoArgs() { } @Test - public void shouldHaveUniqueClassForEachConverter() { + void shouldHaveUniqueClassForEachConverter() { // given Set> classes = new HashSet<>(); @@ -101,7 +101,7 @@ public void shouldHaveUniqueClassForEachConverter() { } @Test - public void shouldLaunchConverterForAllTypes() { + void shouldLaunchConverterForAllTypes() { // given String converterName = "rakamak"; Class converterClass = ConverterCommand.CONVERTERS.get(converterName); @@ -120,7 +120,7 @@ public void shouldLaunchConverterForAllTypes() { } @Test - public void shouldCatchExceptionInConverterAndInformSender() { + void shouldCatchExceptionInConverterAndInformSender() { // given String converterName = "vauth"; Class converterClass = ConverterCommand.CONVERTERS.get(converterName); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java index 4b1af2b970..77e0345989 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java @@ -3,11 +3,11 @@ import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -23,8 +23,8 @@ /** * Test for {@link FirstSpawnCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class FirstSpawnCommandTest { +@ExtendWith(MockitoExtension.class) +class FirstSpawnCommandTest { @InjectMocks private FirstSpawnCommand command; @@ -33,7 +33,7 @@ public class FirstSpawnCommandTest { private SpawnLoader spawnLoader; @Test - public void shouldTeleportToFirstSpawn() { + void shouldTeleportToFirstSpawn() { // given Location firstSpawn = mock(Location.class); given(spawnLoader.getFirstSpawn()).willReturn(firstSpawn); @@ -48,7 +48,7 @@ public void shouldTeleportToFirstSpawn() { } @Test - public void shouldHandleMissingFirstSpawn() { + void shouldHandleMissingFirstSpawn() { // given given(spawnLoader.getFirstSpawn()).willReturn(null); Player player = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java index b07b84596d..7f5ee6e04b 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java @@ -6,11 +6,11 @@ import fr.xephi.authme.service.BukkitService; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -24,8 +24,8 @@ /** * Test for {@link ForceLoginCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ForceLoginCommandTest { +@ExtendWith(MockitoExtension.class) +class ForceLoginCommandTest { @InjectMocks private ForceLoginCommand command; @@ -40,7 +40,7 @@ public class ForceLoginCommandTest { private BukkitService bukkitService; @Test - public void shouldRejectOfflinePlayer() { + void shouldRejectOfflinePlayer() { // given String playerName = "Bobby"; Player player = mockPlayer(false); @@ -57,7 +57,7 @@ public void shouldRejectOfflinePlayer() { } @Test - public void shouldRejectInexistentPlayer() { + void shouldRejectInexistentPlayer() { // given String playerName = "us3rname01"; given(bukkitService.getPlayerExact(playerName)).willReturn(null); @@ -73,7 +73,7 @@ public void shouldRejectInexistentPlayer() { } @Test - public void shouldRejectPlayerWithMissingPermission() { + void shouldRejectPlayerWithMissingPermission() { // given String playerName = "testTest"; Player player = mockPlayer(true); @@ -91,7 +91,7 @@ public void shouldRejectPlayerWithMissingPermission() { } @Test - public void shouldForceLoginPlayer() { + void shouldForceLoginPlayer() { // given String playerName = "tester23"; Player player = mockPlayer(true); @@ -108,7 +108,7 @@ public void shouldForceLoginPlayer() { } @Test - public void shouldForceLoginSenderSelf() { + void shouldForceLoginSenderSelf() { // given String senderName = "tester23"; Player player = mockPlayer(true); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/GetEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/GetEmailCommandTest.java index dc3fda40e0..cea1ffdafe 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/GetEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/GetEmailCommandTest.java @@ -5,11 +5,11 @@ import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.CommonService; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -22,8 +22,8 @@ /** * Test for {@link GetEmailCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class GetEmailCommandTest { +@ExtendWith(MockitoExtension.class) +class GetEmailCommandTest { @InjectMocks private GetEmailCommand command; @@ -35,7 +35,7 @@ public class GetEmailCommandTest { private CommonService service; @Test - public void shouldReportUnknownUser() { + void shouldReportUnknownUser() { // given String user = "myTestUser"; given(dataSource.getEmail(user)).willReturn(DataSourceValueImpl.unknownRow()); @@ -49,7 +49,7 @@ public void shouldReportUnknownUser() { } @Test - public void shouldReturnEmail() { + void shouldReturnEmail() { // given String user = "userToView"; String email = "user.email@example.org"; diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/GetIpCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/GetIpCommandTest.java index 8fe65e90b6..5822358191 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/GetIpCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/GetIpCommandTest.java @@ -6,11 +6,11 @@ import fr.xephi.authme.service.BukkitService; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -26,8 +26,8 @@ /** * Test for {@link GetIpCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class GetIpCommandTest { +@ExtendWith(MockitoExtension.class) +class GetIpCommandTest { @InjectMocks private GetIpCommand command; @@ -40,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); @@ -57,7 +57,7 @@ public void shouldGetIpOfPlayer() { } @Test - public void shouldReturnIpAddressOfPlayer() { + void shouldReturnIpAddressOfPlayer() { // given String playerName = "charlie"; String ip = "123.34.56.88"; @@ -78,7 +78,7 @@ public void shouldReturnIpAddressOfPlayer() { } @Test - public void shouldHandleUnregisteredOnlinePlayer() { + void shouldHandleUnregisteredOnlinePlayer() { // given String playerName = "Test"; String ip = "44.111.22.33"; diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/LastLoginCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/LastLoginCommandTest.java index 9e35cd7cf4..9287ab1054 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/LastLoginCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/LastLoginCommandTest.java @@ -5,19 +5,19 @@ import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.CommonService; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +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.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -26,8 +26,8 @@ /** * Test for {@link LastLoginCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class LastLoginCommandTest { +@ExtendWith(MockitoExtension.class) +class LastLoginCommandTest { private static final long HOUR_IN_MSEC = 3600 * 1000; private static final long DAY_IN_MSEC = 24 * HOUR_IN_MSEC; @@ -43,7 +43,7 @@ public class LastLoginCommandTest { @Test - public void shouldRejectNonExistentUser() { + void shouldRejectNonExistentUser() { // given String player = "tester"; given(dataSource.getAuth(player)).willReturn(null); @@ -58,7 +58,7 @@ public void shouldRejectNonExistentUser() { } @Test - public void shouldDisplayLastLoginOfUser() { + void shouldDisplayLastLoginOfUser() { // given String player = "SomePlayer"; long lastLogin = System.currentTimeMillis() - @@ -84,7 +84,7 @@ public void shouldDisplayLastLoginOfUser() { } @Test - public void shouldDisplayLastLoginOfCommandSender() { + void shouldDisplayLastLoginOfCommandSender() { // given String name = "CommandSender"; CommandSender sender = mock(CommandSender.class); @@ -112,7 +112,7 @@ public void shouldDisplayLastLoginOfCommandSender() { } @Test - public void shouldHandleNullLastLoginDate() { + void shouldHandleNullLastLoginDate() { // given String name = "player"; PlayerAuth auth = PlayerAuth.builder() diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommandTest.java index 7c675bc07a..2f33514dff 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommandTest.java @@ -4,11 +4,11 @@ import fr.xephi.authme.task.purge.PurgeService; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.HashSet; @@ -26,8 +26,8 @@ /** * Test for {@link PurgeBannedPlayersCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class PurgeBannedPlayersCommandTest { +@ExtendWith(MockitoExtension.class) +class PurgeBannedPlayersCommandTest { @InjectMocks private PurgeBannedPlayersCommand command; @@ -39,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); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/PurgeCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/PurgeCommandTest.java index 70e4f03a12..9af91e7985 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/PurgeCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/PurgeCommandTest.java @@ -2,20 +2,20 @@ import fr.xephi.authme.task.purge.PurgeService; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +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.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -25,8 +25,8 @@ /** * Test for {@link PurgeCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class PurgeCommandTest { +@ExtendWith(MockitoExtension.class) +class PurgeCommandTest { @InjectMocks private PurgeCommand command; @@ -35,7 +35,7 @@ public class PurgeCommandTest { private PurgeService purgeService; @Test - public void shouldHandleInvalidNumber() { + void shouldHandleInvalidNumber() { // given String interval = "invalid"; CommandSender sender = mock(CommandSender.class); @@ -49,7 +49,7 @@ public void shouldHandleInvalidNumber() { } @Test - public void shouldRejectTooSmallInterval() { + void shouldRejectTooSmallInterval() { // given String interval = "29"; CommandSender sender = mock(CommandSender.class); @@ -63,7 +63,7 @@ public void shouldRejectTooSmallInterval() { } @Test - public void shouldForwardToService() { + void shouldForwardToService() { // given String interval = "45"; CommandSender sender = mock(CommandSender.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommandTest.java index 57bb21e26b..346f7a05e7 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommandTest.java @@ -6,11 +6,11 @@ import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.bungeecord.BungeeSender; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; @@ -24,8 +24,8 @@ /** * Test for {@link PurgeLastPositionCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class PurgeLastPositionCommandTest { +@ExtendWith(MockitoExtension.class) +class PurgeLastPositionCommandTest { @InjectMocks private PurgeLastPositionCommand command; @@ -40,7 +40,7 @@ public class PurgeLastPositionCommandTest { private BungeeSender bungeeSender; @Test - public void shouldPurgeLastPosOfUser() { + void shouldPurgeLastPosOfUser() { // given String player = "_Bobby"; PlayerAuth auth = mock(PlayerAuth.class); @@ -57,7 +57,7 @@ public void shouldPurgeLastPosOfUser() { } @Test - public void shouldPurgePositionOfCommandSender() { + void shouldPurgePositionOfCommandSender() { // given String player = "_Bobby"; CommandSender sender = mock(CommandSender.class); @@ -75,7 +75,7 @@ public void shouldPurgePositionOfCommandSender() { } @Test - public void shouldHandleNonExistentUser() { + void shouldHandleNonExistentUser() { // given String name = "invalidPlayer"; CommandSender sender = mock(CommandSender.class); @@ -89,7 +89,7 @@ public void shouldHandleNonExistentUser() { } @Test - public void shouldResetAllLastPositions() { + void shouldResetAllLastPositions() { // given PlayerAuth auth1 = mock(PlayerAuth.class); PlayerAuth auth2 = mock(PlayerAuth.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/PurgePlayerCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/PurgePlayerCommandTest.java index cf48d2a394..6d5fb2b6cc 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/PurgePlayerCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/PurgePlayerCommandTest.java @@ -5,11 +5,11 @@ import fr.xephi.authme.task.purge.PurgeExecutor; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Locale; @@ -27,8 +27,8 @@ /** * Test for {@link PurgePlayerCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class PurgePlayerCommandTest { +@ExtendWith(MockitoExtension.class) +class PurgePlayerCommandTest { @InjectMocks private PurgePlayerCommand command; @@ -43,7 +43,7 @@ public class PurgePlayerCommandTest { private DataSource dataSource; @Test - public void shouldNotExecutePurgeForRegisteredPlayer() { + void shouldNotExecutePurgeForRegisteredPlayer() { // given String name = "Bobby"; given(dataSource.isAuthAvailable(name)).willReturn(true); @@ -59,7 +59,7 @@ public void shouldNotExecutePurgeForRegisteredPlayer() { } @Test - public void shouldExecutePurge() { + void shouldExecutePurge() { // given String name = "Frank"; given(dataSource.isAuthAvailable(name)).willReturn(false); @@ -77,7 +77,7 @@ public void shouldExecutePurge() { } @Test - public void shouldExecutePurgeOfRegisteredPlayer() { + void shouldExecutePurgeOfRegisteredPlayer() { // given String name = "GhiJKlmn7"; OfflinePlayer player = mock(OfflinePlayer.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/RecentPlayersCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/RecentPlayersCommandTest.java index 30ee0e72e2..b2c70322a3 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/RecentPlayersCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/RecentPlayersCommandTest.java @@ -3,12 +3,12 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.time.ZoneId; import java.util.Arrays; @@ -25,8 +25,8 @@ /** * Test for {@link RecentPlayersCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class RecentPlayersCommandTest { +@ExtendWith(MockitoExtension.class) +class RecentPlayersCommandTest { @InjectMocks @Spy @@ -36,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") @@ -61,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") diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java index 07808fa586..914ebd8d48 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java @@ -12,21 +12,21 @@ import fr.xephi.authme.service.ValidationService.ValidationResult; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +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.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -36,8 +36,8 @@ /** * Test for {@link RegisterAdminCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class RegisterAdminCommandTest { +@ExtendWith(MockitoExtension.class) +class RegisterAdminCommandTest { @InjectMocks private RegisterAdminCommand command; @@ -57,13 +57,13 @@ public class RegisterAdminCommandTest { @Mock private ValidationService validationService; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldRejectInvalidPassword() { + void shouldRejectInvalidPassword() { // given String user = "tester"; String password = "myPassword"; @@ -81,7 +81,7 @@ public void shouldRejectInvalidPassword() { } @Test - public void shouldRejectAlreadyRegisteredAccount() { + void shouldRejectAlreadyRegisteredAccount() { // given String user = "my_name55"; String password = "@some-pass@"; @@ -100,7 +100,7 @@ public void shouldRejectAlreadyRegisteredAccount() { } @Test - public void shouldHandleSavingError() { + void shouldHandleSavingError() { // given String user = "test-test"; String password = "afdjhfkt"; @@ -124,7 +124,7 @@ public void shouldHandleSavingError() { } @Test - public void shouldRegisterOfflinePlayer() { + void shouldRegisterOfflinePlayer() { // given String user = "someone"; String password = "Al1O3P49S5%"; @@ -149,7 +149,7 @@ public void shouldRegisterOfflinePlayer() { } @Test - public void shouldRegisterOnlinePlayer() { + void shouldRegisterOnlinePlayer() { // given String user = "someone"; String password = "Al1O3P49S5%"; diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java index 679b5e5274..2525812f0d 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java @@ -16,13 +16,13 @@ import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.command.CommandSender; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; @@ -38,8 +38,8 @@ /** * Test for {@link ReloadCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ReloadCommandTest { +@ExtendWith(MockitoExtension.class) +class ReloadCommandTest { @InjectMocks private ReloadCommand command; @@ -65,20 +65,20 @@ public class ReloadCommandTest { @Mock private SingletonStore settingsDependentStore; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } - @Before - public void setDefaultSettings() { + @BeforeEach + 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); @@ -101,7 +101,7 @@ public void shouldReload() { } @Test - public void shouldHandleReloadError() { + void shouldHandleReloadError() { // given CommandSender sender = mock(CommandSender.class); doThrow(IllegalStateException.class).when(reloadableStore).retrieveAllOfType(); @@ -119,7 +119,7 @@ public void shouldHandleReloadError() { } @Test - public void shouldIssueWarningForChangedDataSourceSetting() { + void shouldIssueWarningForChangedDataSourceSetting() { // given CommandSender sender = mock(CommandSender.class); given(settings.getProperty(DatabaseSettings.BACKEND)).willReturn(DataSourceType.MYSQL); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/SetEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/SetEmailCommandTest.java index 3b96070d6f..871f4f4690 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/SetEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/SetEmailCommandTest.java @@ -8,11 +8,11 @@ import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.ValidationService; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; @@ -28,8 +28,8 @@ /** * Test for {@link SetEmailCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class SetEmailCommandTest { +@ExtendWith(MockitoExtension.class) +class SetEmailCommandTest { @InjectMocks private SetEmailCommand command; @@ -50,7 +50,7 @@ public class SetEmailCommandTest { private ValidationService validationService; @Test - public void shouldRejectInvalidMail() { + void shouldRejectInvalidMail() { // given String user = "somebody"; String email = "some.test@example.org"; @@ -67,7 +67,7 @@ public void shouldRejectInvalidMail() { } @Test - public void shouldHandleUnknownUser() { + void shouldHandleUnknownUser() { // given String user = "nonexistent"; String email = "mail@example.com"; @@ -87,7 +87,7 @@ public void shouldHandleUnknownUser() { } @Test - public void shouldHandleAlreadyTakenEmail() { + void shouldHandleAlreadyTakenEmail() { // given String user = "someone"; String email = "mail@example.com"; @@ -111,7 +111,7 @@ public void shouldHandleAlreadyTakenEmail() { } @Test - public void shouldHandlePersistenceError() { + void shouldHandlePersistenceError() { // given String user = "Bobby"; String email = "new-addr@example.org"; @@ -136,7 +136,7 @@ public void shouldHandlePersistenceError() { } @Test - public void shouldUpdateEmail() { + void shouldUpdateEmail() { // given String user = "Bobby"; String email = "new-addr@example.org"; @@ -163,7 +163,7 @@ public void shouldUpdateEmail() { } @Test - public void shouldUpdateEmailAndPlayerCache() { + void shouldUpdateEmailAndPlayerCache() { // given String user = "Bobby"; String email = "new-addr@example.org"; diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommandTest.java index 67cb3d91c8..4fed450dac 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommandTest.java @@ -3,11 +3,11 @@ import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -20,8 +20,8 @@ /** * Test for {@link SetFirstSpawnCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class SetFirstSpawnCommandTest { +@ExtendWith(MockitoExtension.class) +class SetFirstSpawnCommandTest { @InjectMocks private SetFirstSpawnCommand command; @@ -31,7 +31,7 @@ public class SetFirstSpawnCommandTest { @Test - public void shouldSetFirstSpawn() { + void shouldSetFirstSpawn() { // given Player player = mock(Player.class); Location location = mock(Location.class); @@ -47,7 +47,7 @@ public void shouldSetFirstSpawn() { } @Test - public void shouldHandleError() { + void shouldHandleError() { // given Player player = mock(Player.class); Location location = mock(Location.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/SetSpawnCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/SetSpawnCommandTest.java index 17f77e31be..d5e4eb9d4e 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/SetSpawnCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/SetSpawnCommandTest.java @@ -3,11 +3,11 @@ import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -20,8 +20,8 @@ /** * Test for {@link SetSpawnCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class SetSpawnCommandTest { +@ExtendWith(MockitoExtension.class) +class SetSpawnCommandTest { @InjectMocks private SetSpawnCommand command; @@ -31,7 +31,7 @@ public class SetSpawnCommandTest { @Test - public void shouldSetSpawn() { + void shouldSetSpawn() { // given Player player = mock(Player.class); Location location = mock(Location.class); @@ -47,7 +47,7 @@ public void shouldSetSpawn() { } @Test - public void shouldHandleError() { + void shouldHandleError() { // given Player player = mock(Player.class); Location location = mock(Location.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/SpawnCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/SpawnCommandTest.java index b9566c98b8..841a569b67 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/SpawnCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/SpawnCommandTest.java @@ -3,11 +3,11 @@ import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -23,8 +23,8 @@ /** * Test for {@link SpawnCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class SpawnCommandTest { +@ExtendWith(MockitoExtension.class) +class SpawnCommandTest { @InjectMocks private SpawnCommand command; @@ -34,7 +34,7 @@ public class SpawnCommandTest { @Test - public void shouldTeleportToSpawn() { + void shouldTeleportToSpawn() { // given Location spawn = mock(Location.class); given(spawnLoader.getSpawn()).willReturn(spawn); @@ -49,7 +49,7 @@ public void shouldTeleportToSpawn() { } @Test - public void shouldHandleMissingSpawn() { + void shouldHandleMissingSpawn() { // given given(spawnLoader.getSpawn()).willReturn(null); Player player = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommandTest.java index f3c2e99ca7..fe70aac498 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommandTest.java @@ -5,11 +5,11 @@ import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.service.AntiBotService; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -25,8 +25,8 @@ /** * Test for {@link SwitchAntiBotCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class SwitchAntiBotCommandTest { +@ExtendWith(MockitoExtension.class) +class SwitchAntiBotCommandTest { @InjectMocks private SwitchAntiBotCommand command; @@ -41,7 +41,7 @@ public class SwitchAntiBotCommandTest { private HelpProvider helpProvider; @Test - public void shouldReturnAntiBotState() { + void shouldReturnAntiBotState() { // given given(antiBot.getAntiBotStatus()).willReturn(AntiBotService.AntiBotStatus.ACTIVE); CommandSender sender = mock(CommandSender.class); @@ -54,7 +54,7 @@ public void shouldReturnAntiBotState() { } @Test - public void shouldActivateAntiBot() { + void shouldActivateAntiBot() { // given CommandSender sender = mock(CommandSender.class); @@ -67,7 +67,7 @@ public void shouldActivateAntiBot() { } @Test - public void shouldDeactivateAntiBot() { + void shouldDeactivateAntiBot() { // given CommandSender sender = mock(CommandSender.class); @@ -80,7 +80,7 @@ public void shouldDeactivateAntiBot() { } @Test - public void shouldShowHelpForUnknownState() { + void shouldShowHelpForUnknownState() { // given CommandSender sender = mock(CommandSender.class); FoundCommandResult foundCommandResult = mock(FoundCommandResult.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommandTest.java index e6728d8940..a5c056005b 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/TotpDisableAdminCommandTest.java @@ -8,12 +8,12 @@ import fr.xephi.authme.service.BukkitService; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -27,8 +27,8 @@ /** * Test for {@link TotpDisableAdminCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class TotpDisableAdminCommandTest { +@ExtendWith(MockitoExtension.class) +class TotpDisableAdminCommandTest { @InjectMocks private TotpDisableAdminCommand command; @@ -42,13 +42,13 @@ public class TotpDisableAdminCommandTest { @Mock private BukkitService bukkitService; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldHandleUnknownUser() { + void shouldHandleUnknownUser() { // given CommandSender sender = mock(CommandSender.class); given(dataSource.getAuth("user")).willReturn(null); @@ -62,7 +62,7 @@ public void shouldHandleUnknownUser() { } @Test - public void shouldHandleUserWithNoTotpEnabled() { + void shouldHandleUserWithNoTotpEnabled() { // given CommandSender sender = mock(CommandSender.class); PlayerAuth auth = PlayerAuth.builder() @@ -80,7 +80,7 @@ public void shouldHandleUserWithNoTotpEnabled() { } @Test - public void shouldRemoveTotpFromUser() { + void shouldRemoveTotpFromUser() { // given CommandSender sender = mock(CommandSender.class); PlayerAuth auth = PlayerAuth.builder() @@ -101,7 +101,7 @@ public void shouldRemoveTotpFromUser() { } @Test - public void shouldHandleErrorWhileRemovingTotp() { + void shouldHandleErrorWhileRemovingTotp() { // given CommandSender sender = mock(CommandSender.class); PlayerAuth auth = PlayerAuth.builder() diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommandTest.java index ba6560306b..91133c683b 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/TotpViewStatusCommandTest.java @@ -6,12 +6,12 @@ import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import org.bukkit.command.CommandSender; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -25,8 +25,8 @@ /** * Test for {@link TotpViewStatusCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class TotpViewStatusCommandTest { +@ExtendWith(MockitoExtension.class) +class TotpViewStatusCommandTest { @InjectMocks private TotpViewStatusCommand command; @@ -37,13 +37,13 @@ public class TotpViewStatusCommandTest { @Mock private Messages messages; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldHandleUnknownUser() { + void shouldHandleUnknownUser() { // given CommandSender sender = mock(CommandSender.class); given(dataSource.getAuth("user")).willReturn(null); @@ -57,7 +57,7 @@ public void shouldHandleUnknownUser() { } @Test - public void shouldInformForUserWithoutTotp() { + void shouldInformForUserWithoutTotp() { // given CommandSender sender = mock(CommandSender.class); PlayerAuth auth = PlayerAuth.builder() @@ -74,7 +74,7 @@ public void shouldInformForUserWithoutTotp() { } @Test - public void shouldInformForUserWithTotpEnabled() { + void shouldInformForUserWithTotpEnabled() { // given CommandSender sender = mock(CommandSender.class); PlayerAuth auth = PlayerAuth.builder() diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommandTest.java index 4651b2beb1..ceb99ad65f 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommandTest.java @@ -7,11 +7,11 @@ import fr.xephi.authme.service.CommonService; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -23,8 +23,8 @@ /** * Test for {@link UnregisterAdminCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class UnregisterAdminCommandTest { +@ExtendWith(MockitoExtension.class) +class UnregisterAdminCommandTest { @InjectMocks private UnregisterAdminCommand command; @@ -42,7 +42,7 @@ public class UnregisterAdminCommandTest { private Management management; @Test - public void shouldHandleUnknownPlayer() { + void shouldHandleUnknownPlayer() { // given String user = "bobby"; given(dataSource.isAuthAvailable(user)).willReturn(false); @@ -57,7 +57,7 @@ public void shouldHandleUnknownPlayer() { } @Test - public void shouldInvokeUnregisterProcess() { + void shouldInvokeUnregisterProcess() { // given String user = "personaNonGrata"; given(dataSource.isAuthAvailable(user)).willReturn(true); @@ -75,7 +75,7 @@ public void shouldInvokeUnregisterProcess() { } @Test - public void shouldInvokeUnregisterProcessWithNullPlayer() { + void shouldInvokeUnregisterProcessWithNullPlayer() { // given String user = "personaNonGrata"; given(dataSource.isAuthAvailable(user)).willReturn(true); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/UpdateHelpMessagesCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/UpdateHelpMessagesCommandTest.java index 64113da4a0..118c9721fa 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/UpdateHelpMessagesCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/UpdateHelpMessagesCommandTest.java @@ -4,12 +4,12 @@ import fr.xephi.authme.command.help.HelpMessagesService; import fr.xephi.authme.service.HelpTranslationGenerator; import org.bukkit.command.CommandSender; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -23,8 +23,8 @@ /** * Test for {@link UpdateHelpMessagesCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class UpdateHelpMessagesCommandTest { +@ExtendWith(MockitoExtension.class) +class UpdateHelpMessagesCommandTest { @InjectMocks private UpdateHelpMessagesCommand command; @@ -34,13 +34,13 @@ public class UpdateHelpMessagesCommandTest { @Mock private HelpMessagesService helpMessagesService; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldUpdateHelpMessage() throws IOException { + void shouldUpdateHelpMessage() throws IOException { // given File updatedFile = new File("some/path/help_xx.yml"); given(helpTranslationGenerator.updateHelpFile()).willReturn(updatedFile); @@ -55,7 +55,7 @@ public void shouldUpdateHelpMessage() throws IOException { } @Test - public void shouldCatchAndReportException() throws IOException { + void shouldCatchAndReportException() throws IOException { // given given(helpTranslationGenerator.updateHelpFile()).willThrow(new IOException("Couldn't do the thing")); CommandSender sender = mock(CommandSender.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DataStatisticsTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DataStatisticsTest.java index fe50d83702..5ce624468b 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DataStatisticsTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DataStatisticsTest.java @@ -15,13 +15,13 @@ import fr.xephi.authme.output.ConsoleLoggerFactory; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.HashMap; @@ -29,9 +29,9 @@ import java.util.Map; import java.util.Optional; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -40,8 +40,8 @@ /** * Test for {@link DataStatistics}. */ -@RunWith(MockitoJUnitRunner.class) -public class DataStatisticsTest { +@ExtendWith(MockitoExtension.class) +class DataStatisticsTest { @InjectMocks private DataStatistics dataStatistics; @@ -55,15 +55,15 @@ public class DataStatisticsTest { @Mock private SingletonStore singletonStore; - @Before - public void setUpLimboCacheMap() { + @BeforeEach + 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)); @@ -96,7 +96,7 @@ public void shouldOutputStatistics() { } @Test - public void shouldOutputCachedDataSourceStatistics() { + void shouldOutputCachedDataSourceStatistics() { // given CacheDataSource cacheDataSource = mock(CacheDataSource.class); LoadingCache> cache = mock(LoadingCache.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugCommandTest.java index 82e39d4113..d6b8aacf13 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugCommandTest.java @@ -6,13 +6,13 @@ import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.List; @@ -20,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.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.eq; @@ -41,8 +41,8 @@ /** * Test for {@link DebugCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class DebugCommandTest { +@ExtendWith(MockitoExtension.class) +class DebugCommandTest { /** * Number we test against if we expect an action to have been performed for each debug section. @@ -60,9 +60,9 @@ public class DebugCommandTest { @Mock private PermissionsManager permissionsManager; - @Before + @BeforeEach @SuppressWarnings("unchecked") - public void initFactory() { + void initFactory() { given(debugSectionFactory.newInstance(any(Class.class))).willAnswer( invocation -> { Class classArgument = invocation.getArgument(0); @@ -72,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); @@ -96,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); @@ -117,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()); @@ -137,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(...)" diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java index ea92f85e6b..f5be549df7 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java @@ -2,30 +2,30 @@ import fr.xephi.authme.ClassCollector; import fr.xephi.authme.TestHelper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.lang.reflect.Modifier; import java.util.HashSet; 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.junit.Assert.assertThat; -import static org.junit.Assert.fail; +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; - @BeforeClass - public static void collectClasses() { + @BeforeAll + 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())); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java index 1157663ba6..b666004e59 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java @@ -8,31 +8,31 @@ import fr.xephi.authme.datasource.CacheDataSource; import fr.xephi.authme.datasource.DataSource; import org.bukkit.Location; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; 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.junit.Assert.assertThat; import static org.mockito.Mockito.mock; /** * Test for {@link DebugSectionUtils}. */ -public class DebugSectionUtilsTest { +class DebugSectionUtilsTest { - @Before - public void initMockLogger() { + @BeforeEach + 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<>(); @@ -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()); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/HasPermissionCheckerTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/HasPermissionCheckerTest.java index 4bd8eab199..8e307a8958 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/HasPermissionCheckerTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/HasPermissionCheckerTest.java @@ -8,22 +8,22 @@ import fr.xephi.authme.service.BukkitService; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +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.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; @@ -33,8 +33,8 @@ /** * Test for {@link HasPermissionChecker}. */ -@RunWith(MockitoJUnitRunner.class) -public class HasPermissionCheckerTest { +@ExtendWith(MockitoExtension.class) +class HasPermissionCheckerTest { @InjectMocks private HasPermissionChecker hasPermissionChecker; @@ -46,7 +46,7 @@ public class HasPermissionCheckerTest { private BukkitService bukkitService; @Test - public void shouldListAllPermissionNodeClasses() { + void shouldListAllPermissionNodeClasses() { // given List> permissionClasses = new ClassCollector(TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT) @@ -59,7 +59,7 @@ public void shouldListAllPermissionNodeClasses() { } @Test - public void shouldShowUsageInfo() { + void shouldShowUsageInfo() { // given CommandSender sender = mock(CommandSender.class); @@ -75,7 +75,7 @@ public void shouldShowUsageInfo() { } @Test - public void shouldShowSuccessfulTestWithRegularPlayer() { + void shouldShowSuccessfulTestWithRegularPlayer() { // given String name = "Chuck"; Player player = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerColumnsTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerColumnsTest.java index df891fe68d..46649651f2 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerColumnsTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerColumnsTest.java @@ -1,21 +1,21 @@ package fr.xephi.authme.command.executable.authme.debug; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +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); } diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerTest.java index 516d16780d..882402f498 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/MySqlDefaultChangerTest.java @@ -9,19 +9,19 @@ import fr.xephi.authme.datasource.MySQL; import fr.xephi.authme.datasource.SqlDataSourceTestUtil; import fr.xephi.authme.settings.Settings; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +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.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -29,19 +29,19 @@ /** * Test for {@link MySqlDefaultChanger}. */ -@RunWith(MockitoJUnitRunner.class) -public class MySqlDefaultChangerTest { +@ExtendWith(MockitoExtension.class) +class MySqlDefaultChangerTest { @Mock private Settings settings; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldReturnMySqlConnection() throws SQLException { + void shouldReturnMySqlConnection() throws SQLException { // given Settings settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); @@ -60,7 +60,7 @@ public void shouldReturnMySqlConnection() throws SQLException { } @Test - public void shouldSetMySqlFieldOnInitialization() { + void shouldSetMySqlFieldOnInitialization() { // given MySQL mySql = mock(MySQL.class); MySqlDefaultChanger defaultChanger = createDefaultChanger(mySql); @@ -74,7 +74,7 @@ public void shouldSetMySqlFieldOnInitialization() { } @Test - public void shouldLeaveMySqlFieldToNullOnInitialization() { + void shouldLeaveMySqlFieldToNullOnInitialization() { // given DataSource dataSource = mock(DataSource.class); PlayerCache playerCache = mock(PlayerCache.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/PlayerAuthViewerTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/PlayerAuthViewerTest.java index 8f34bcbf85..6e8d6dde39 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/PlayerAuthViewerTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/PlayerAuthViewerTest.java @@ -3,18 +3,18 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +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.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -24,8 +24,8 @@ /** * Test for {@link PlayerAuthViewer}. */ -@RunWith(MockitoJUnitRunner.class) -public class PlayerAuthViewerTest { +@ExtendWith(MockitoExtension.class) +class PlayerAuthViewerTest { @InjectMocks private PlayerAuthViewer authViewer; @@ -34,7 +34,7 @@ public class PlayerAuthViewerTest { private DataSource dataSource; @Test - public void shouldMakeExample() { + void shouldMakeExample() { // given CommandSender sender = mock(CommandSender.class); @@ -46,7 +46,7 @@ public void shouldMakeExample() { } @Test - public void shouldHandleMissingPlayer() { + void shouldHandleMissingPlayer() { // given CommandSender sender = mock(CommandSender.class); @@ -59,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") @@ -82,7 +82,7 @@ public void shouldDisplayAuthInfo() { } @Test - public void shouldHandleCornerCases() { + void shouldHandleCornerCases() { // given CommandSender sender = mock(CommandSender.class); PlayerAuth auth = PlayerAuth.builder().name("tar") diff --git a/src/test/java/fr/xephi/authme/command/executable/captcha/CaptchaCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/captcha/CaptchaCommandTest.java index 9f47dfae3e..9faad79c06 100644 --- a/src/test/java/fr/xephi/authme/command/executable/captcha/CaptchaCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/captcha/CaptchaCommandTest.java @@ -8,11 +8,11 @@ import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.CommonService; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -25,8 +25,8 @@ /** * Test for {@link CaptchaCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class CaptchaCommandTest { +@ExtendWith(MockitoExtension.class) +class CaptchaCommandTest { @InjectMocks private CaptchaCommand command; @@ -50,7 +50,7 @@ public class CaptchaCommandTest { private DataSource dataSource; @Test - public void shouldDetectIfPlayerIsLoggedIn() { + void shouldDetectIfPlayerIsLoggedIn() { // given String name = "creeper011"; Player player = mockPlayerWithName(name); @@ -64,7 +64,7 @@ public void shouldDetectIfPlayerIsLoggedIn() { } @Test - public void shouldShowLoginUsageIfCaptchaIsNotRequired() { + void shouldShowLoginUsageIfCaptchaIsNotRequired() { // given String name = "bobby"; Player player = mockPlayerWithName(name); @@ -82,7 +82,7 @@ public void shouldShowLoginUsageIfCaptchaIsNotRequired() { } @Test - public void shouldHandleCorrectCaptchaInput() { + void shouldHandleCorrectCaptchaInput() { // given String name = "smith"; Player player = mockPlayerWithName(name); @@ -105,7 +105,7 @@ public void shouldHandleCorrectCaptchaInput() { } @Test - public void shouldHandleWrongCaptchaInput() { + void shouldHandleWrongCaptchaInput() { // given String name = "smith"; Player player = mockPlayerWithName(name); @@ -129,7 +129,7 @@ public void shouldHandleWrongCaptchaInput() { } @Test - public void shouldVerifyWithRegisterCaptchaManager() { + void shouldVerifyWithRegisterCaptchaManager() { // given String name = "john"; Player player = mockPlayerWithName(name); @@ -149,7 +149,7 @@ public void shouldVerifyWithRegisterCaptchaManager() { } @Test - public void shouldHandleFailedRegisterCaptcha() { + void shouldHandleFailedRegisterCaptcha() { // given String name = "asfd"; Player player = mockPlayerWithName(name); @@ -168,7 +168,7 @@ public void shouldHandleFailedRegisterCaptcha() { } @Test - public void shouldShowRegisterUsageWhenRegistrationCaptchaIsSolved() { + void shouldShowRegisterUsageWhenRegistrationCaptchaIsSolved() { // given String name = "alice"; Player player = mockPlayerWithName(name); diff --git a/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java index 4c5488cb85..e26d3df94f 100644 --- a/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java @@ -10,18 +10,18 @@ import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; @@ -34,8 +34,8 @@ /** * Test for {@link ChangePasswordCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ChangePasswordCommandTest { +@ExtendWith(MockitoExtension.class) +class ChangePasswordCommandTest { @InjectMocks private ChangePasswordCommand command; @@ -56,7 +56,7 @@ public class ChangePasswordCommandTest { private Management management; @Test - public void shouldRejectNonPlayerSender() { + void shouldRejectNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); @@ -68,7 +68,7 @@ public void shouldRejectNonPlayerSender() { } @Test - public void shouldRejectNotLoggedInPlayer() { + void shouldRejectNotLoggedInPlayer() { // given CommandSender sender = initPlayerWithName("name", false); @@ -80,7 +80,7 @@ public void shouldRejectNotLoggedInPlayer() { } @Test - public void shouldRejectInvalidPassword() { + void shouldRejectInvalidPassword() { // given Player sender = initPlayerWithName("abc12", true); String password = "newPW"; @@ -97,7 +97,7 @@ public void shouldRejectInvalidPassword() { } @Test - public void shouldForwardTheDataForValidPassword() { + void shouldForwardTheDataForValidPassword() { // given String oldPass = "oldpass"; String newPass = "abc123"; @@ -116,7 +116,7 @@ public void shouldForwardTheDataForValidPassword() { } @Test - public void shouldDefineArgumentMismatchMessage() { + void shouldDefineArgumentMismatchMessage() { // given / when / then assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_CHANGE_PASSWORD)); } diff --git a/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java index c8a57562fa..4579980597 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java @@ -6,17 +6,17 @@ import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -24,8 +24,8 @@ /** * Test for {@link AddEmailCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class AddEmailCommandTest { +@ExtendWith(MockitoExtension.class) +class AddEmailCommandTest { @InjectMocks private AddEmailCommand command; @@ -37,7 +37,7 @@ public class AddEmailCommandTest { private Management management; @Test - public void shouldRejectNonPlayerSender() { + void shouldRejectNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); @@ -49,7 +49,7 @@ public void shouldRejectNonPlayerSender() { } @Test - public void shouldForwardData() { + void shouldForwardData() { // given Player sender = mock(Player.class); String email = "mail@example"; @@ -62,7 +62,7 @@ public void shouldForwardData() { } @Test - public void shouldFailForConfirmationMismatch() { + void shouldFailForConfirmationMismatch() { // given Player sender = mock(Player.class); String email = "asdfasdf@example.com"; @@ -76,7 +76,7 @@ public void shouldFailForConfirmationMismatch() { } @Test - public void shouldDefineArgumentMismatchMessage() { + void shouldDefineArgumentMismatchMessage() { // given / when / then assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_ADD_EMAIL)); } diff --git a/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java index 3c99e17dcf..99757bf959 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java @@ -7,17 +7,17 @@ import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -27,8 +27,8 @@ /** * Test for {@link ChangeEmailCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ChangeEmailCommandTest { +@ExtendWith(MockitoExtension.class) +class ChangeEmailCommandTest { @InjectMocks private ChangeEmailCommand command; @@ -44,7 +44,7 @@ public class ChangeEmailCommandTest { @Test - public void shouldRejectNonPlayerSender() { + void shouldRejectNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); @@ -56,7 +56,7 @@ public void shouldRejectNonPlayerSender() { } @Test - public void shouldStopIfVerificationIsRequired() { + void shouldStopIfVerificationIsRequired() { // given String name = "Testeroni"; Player player = initPlayerWithName(name); @@ -72,7 +72,7 @@ public void shouldStopIfVerificationIsRequired() { } @Test - public void shouldForwardData() { + void shouldForwardData() { // given Player sender = initPlayerWithName("AmATest"); given(codeManager.isVerificationRequired(sender)).willReturn(false); @@ -86,7 +86,7 @@ public void shouldForwardData() { } @Test - public void shouldDefineArgumentMismatchMessage() { + void shouldDefineArgumentMismatchMessage() { // given / when / then assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_CHANGE_EMAIL)); } diff --git a/src/test/java/fr/xephi/authme/command/executable/email/EmailBaseCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/EmailBaseCommandTest.java index 7ca0aff9c0..128bbd6acb 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/EmailBaseCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/EmailBaseCommandTest.java @@ -4,11 +4,11 @@ import fr.xephi.authme.command.FoundCommandResult; import fr.xephi.authme.command.help.HelpProvider; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -21,8 +21,8 @@ /** * Test for {@link EmailBaseCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class EmailBaseCommandTest { +@ExtendWith(MockitoExtension.class) +class EmailBaseCommandTest { @InjectMocks private EmailBaseCommand command; @@ -33,7 +33,7 @@ public class EmailBaseCommandTest { private CommandMapper commandMapper; @Test - public void shouldDisplayHelp() { + void shouldDisplayHelp() { // given CommandSender sender = mock(CommandSender.class); FoundCommandResult result = mock(FoundCommandResult.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/email/EmailSetPasswordCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/EmailSetPasswordCommandTest.java index a0338492e6..2563e764c7 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/EmailSetPasswordCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/EmailSetPasswordCommandTest.java @@ -9,12 +9,12 @@ import fr.xephi.authme.service.PasswordRecoveryService; import fr.xephi.authme.service.ValidationService; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -26,8 +26,8 @@ /** * Tests for {@link EmailSetPasswordCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class EmailSetPasswordCommandTest { +@ExtendWith(MockitoExtension.class) +class EmailSetPasswordCommandTest { @InjectMocks private EmailSetPasswordCommand command; @@ -47,13 +47,13 @@ public class EmailSetPasswordCommandTest { @Mock private ValidationService validationService; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldChangePassword() { + void shouldChangePassword() { // given Player player = mock(Player.class); String name = "Jerry"; @@ -75,7 +75,7 @@ public void shouldChangePassword() { } @Test - public void shouldRejectInvalidPassword() { + void shouldRejectInvalidPassword() { // given Player player = mock(Player.class); String name = "Morgan"; @@ -94,7 +94,7 @@ public void shouldRejectInvalidPassword() { } @Test - public void shouldDoNothingCantChangePass() { + void shouldDoNothingCantChangePass() { // given Player player = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/email/ProcessCodeCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/ProcessCodeCommandTest.java index b5790cc44e..e11161dc5d 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/ProcessCodeCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/ProcessCodeCommandTest.java @@ -5,11 +5,11 @@ import fr.xephi.authme.service.PasswordRecoveryService; import fr.xephi.authme.service.RecoveryCodeService; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -21,8 +21,8 @@ /** * Tests for {@link ProcessCodeCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ProcessCodeCommandTest { +@ExtendWith(MockitoExtension.class) +class ProcessCodeCommandTest { @InjectMocks private ProcessCodeCommand command; @@ -37,7 +37,7 @@ public class ProcessCodeCommandTest { private PasswordRecoveryService recoveryService; @Test - public void shouldSendErrorForInvalidRecoveryCode() { + void shouldSendErrorForInvalidRecoveryCode() { // given String name = "Vultur3"; Player sender = mock(Player.class); @@ -55,7 +55,7 @@ public void shouldSendErrorForInvalidRecoveryCode() { } @Test - public void shouldSendErrorForNoMoreTries() { + void shouldSendErrorForNoMoreTries() { // given String name = "BobbY"; Player sender = mock(Player.class); @@ -72,7 +72,7 @@ public void shouldSendErrorForNoMoreTries() { } @Test - public void shouldProcessCorrectCode() { + void shouldProcessCorrectCode() { // given String name = "Dwight"; String code = "chickenDinner"; diff --git a/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java index 06ce4ee5bb..8666d76f4a 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java @@ -1,35 +1,32 @@ package fr.xephi.authme.command.executable.email; import ch.jalu.datasourcecolumns.data.DataSourceValueImpl; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.message.MessageKey; -import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.PasswordRecoveryService; import fr.xephi.authme.service.RecoveryCodeService; -import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Locale; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -37,17 +34,14 @@ /** * Test for {@link RecoverEmailCommand}. */ -@RunWith(DelayedInjectionRunner.class) -public class RecoverEmailCommandTest { +@ExtendWith(MockitoExtension.class) +class RecoverEmailCommandTest { private static final String DEFAULT_EMAIL = "your@email.com"; - @InjectDelayed + @InjectMocks private RecoverEmailCommand command; - @Mock - private PasswordSecurity passwordSecurity; - @Mock private CommonService commonService; @@ -69,18 +63,13 @@ public class RecoverEmailCommandTest { @Mock private BukkitService bukkitService; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void initSettings() { - given(commonService.getProperty(SecuritySettings.EMAIL_RECOVERY_COOLDOWN_SECONDS)).willReturn(40); - } - @Test - public void shouldHandleMissingMailProperties() { + void shouldHandleMissingMailProperties() { // given given(emailService.hasAllInformation()).willReturn(false); Player sender = mock(Player.class); @@ -90,11 +79,11 @@ public void shouldHandleMissingMailProperties() { // then verify(commonService).send(sender, MessageKey.INCOMPLETE_EMAIL_SETTINGS); - verifyNoInteractions(dataSource, passwordSecurity); + verifyNoInteractions(dataSource); } @Test - public void shouldShowErrorForAuthenticatedUser() { + void shouldShowErrorForAuthenticatedUser() { // given String name = "Bobby"; Player sender = mock(Player.class); @@ -112,7 +101,7 @@ public void shouldShowErrorForAuthenticatedUser() { } @Test - public void shouldShowRegisterMessageForUnregisteredPlayer() { + void shouldShowRegisterMessageForUnregisteredPlayer() { // given String name = "Player123"; Player sender = mock(Player.class); @@ -132,7 +121,7 @@ public void shouldShowRegisterMessageForUnregisteredPlayer() { } @Test - public void shouldHandleDefaultEmail() { + void shouldHandleDefaultEmail() { // given String name = "Tract0r"; Player sender = mock(Player.class); @@ -152,7 +141,7 @@ public void shouldHandleDefaultEmail() { } @Test - public void shouldHandleInvalidEmailInput() { + void shouldHandleInvalidEmailInput() { // given String name = "Rapt0r"; Player sender = mock(Player.class); @@ -172,38 +161,32 @@ public void shouldHandleInvalidEmailInput() { } @Test - public void shouldGenerateRecoveryCode() { + void shouldGenerateRecoveryCode() { // given String name = "Vultur3"; Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); - given(emailService.sendRecoveryCode(anyString(), anyString(), anyString())).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); String email = "v@example.com"; given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.of(email)); - String code = "a94f37"; given(recoveryCodeService.isRecoveryCodeNeeded()).willReturn(true); - given(recoveryCodeService.generateCode(name)).willReturn(code); setBukkitServiceToRunTaskAsynchronously(bukkitService); // when command.executeCommand(sender, Collections.singletonList(email.toUpperCase(Locale.ROOT))); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); - verify(recoveryService).createAndSendRecoveryCode(sender, email); + verify(recoveryService, only()).createAndSendRecoveryCode(sender, email); } @Test - public void shouldGenerateNewPasswordWithoutRecoveryCode() { + void shouldGenerateNewPasswordWithoutRecoveryCode() { // given String name = "Vultur3"; Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); - given(emailService.sendPasswordMail(anyString(), anyString(), anyString())).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); String email = "vulture@example.com"; given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.of(email)); @@ -214,13 +197,11 @@ public void shouldGenerateNewPasswordWithoutRecoveryCode() { command.executeCommand(sender, Collections.singletonList(email)); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); - verify(recoveryService).generateAndSendNewPassword(sender, email); + verify(recoveryService, only()).generateAndSendNewPassword(sender, email); } @Test - public void shouldDefineArgumentMismatchMessage() { + void shouldDefineArgumentMismatchMessage() { // given / when / then assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_RECOVER_EMAIL)); } diff --git a/src/test/java/fr/xephi/authme/command/executable/email/ShowEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/ShowEmailCommandTest.java index 36e106ede0..2f14a529a9 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/ShowEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/ShowEmailCommandTest.java @@ -6,11 +6,11 @@ import fr.xephi.authme.service.CommonService; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -21,8 +21,8 @@ /** * Test for {@link ShowEmailCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ShowEmailCommandTest { +@ExtendWith(MockitoExtension.class) +class ShowEmailCommandTest { private static final String CURRENT_EMAIL = "my.email@example.com"; private static final String USERNAME = "name"; @@ -37,7 +37,7 @@ public class ShowEmailCommandTest { private PlayerCache playerCache; @Test - public void shouldShowCurrentEmailMessage() { + void shouldShowCurrentEmailMessage() { // given Player sender = mock(Player.class); given(sender.getName()).willReturn(USERNAME); @@ -52,7 +52,7 @@ public void shouldShowCurrentEmailMessage() { } @Test - public void shouldShowHiddenEmailMessage() { + void shouldShowHiddenEmailMessage() { // given Player sender = mock(Player.class); given(sender.getName()).willReturn(USERNAME); @@ -67,7 +67,7 @@ public void shouldShowHiddenEmailMessage() { } @Test - public void shouldReturnNoEmailMessage() { + void shouldReturnNoEmailMessage() { // given Player sender = mock(Player.class); given(sender.getName()).willReturn(USERNAME); diff --git a/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java index 7f6c66759c..7c7263297a 100644 --- a/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java @@ -5,17 +5,17 @@ import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +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.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -24,8 +24,8 @@ /** * Test for {@link LoginCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class LoginCommandTest { +@ExtendWith(MockitoExtension.class) +class LoginCommandTest { @InjectMocks private LoginCommand command; @@ -35,7 +35,7 @@ public class LoginCommandTest { @Test - public void shouldStopIfSenderIsNotAPlayer() { + void shouldStopIfSenderIsNotAPlayer() { // given CommandSender sender = mock(BlockCommandSender.class); @@ -48,7 +48,7 @@ public void shouldStopIfSenderIsNotAPlayer() { } @Test - public void shouldCallManagementForPlayerCaller() { + void shouldCallManagementForPlayerCaller() { // given Player sender = mock(Player.class); @@ -60,7 +60,7 @@ public void shouldCallManagementForPlayerCaller() { } @Test - public void shouldDefineArgumentMismatchMessage() { + void shouldDefineArgumentMismatchMessage() { // given / when / then assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_LOGIN)); } diff --git a/src/test/java/fr/xephi/authme/command/executable/logout/LogoutCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/logout/LogoutCommandTest.java index ba80d6ebbc..e61d0bf9b9 100644 --- a/src/test/java/fr/xephi/authme/command/executable/logout/LogoutCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/logout/LogoutCommandTest.java @@ -4,11 +4,11 @@ import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.Collections; @@ -22,8 +22,8 @@ /** * Test for {@link LogoutCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class LogoutCommandTest { +@ExtendWith(MockitoExtension.class) +class LogoutCommandTest { @InjectMocks private LogoutCommand command; @@ -33,7 +33,7 @@ public class LogoutCommandTest { @Test - public void shouldStopIfSenderIsNotAPlayer() { + void shouldStopIfSenderIsNotAPlayer() { // given CommandSender sender = mock(BlockCommandSender.class); @@ -46,7 +46,7 @@ public void shouldStopIfSenderIsNotAPlayer() { } @Test - public void shouldCallManagementForPlayerCaller() { + void shouldCallManagementForPlayerCaller() { // given Player sender = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java index cd695b65ac..15c3427cf0 100644 --- a/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java @@ -19,13 +19,13 @@ import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; @@ -43,8 +43,8 @@ /** * Test for {@link RegisterCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class RegisterCommandTest { +@ExtendWith(MockitoExtension.class) +class RegisterCommandTest { @InjectMocks private RegisterCommand command; @@ -64,22 +64,21 @@ public class RegisterCommandTest { @Mock private RegistrationCaptchaManager registrationCaptchaManager; - @BeforeClass - public static void setup() { + @BeforeAll + static void setup() { TestHelper.setupLogger(); } - @Before - public void linkMocksAndProvideSettingDefaults() { - given(commonService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.BCRYPT); - given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.PASSWORD); - given(commonService.getProperty(RegistrationSettings.REGISTER_SECOND_ARGUMENT)).willReturn(RegisterSecondaryArgument.NONE); + @BeforeEach + void setPasswordHashProperty() { + given(commonService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.BCRYPT); } @Test - public void shouldNotRunForNonPlayerSender() { + void shouldNotRunForNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); + commonService.getProperty(SecuritySettings.PASSWORD_HASH); // Prevent UnnecessaryStubbingException // when command.executeCommand(sender, Collections.emptyList()); @@ -90,7 +89,7 @@ public void shouldNotRunForNonPlayerSender() { } @Test - public void shouldForwardToManagementForTwoFactor() { + void shouldForwardToManagementForTwoFactor() { // given given(commonService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.TWO_FACTOR); Player player = mockPlayerWithName("test2"); @@ -106,7 +105,7 @@ public void shouldForwardToManagementForTwoFactor() { } @Test - public void shouldReturnErrorForEmptyArguments() { + void shouldReturnErrorForEmptyArguments() { // given Player player = mock(Player.class); @@ -119,7 +118,7 @@ public void shouldReturnErrorForEmptyArguments() { } @Test - public void shouldReturnErrorForMissingConfirmation() { + void shouldReturnErrorForMissingConfirmation() { // given given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.PASSWORD); given(commonService.getProperty(RegistrationSettings.REGISTER_SECOND_ARGUMENT)).willReturn(RegisterSecondaryArgument.CONFIRMATION); @@ -134,7 +133,7 @@ public void shouldReturnErrorForMissingConfirmation() { } @Test - public void shouldReturnErrorForMissingEmailConfirmation() { + void shouldReturnErrorForMissingEmailConfirmation() { // given given(emailService.hasAllInformation()).willReturn(true); given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.EMAIL); @@ -151,7 +150,7 @@ public void shouldReturnErrorForMissingEmailConfirmation() { } @Test - public void shouldThrowErrorForMissingEmailConfiguration() { + void shouldThrowErrorForMissingEmailConfiguration() { // given given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.EMAIL); given(emailService.hasAllInformation()).willReturn(false); @@ -167,7 +166,7 @@ public void shouldThrowErrorForMissingEmailConfiguration() { } @Test - public void shouldRejectInvalidEmail() { + void shouldRejectInvalidEmail() { // given String playerMail = "player@example.org"; given(validationService.validateEmail(playerMail)).willReturn(false); @@ -185,7 +184,7 @@ public void shouldRejectInvalidEmail() { } @Test - public void shouldRejectInvalidEmailConfirmation() { + void shouldRejectInvalidEmailConfirmation() { // given String playerMail = "bobber@bobby.org"; given(validationService.validateEmail(playerMail)).willReturn(true); @@ -204,7 +203,7 @@ public void shouldRejectInvalidEmailConfirmation() { } @Test - public void shouldPerformEmailRegistration() { + void shouldPerformEmailRegistration() { // given String playerMail = "asfd@lakjgre.lds"; given(validationService.validateEmail(playerMail)).willReturn(true); @@ -225,7 +224,7 @@ public void shouldPerformEmailRegistration() { } @Test - public void shouldRejectInvalidPasswordConfirmation() { + void shouldRejectInvalidPasswordConfirmation() { // given given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.PASSWORD); given(commonService.getProperty(RegistrationSettings.REGISTER_SECOND_ARGUMENT)).willReturn(RegisterSecondaryArgument.CONFIRMATION); @@ -240,9 +239,11 @@ public void shouldRejectInvalidPasswordConfirmation() { } @Test - public void shouldPerformPasswordRegistration() { + void shouldPerformPasswordRegistration() { // given Player player = mockPlayerWithName("newPlayer"); + given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.PASSWORD); + given(commonService.getProperty(RegistrationSettings.REGISTER_SECOND_ARGUMENT)).willReturn(RegisterSecondaryArgument.NONE); // when command.executeCommand(player, Collections.singletonList("myPass")); @@ -254,7 +255,7 @@ public void shouldPerformPasswordRegistration() { } @Test - public void shouldPerformMailValidationForPasswordWithEmail() { + void shouldPerformMailValidationForPasswordWithEmail() { // given given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.PASSWORD); given(commonService.getProperty(RegistrationSettings.REGISTER_SECOND_ARGUMENT)).willReturn(RegisterSecondaryArgument.EMAIL_MANDATORY); @@ -272,7 +273,7 @@ public void shouldPerformMailValidationForPasswordWithEmail() { } @Test - public void shouldStopForInvalidEmail() { + void shouldStopForInvalidEmail() { // given given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.PASSWORD); given(commonService.getProperty(RegistrationSettings.REGISTER_SECOND_ARGUMENT)).willReturn(RegisterSecondaryArgument.EMAIL_OPTIONAL); @@ -291,7 +292,7 @@ public void shouldStopForInvalidEmail() { } @Test - public void shouldPerformNormalPasswordRegisterForOneArgument() { + void shouldPerformNormalPasswordRegisterForOneArgument() { // given given(commonService.getProperty(RegistrationSettings.REGISTRATION_TYPE)).willReturn(RegistrationType.PASSWORD); given(commonService.getProperty(RegistrationSettings.REGISTER_SECOND_ARGUMENT)).willReturn(RegisterSecondaryArgument.EMAIL_OPTIONAL); @@ -307,8 +308,9 @@ public void shouldPerformNormalPasswordRegisterForOneArgument() { } @Test - public void shouldRequestCaptcha() { + void shouldRequestCaptcha() { // given + commonService.getProperty(SecuritySettings.PASSWORD_HASH); // Prevent UnnecessaryStubbingException given(registrationCaptchaManager.isCaptchaRequired(anyString())).willReturn(true); String name = "Brian"; Player player = mockPlayerWithName(name); diff --git a/src/test/java/fr/xephi/authme/command/executable/totp/AddTotpCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/totp/AddTotpCommandTest.java index 598200c584..b8d86d15a7 100644 --- a/src/test/java/fr/xephi/authme/command/executable/totp/AddTotpCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/totp/AddTotpCommandTest.java @@ -7,11 +7,11 @@ import fr.xephi.authme.security.totp.GenerateTotpService; import fr.xephi.authme.security.totp.TotpAuthenticator.TotpGenerationResult; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -23,8 +23,8 @@ /** * Test for {@link AddTotpCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class AddTotpCommandTest { +@ExtendWith(MockitoExtension.class) +class AddTotpCommandTest { @InjectMocks private AddTotpCommand addTotpCommand; @@ -37,7 +37,7 @@ public class AddTotpCommandTest { private Messages messages; @Test - public void shouldHandleNonLoggedInUser() { + void shouldHandleNonLoggedInUser() { // given Player player = mockPlayerWithName("bob"); given(playerCache.getAuth("bob")).willReturn(null); @@ -51,7 +51,7 @@ public void shouldHandleNonLoggedInUser() { } @Test - public void shouldNotAddCodeForAlreadyExistingTotp() { + void shouldNotAddCodeForAlreadyExistingTotp() { // given Player player = mockPlayerWithName("arend"); PlayerAuth auth = PlayerAuth.builder().name("arend") @@ -67,7 +67,7 @@ public void shouldNotAddCodeForAlreadyExistingTotp() { } @Test - public void shouldGenerateTotpCode() { + void shouldGenerateTotpCode() { // given Player player = mockPlayerWithName("charles"); PlayerAuth auth = PlayerAuth.builder().name("charles").build(); diff --git a/src/test/java/fr/xephi/authme/command/executable/totp/ConfirmTotpCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/totp/ConfirmTotpCommandTest.java index 4c3053647c..40c685751f 100644 --- a/src/test/java/fr/xephi/authme/command/executable/totp/ConfirmTotpCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/totp/ConfirmTotpCommandTest.java @@ -9,17 +9,17 @@ import fr.xephi.authme.security.totp.GenerateTotpService; import fr.xephi.authme.security.totp.TotpAuthenticator.TotpGenerationResult; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -32,8 +32,8 @@ /** * Test for {@link ConfirmTotpCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class ConfirmTotpCommandTest { +@ExtendWith(MockitoExtension.class) +class ConfirmTotpCommandTest { @InjectMocks private ConfirmTotpCommand command; @@ -47,13 +47,13 @@ public class ConfirmTotpCommandTest { @Mock private Messages messages; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldAddTotpCodeToUserAfterSuccessfulConfirmation() { + void shouldAddTotpCodeToUserAfterSuccessfulConfirmation() { // given Player player = mock(Player.class); String playerName = "George"; @@ -79,7 +79,7 @@ public void shouldAddTotpCodeToUserAfterSuccessfulConfirmation() { } @Test - public void shouldHandleWrongTotpCode() { + void shouldHandleWrongTotpCode() { // given Player player = mock(Player.class); String playerName = "George"; @@ -102,7 +102,7 @@ public void shouldHandleWrongTotpCode() { } @Test - public void shouldHandleMissingTotpKey() { + void shouldHandleMissingTotpKey() { // given Player player = mock(Player.class); String playerName = "George"; @@ -122,7 +122,7 @@ public void shouldHandleMissingTotpKey() { } @Test - public void shouldStopForAlreadyExistingTotpKeyOnAccount() { + void shouldStopForAlreadyExistingTotpKeyOnAccount() { // given Player player = mock(Player.class); String playerName = "George"; @@ -140,7 +140,7 @@ public void shouldStopForAlreadyExistingTotpKeyOnAccount() { } @Test - public void shouldHandleMissingAuthAccount() { + void shouldHandleMissingAuthAccount() { // given Player player = mock(Player.class); String playerName = "George"; diff --git a/src/test/java/fr/xephi/authme/command/executable/totp/RemoveTotpCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/totp/RemoveTotpCommandTest.java index 26c7e87195..4e2928257f 100644 --- a/src/test/java/fr/xephi/authme/command/executable/totp/RemoveTotpCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/totp/RemoveTotpCommandTest.java @@ -8,16 +8,16 @@ import fr.xephi.authme.message.Messages; import fr.xephi.authme.security.totp.TotpAuthenticator; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static java.util.Collections.singletonList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; @@ -27,8 +27,8 @@ /** * Test for {@link RemoveTotpCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class RemoveTotpCommandTest { +@ExtendWith(MockitoExtension.class) +class RemoveTotpCommandTest { @InjectMocks private RemoveTotpCommand command; @@ -42,13 +42,13 @@ public class RemoveTotpCommandTest { @Mock private Messages messages; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldRemoveTotpKey() { + void shouldRemoveTotpKey() { // given String name = "aws"; PlayerAuth auth = PlayerAuth.builder().name(name).totpKey("some-totp-key").build(); @@ -70,7 +70,7 @@ public void shouldRemoveTotpKey() { } @Test - public void shouldHandleDatabaseError() { + void shouldHandleDatabaseError() { // given String name = "aws"; PlayerAuth auth = PlayerAuth.builder().name(name).totpKey("some-totp-key").build(); @@ -91,7 +91,7 @@ public void shouldHandleDatabaseError() { } @Test - public void shouldHandleInvalidCode() { + void shouldHandleInvalidCode() { // given String name = "cesar"; PlayerAuth auth = PlayerAuth.builder().name(name).totpKey("some-totp-key").build(); @@ -111,7 +111,7 @@ public void shouldHandleInvalidCode() { } @Test - public void shouldHandleUserWithoutTotpKey() { + void shouldHandleUserWithoutTotpKey() { // given String name = "cesar"; PlayerAuth auth = PlayerAuth.builder().name(name).build(); @@ -130,7 +130,7 @@ public void shouldHandleUserWithoutTotpKey() { } @Test - public void shouldHandleNonLoggedInUser() { + void shouldHandleNonLoggedInUser() { // given String name = "cesar"; given(playerCache.getAuth(name)).willReturn(null); diff --git a/src/test/java/fr/xephi/authme/command/executable/totp/TotpBaseCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/totp/TotpBaseCommandTest.java index 0e279f6874..a37de3a8d1 100644 --- a/src/test/java/fr/xephi/authme/command/executable/totp/TotpBaseCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/totp/TotpBaseCommandTest.java @@ -4,11 +4,11 @@ import fr.xephi.authme.command.FoundCommandResult; import fr.xephi.authme.command.help.HelpProvider; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -19,8 +19,8 @@ /** * Test for {@link TotpBaseCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class TotpBaseCommandTest { +@ExtendWith(MockitoExtension.class) +class TotpBaseCommandTest { @InjectMocks private TotpBaseCommand command; @@ -31,7 +31,7 @@ public class TotpBaseCommandTest { private HelpProvider helpProvider; @Test - public void shouldOutputHelp() { + void shouldOutputHelp() { // given CommandSender sender = mock(CommandSender.class); FoundCommandResult mappingResult = mock(FoundCommandResult.class); diff --git a/src/test/java/fr/xephi/authme/command/executable/unregister/UnregisterCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/unregister/UnregisterCommandTest.java index a0fc8d3d17..40aa085cfe 100644 --- a/src/test/java/fr/xephi/authme/command/executable/unregister/UnregisterCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/unregister/UnregisterCommandTest.java @@ -7,17 +7,17 @@ import fr.xephi.authme.service.CommonService; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +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.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -27,8 +27,8 @@ /** * Test for {@link UnregisterCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class UnregisterCommandTest { +@ExtendWith(MockitoExtension.class) +class UnregisterCommandTest { @InjectMocks private UnregisterCommand command; @@ -46,7 +46,7 @@ public class UnregisterCommandTest { private VerificationCodeManager codeManager; @Test - public void shouldCatchUnauthenticatedUser() { + void shouldCatchUnauthenticatedUser() { // given String password = "mySecret123"; String name = "player77"; @@ -64,7 +64,7 @@ public void shouldCatchUnauthenticatedUser() { } @Test - public void shouldStopForMissingVerificationCode() { + void shouldStopForMissingVerificationCode() { // given String name = "asldjf"; Player player = mock(Player.class); @@ -83,7 +83,7 @@ public void shouldStopForMissingVerificationCode() { } @Test - public void shouldForwardDataToAsyncTask() { + void shouldForwardDataToAsyncTask() { // given String password = "p@ssw0rD"; String name = "jas0n_"; @@ -102,7 +102,7 @@ public void shouldForwardDataToAsyncTask() { } @Test - public void shouldStopIfSenderIsNotPlayer() { + void shouldStopIfSenderIsNotPlayer() { // given CommandSender sender = mock(CommandSender.class); @@ -115,7 +115,7 @@ public void shouldStopIfSenderIsNotPlayer() { } @Test - public void shouldDefineArgumentMismatchMessage() { + void shouldDefineArgumentMismatchMessage() { // given / when / then assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_UNREGISTER)); } diff --git a/src/test/java/fr/xephi/authme/command/executable/verification/VerificationCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/verification/VerificationCommandTest.java index d4b38f1ad4..cf6a3fbb14 100644 --- a/src/test/java/fr/xephi/authme/command/executable/verification/VerificationCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/verification/VerificationCommandTest.java @@ -5,17 +5,17 @@ import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.service.CommonService; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -23,8 +23,8 @@ /** * Test for {@link VerificationCommand}. */ -@RunWith(MockitoJUnitRunner.class) -public class VerificationCommandTest { +@ExtendWith(MockitoExtension.class) +class VerificationCommandTest { @InjectMocks private VerificationCommand command; @@ -35,13 +35,13 @@ public class VerificationCommandTest { @Mock private VerificationCodeManager codeManager; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldDetectIfMailHasASetup() { + void shouldDetectIfMailHasASetup() { // given String name = "Alligator"; Player player = mockPlayerWithName(name); @@ -55,7 +55,7 @@ public void shouldDetectIfMailHasASetup() { } @Test - public void shouldRequireAndAcceptCode() { + void shouldRequireAndAcceptCode() { // given String name = "Duck"; String code = "123932"; @@ -76,7 +76,7 @@ public void shouldRequireAndAcceptCode() { } @Test - public void shouldRejectCode() { + void shouldRejectCode() { // given String name = "Spider"; String code = "98345222"; // more than 6 digits @@ -97,7 +97,7 @@ public void shouldRejectCode() { } @Test - public void shouldRejectVerificationDueToExpiration() { + void shouldRejectVerificationDueToExpiration() { // given String name = "Dog"; String code = "131552"; @@ -116,7 +116,7 @@ public void shouldRejectVerificationDueToExpiration() { } @Test - public void shouldRejectVerificationDueToVerifiedIdentity() { + void shouldRejectVerificationDueToVerifiedIdentity() { // given String name = "Cow"; String code = "973583"; @@ -135,7 +135,7 @@ public void shouldRejectVerificationDueToVerifiedIdentity() { } @Test - public void shouldRejectVerificationDueToUndefinedEmail() { + void shouldRejectVerificationDueToUndefinedEmail() { // given String name = "Frog"; String code = "774543"; @@ -155,7 +155,7 @@ public void shouldRejectVerificationDueToUndefinedEmail() { } @Test - public void shouldDefineArgumentMismatchMessage() { + void shouldDefineArgumentMismatchMessage() { // given / when / then assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_VERIFICATION_CODE)); } diff --git a/src/test/java/fr/xephi/authme/command/help/HelpMessageAndHelpSectionConsistencyTest.java b/src/test/java/fr/xephi/authme/command/help/HelpMessageAndHelpSectionConsistencyTest.java index 02a42ba998..6920633427 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpMessageAndHelpSectionConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpMessageAndHelpSectionConsistencyTest.java @@ -1,22 +1,22 @@ package fr.xephi.authme.command.help; import fr.xephi.authme.util.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +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<>(); diff --git a/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java b/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java index 019e6c8630..c508603ba2 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpMessagesConsistencyTest.java @@ -9,28 +9,28 @@ import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; 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.junit.Assert.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); diff --git a/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java b/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java index 514724a979..1c874c552d 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java @@ -5,46 +5,42 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.TestCommandsUtil; -import fr.xephi.authme.message.AbstractMessageFileHandler; import fr.xephi.authme.message.HelpMessagesFileHandler; import fr.xephi.authme.message.MessagePathHelper; import fr.xephi.authme.permission.DefaultPermission; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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.junit.Assert.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; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private File dataFolder; + @TempDir + File dataFolder; - @Before - public void initializeHandler() throws IOException { - dataFolder = temporaryFolder.newFolder(); + @BeforeEach + void initializeHandler() throws IOException { new File(dataFolder, "messages").mkdirs(); File messagesFile = new File(dataFolder, MessagePathHelper.createHelpMessageFilePath("test")); Files.copy(TestHelper.getJarFile(TEST_FILE), messagesFile); @@ -54,7 +50,7 @@ public void initializeHandler() throws IOException { } @Test - public void shouldReturnLocalizedCommand() { + void shouldReturnLocalizedCommand() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "authme", "register"); @@ -74,7 +70,7 @@ public void shouldReturnLocalizedCommand() { } @Test - public void shouldReturnLocalizedCommandWithDefaults() { + void shouldReturnLocalizedCommandWithDefaults() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "authme", "login"); @@ -90,7 +86,7 @@ public void shouldReturnLocalizedCommandWithDefaults() { } @Test - public void shouldReturnSameCommandForNoLocalization() { + void shouldReturnSameCommandForNoLocalization() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "email"); @@ -102,7 +98,7 @@ public void shouldReturnSameCommandForNoLocalization() { } @Test - public void shouldKeepChildrenInLocalCommand() { + void shouldKeepChildrenInLocalCommand() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "authme"); @@ -116,7 +112,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.")); @@ -124,7 +120,7 @@ public void shouldGetTranslationsForSectionAndMessage() { } @Test - public void shouldGetLocalCommandDescription() { + void shouldGetLocalCommandDescription() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "authme", "register"); @@ -136,7 +132,7 @@ public void shouldGetLocalCommandDescription() { } @Test - public void shouldFallbackToDescriptionOnCommandObject() { + void shouldFallbackToDescriptionOnCommandObject() { // given CommandDescription command = getCommandWithLabel(COMMANDS, "unregister"); @@ -151,9 +147,7 @@ private HelpMessagesFileHandler createMessagesFileHandler() { Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); - HelpMessagesFileHandler messagesFileHandler = ReflectionTestUtils.newInstance(HelpMessagesFileHandler.class); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "settings", settings); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "dataFolder", dataFolder); + HelpMessagesFileHandler messagesFileHandler = new HelpMessagesFileHandler(dataFolder, settings); ReflectionTestUtils.invokePostConstructMethods(messagesFileHandler); return messagesFileHandler; } diff --git a/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java b/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java index 8852387fa8..eca09739f5 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.command.help; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.FoundCommandResult; import fr.xephi.authme.command.FoundResultStatus; @@ -12,12 +9,14 @@ import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Mock; import org.mockito.internal.stubbing.answers.ReturnsArgumentAt; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collection; @@ -35,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.junit.Assert.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; @@ -51,12 +51,11 @@ /** * Test for {@link HelpProvider}. */ -@RunWith(DelayedInjectionRunner.class) -public class HelpProviderTest { +@ExtendWith(MockitoExtension.class) +class HelpProviderTest { private static Collection commands; - @InjectDelayed private HelpProvider helpProvider; @Mock private PermissionsManager permissionsManager; @@ -65,18 +64,19 @@ public class HelpProviderTest { @Mock private CommandSender sender; - @BeforeClass - public static void setUpCommands() { + @BeforeAll + 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")); @@ -95,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")); @@ -113,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")); @@ -129,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")); @@ -143,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")); @@ -165,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")); @@ -187,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")); @@ -201,7 +201,7 @@ public void shouldNotShowAnythingForEmptyPermissions() { } @Test - public void shouldNotShowAnythingForNullPermissionsOnCommand() { + void shouldNotShowAnythingForNullPermissionsOnCommand() { // given CommandDescription command = mock(CommandDescription.class); given(command.getPermission()).willReturn(null); @@ -217,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")); @@ -234,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")); @@ -248,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")); @@ -269,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")); @@ -283,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); @@ -302,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")); @@ -318,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"); @@ -331,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"); @@ -344,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(""); @@ -368,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(""); @@ -385,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"); @@ -401,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")); @@ -444,22 +444,22 @@ private static List getLines(CommandSender sender) { } private static void setDefaultHelpMessages(HelpMessagesService helpMessagesService) { - given(helpMessagesService.buildLocalizedDescription(any(CommandDescription.class))) - .willAnswer(new ReturnsArgumentAt(0)); + 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)); } } diff --git a/src/test/java/fr/xephi/authme/data/QuickCommandsProtectionManagerTest.java b/src/test/java/fr/xephi/authme/data/QuickCommandsProtectionManagerTest.java index 704075674d..bb912aa308 100644 --- a/src/test/java/fr/xephi/authme/data/QuickCommandsProtectionManagerTest.java +++ b/src/test/java/fr/xephi/authme/data/QuickCommandsProtectionManagerTest.java @@ -5,21 +5,21 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ProtectionSettings; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link QuickCommandsProtectionManager}. */ -@RunWith(MockitoJUnitRunner.class) -public class QuickCommandsProtectionManagerTest { +@ExtendWith(MockitoExtension.class) +class QuickCommandsProtectionManagerTest { @Mock private Settings settings; @@ -28,7 +28,7 @@ public class QuickCommandsProtectionManagerTest { private PermissionsManager permissionsManager; @Test - public void shouldAllowCommand() { + void shouldAllowCommand() { // given String playername = "PlayerName"; Player player = mockPlayerWithName(playername); @@ -50,7 +50,7 @@ public void shouldAllowCommand() { } @Test - public void shouldDenyCommand() { + void shouldDenyCommand() { // given String name = "TestName1"; Player player = mockPlayerWithName(name); diff --git a/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java b/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java index a186920a54..38a9095943 100644 --- a/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java +++ b/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java @@ -9,11 +9,11 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.expiring.TimedCounter; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Calendar; import java.util.Date; @@ -21,10 +21,10 @@ import java.util.Map; 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.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -34,8 +34,8 @@ /** * Test for {@link TempbanManager}. */ -@RunWith(MockitoJUnitRunner.class) -public class TempbanManagerTest { +@ExtendWith(MockitoExtension.class) +class TempbanManagerTest { private static final long DATE_TOLERANCE_MILLISECONDS = 200L; private static final long TEST_EXPIRATION_THRESHOLD = 120_000L; @@ -47,7 +47,7 @@ public class TempbanManagerTest { private Messages messages; @Test - public void shouldAddCounts() { + void shouldAddCounts() { // given Settings settings = mockSettings(3, 60, ""); TempbanManager manager = new TempbanManager(bukkitService, messages, settings); @@ -67,7 +67,7 @@ public void shouldAddCounts() { } @Test - public void shouldIncreaseAndResetCount() { + void shouldIncreaseAndResetCount() { // given String address = "192.168.1.2"; Settings settings = mockSettings(3, 60, ""); @@ -91,7 +91,7 @@ public void shouldIncreaseAndResetCount() { } @Test - public void shouldNotIncreaseCountForDisabledTempban() { + void shouldNotIncreaseCountForDisabledTempban() { // given String address = "192.168.1.3"; Settings settings = mockSettings(1, 5, ""); @@ -107,7 +107,7 @@ public void shouldNotIncreaseCountForDisabledTempban() { } @Test - public void shouldNotCheckCountIfTempbanIsDisabled() { + void shouldNotCheckCountIfTempbanIsDisabled() { // given String address = "192.168.1.4"; Settings settings = mockSettings(1, 5, ""); @@ -128,7 +128,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); @@ -143,7 +143,7 @@ public void shouldNotIssueBanIfDisabled() { } @Test - public void shouldBanPlayerIp() { + void shouldBanPlayerIp() { // given Player player = mock(Player.class); String ip = "123.45.67.89"; @@ -170,7 +170,7 @@ public void shouldBanPlayerIp() { } @Test - public void shouldBanPlayerIpCustom() { + void shouldBanPlayerIpCustom() { // given Player player = mock(Player.class); given(player.getName()).willReturn("Bob"); @@ -189,7 +189,7 @@ public void shouldBanPlayerIpCustom() { } @Test - public void shouldResetCountAfterBan() { + void shouldResetCountAfterBan() { // given Player player = mock(Player.class); String ip = "22.44.66.88"; @@ -212,7 +212,7 @@ public void shouldResetCountAfterBan() { } @Test - public void shouldPerformCleanup() { + void shouldPerformCleanup() { // given Map> counts = new HashMap<>(); TimedCounter counter1 = mockCounter(); diff --git a/src/test/java/fr/xephi/authme/data/VerificationCodeManagerTest.java b/src/test/java/fr/xephi/authme/data/VerificationCodeManagerTest.java index 147b0dd057..105a6d55a6 100644 --- a/src/test/java/fr/xephi/authme/data/VerificationCodeManagerTest.java +++ b/src/test/java/fr/xephi/authme/data/VerificationCodeManagerTest.java @@ -8,14 +8,14 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; @@ -25,8 +25,8 @@ /** * Test for {@link VerificationCodeManager}. */ -@RunWith(MockitoJUnitRunner.class) -public class VerificationCodeManagerTest { +@ExtendWith(MockitoExtension.class) +class VerificationCodeManagerTest { @Mock private Settings settings; @@ -40,15 +40,15 @@ public class VerificationCodeManagerTest { @Mock private PermissionsManager permissionsManager; - @Before - public void setUpBasicBehavior() { - given(emailService.hasAllInformation()).willReturn(true); + @BeforeEach + 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")); @@ -71,7 +71,7 @@ public void shouldRequireVerification() { } @Test - public void shouldNotRequireVerificationIfEmailSettingsAreIncomplete() { + void shouldNotRequireVerificationIfEmailSettingsAreIncomplete() { // given given(emailService.hasAllInformation()).willReturn(false); VerificationCodeManager codeManager = createCodeManager(); @@ -86,8 +86,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(); @@ -102,8 +103,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)); @@ -121,8 +123,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)); @@ -140,8 +143,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"; diff --git a/src/test/java/fr/xephi/authme/data/auth/PlayerAuthTest.java b/src/test/java/fr/xephi/authme/data/auth/PlayerAuthTest.java index 360abdc986..679dc52a0e 100644 --- a/src/test/java/fr/xephi/authme/data/auth/PlayerAuthTest.java +++ b/src/test/java/fr/xephi/authme/data/auth/PlayerAuthTest.java @@ -1,19 +1,19 @@ package fr.xephi.authme.data.auth; -import org.junit.Test; +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.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * 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") diff --git a/src/test/java/fr/xephi/authme/data/captcha/LoginCaptchaManagerTest.java b/src/test/java/fr/xephi/authme/data/captcha/LoginCaptchaManagerTest.java index 3197634581..e612bd8bb0 100644 --- a/src/test/java/fr/xephi/authme/data/captcha/LoginCaptchaManagerTest.java +++ b/src/test/java/fr/xephi/authme/data/captcha/LoginCaptchaManagerTest.java @@ -5,24 +5,24 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.expiring.TimedCounter; import org.bukkit.entity.Player; -import org.junit.Test; +import org.junit.jupiter.api.Test; 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.junit.Assert.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); diff --git a/src/test/java/fr/xephi/authme/data/captcha/RegistrationCaptchaManagerTest.java b/src/test/java/fr/xephi/authme/data/captcha/RegistrationCaptchaManagerTest.java index 4a71ab2ca1..a0ef35bcac 100644 --- a/src/test/java/fr/xephi/authme/data/captcha/RegistrationCaptchaManagerTest.java +++ b/src/test/java/fr/xephi/authme/data/captcha/RegistrationCaptchaManagerTest.java @@ -5,21 +5,21 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.expiring.ExpiringMap; import org.bukkit.entity.Player; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; 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); diff --git a/src/test/java/fr/xephi/authme/data/limbo/AllowFlightRestoreTypeTest.java b/src/test/java/fr/xephi/authme/data/limbo/AllowFlightRestoreTypeTest.java index eb7ee38936..efc7d75196 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/AllowFlightRestoreTypeTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/AllowFlightRestoreTypeTest.java @@ -1,7 +1,7 @@ package fr.xephi.authme.data.limbo; import org.bukkit.entity.Player; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -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; diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java index 5cbbb1ffe7..b9fcdf4a51 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboPlayerTaskManagerTest.java @@ -13,21 +13,21 @@ import fr.xephi.authme.task.TimeoutTask; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +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.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; @@ -39,8 +39,8 @@ /** * Test for {@link LimboPlayerTaskManager}. */ -@RunWith(MockitoJUnitRunner.class) -public class LimboPlayerTaskManagerTest { +@ExtendWith(MockitoExtension.class) +class LimboPlayerTaskManagerTest { @InjectMocks private LimboPlayerTaskManager limboPlayerTaskManager; @@ -60,13 +60,13 @@ public class LimboPlayerTaskManagerTest { @Mock private RegistrationCaptchaManager registrationCaptchaManager; - @BeforeClass - public static void setupLogger() { + @BeforeAll + static void setupLogger() { TestHelper.setupLogger(); } @Test - public void shouldRegisterMessageTask() { + void shouldRegisterMessageTask() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -86,7 +86,7 @@ public void shouldRegisterMessageTask() { } @Test - public void shouldNotScheduleTaskForZeroAsInterval() { + void shouldNotScheduleTaskForZeroAsInterval() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -101,7 +101,7 @@ public void shouldNotScheduleTaskForZeroAsInterval() { } @Test - public void shouldCancelExistingMessageTask() { + void shouldCancelExistingMessageTask() { // given String name = "rats"; Player player = mock(Player.class); @@ -124,7 +124,7 @@ public void shouldCancelExistingMessageTask() { } @Test - public void shouldInitializeMessageTaskWithCaptchaMessage() { + void shouldInitializeMessageTaskWithCaptchaMessage() { // given String name = "race"; Player player = mock(Player.class); @@ -145,7 +145,7 @@ public void shouldInitializeMessageTaskWithCaptchaMessage() { } @Test - public void shouldRegisterTimeoutTask() { + void shouldRegisterTimeoutTask() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -163,7 +163,7 @@ public void shouldRegisterTimeoutTask() { } @Test - public void shouldNotRegisterTimeoutTaskForZeroTimeout() { + void shouldNotRegisterTimeoutTaskForZeroTimeout() { // given Player player = mock(Player.class); LimboPlayer limboPlayer = mock(LimboPlayer.class); @@ -177,7 +177,7 @@ public void shouldNotRegisterTimeoutTaskForZeroTimeout() { } @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); diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java index 418ce698cc..f2d4a99f78 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceHelperTest.java @@ -2,18 +2,18 @@ import fr.xephi.authme.TestHelper; import org.bukkit.Location; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -22,19 +22,19 @@ *

* Note: some methods are tested directly where they are used via {@link LimboServiceTest}. */ -@RunWith(MockitoJUnitRunner.class) -public class LimboServiceHelperTest { +@ExtendWith(MockitoExtension.class) +class LimboServiceHelperTest { @InjectMocks private LimboServiceHelper limboServiceHelper; - @BeforeClass - public static void initLogger() { + @BeforeAll + 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); @@ -54,7 +54,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); @@ -73,7 +73,7 @@ public void shouldFallBackToNewLimboForMissingData() { } @Test - public void shouldHandleNullInputs() { + void shouldHandleNullInputs() { // given LimboPlayer limbo = mock(LimboPlayer.class); diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java index 44839c13bd..1584285247 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java @@ -1,7 +1,5 @@ package fr.xephi.authme.data.limbo; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.persistence.LimboPersistence; @@ -12,25 +10,28 @@ import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.Location; import org.bukkit.entity.Player; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Arrays; import java.util.Collections; import java.util.Map; +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.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; 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; @@ -39,13 +40,13 @@ /** * Test for {@link LimboService}, and {@link LimboServiceHelper}. */ -@RunWith(DelayedInjectionRunner.class) -public class LimboServiceTest { +@ExtendWith(MockitoExtension.class) +class LimboServiceTest { - @InjectDelayed + @InjectMocks private LimboService limboService; - @InjectDelayed + @InjectMocks private LimboServiceHelper limboServiceHelper; @Mock @@ -66,18 +67,18 @@ public class LimboServiceTest { @Mock private AuthGroupHandler authGroupHandler; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } - @Before - public void mockSettings() { - given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); + @BeforeEach + 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); @@ -85,6 +86,7 @@ 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); // when limboService.createLimboPlayer(player, true); @@ -109,13 +111,14 @@ 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); // when limboService.createLimboPlayer(player, false); @@ -140,12 +143,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); @@ -159,10 +163,9 @@ public void shouldClearTasksOnAlreadyExistingLimbo() { } @Test - public void shouldRestoreData() { + void shouldRestoreData() { // given - LimboPlayer limbo = Mockito.spy(convertToLimboPlayer( - newPlayer("John", true, 0.4f, false, 0.0f), null, Collections.emptyList())); + LimboPlayer limbo = Mockito.spy(newLimboPlayer(null, true, true, 0.4f, 0.0f)); getLimboMap().put("john", limbo); Player player = newPlayer("John", false, 0.2f, false, 0.7f); @@ -184,7 +187,7 @@ public void shouldRestoreData() { } @Test - public void shouldHandleMissingLimboPlayerWhileRestoring() { + void shouldHandleMissingLimboPlayerWhileRestoring() { // given Player player = newPlayer("Test"); @@ -197,7 +200,7 @@ public void shouldHandleMissingLimboPlayerWhileRestoring() { } @Test - public void shouldReplaceTasks() { + void shouldReplaceTasks() { // given LimboPlayer limbo = mock(LimboPlayer.class); getLimboMap().put("jeff", limbo); @@ -214,7 +217,7 @@ public void shouldReplaceTasks() { } @Test - public void shouldHandleMissingLimboForReplaceTasks() { + void shouldHandleMissingLimboForReplaceTasks() { // given Player player = newPlayer("ghost"); @@ -234,16 +237,16 @@ private static Player newPlayer(String name) { 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; } - private static LimboPlayer convertToLimboPlayer(Player player, Location location, Collection groups) { - return new LimboPlayer(location, player.isOp(), groups, player.getAllowFlight(), - player.getWalkSpeed(), player.getFlySpeed()); + private static LimboPlayer newLimboPlayer(Location location, boolean isOp, + boolean allowFlight, float walkSpeed, float flySpeed, UserGroup... groups) { + return new LimboPlayer(location, isOp, Arrays.asList(groups), allowFlight, walkSpeed, flySpeed); } private Map getLimboMap() { diff --git a/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java b/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java index f8aa2719c7..110665b08b 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/WalkFlySpeedRestoreTypeTest.java @@ -1,13 +1,11 @@ package fr.xephi.authme.data.limbo; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; import static fr.xephi.authme.data.limbo.LimboPlayer.DEFAULT_FLY_SPEED; import static fr.xephi.authme.data.limbo.LimboPlayer.DEFAULT_WALK_SPEED; @@ -22,17 +20,11 @@ /** * Test for {@link WalkFlySpeedRestoreType}. */ -@RunWith(Parameterized.class) -public class WalkFlySpeedRestoreTypeTest { +class WalkFlySpeedRestoreTypeTest { - private final TestParameters parameters; - - public WalkFlySpeedRestoreTypeTest(TestParameters parameters) { - this.parameters = parameters; - } - - @Test - public void shouldRestoreToExpectedValue() { + @ParameterizedTest + @MethodSource("buildParams") + void shouldRestoreToExpectedValue(TestParameters parameters) { // given LimboPlayer limbo = mock(LimboPlayer.class); given(limbo.getWalkSpeed()).willReturn(parameters.givenLimboWalkSpeed); @@ -50,10 +42,9 @@ public void shouldRestoreToExpectedValue() { verify(player).setWalkSpeed(parameters.expectedWalkSpeed); verify(player).setFlySpeed(parameters.expectedFlySpeed); } - - @Parameterized.Parameters(name = "{0}") - public static List buildParams() { - List parameters = Arrays.asList( + + 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), create(MAX_RESTORE).withLimbo(0.3f, 0.8f).withPlayer(0.5f, 0.2f).expect(0.5f, 0.8f), @@ -62,9 +53,6 @@ public static List buildParams() { create(RESTORE_NO_ZERO).withLimbo(0.0f, 0.005f).withPlayer(0.4f, 0.8f).expect(DEFAULT_WALK_SPEED, DEFAULT_FLY_SPEED), create(DEFAULT).withLimbo(0.1f, 0.7f).withPlayer(0.4f, 0.0f).expect(DEFAULT_WALK_SPEED, DEFAULT_FLY_SPEED) ); - - // Convert List to List - return parameters.stream().map(p -> new Object[]{p}).collect(Collectors.toList()); } private static TestParameters create(WalkFlySpeedRestoreType testedType) { diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java index f223bdf1c1..096b7d6eb6 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java @@ -1,13 +1,9 @@ package fr.xephi.authme.data.limbo.persistence; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -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; @@ -15,12 +11,13 @@ import org.bukkit.World; import org.bukkit.entity.Player; import org.hamcrest.Matcher; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +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.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -38,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}. */ -@RunWith(DelayedInjectionRunner.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"); @@ -73,29 +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; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @BeforeClass - public static void initLogger() { + @BeforeAll + 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(); @@ -108,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")); @@ -133,7 +128,7 @@ public void shouldMigrateOldSegmentFilesOnStartup() { } @Test - public void shouldRemovePlayer() { + void shouldRemovePlayer() { // given Player playerToRemove = mockPlayerWithUuid(UUID_STAFF); Player unknownPlayerToRemove = mockPlayerWithUuid(UNKNOWN_UUID); @@ -153,7 +148,7 @@ public void shouldRemovePlayer() { } @Test - public void shouldAddPlayer() { + void shouldAddPlayer() { // given Player uuidToAdd1 = mockPlayerWithUuid(UNKNOWN_UUID); Location location1 = mockLocation("1world"); @@ -181,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"); diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java index 77af856773..bef336ce90 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java @@ -1,22 +1,19 @@ package fr.xephi.authme.data.limbo.persistence; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; 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.util.FileUtils; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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; @@ -24,48 +21,45 @@ 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.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link IndividualFilesPersistenceHandler}. */ -@RunWith(DelayedInjectionRunner.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; + @TempDir + File dataFolder; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @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 +86,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 +99,7 @@ public void shouldReturnNullForUnavailablePlayer() { } @Test - public void shouldSavePlayerData() { + void shouldSavePlayerData() { // given Player player = mock(Player.class); UUID uuid = UUID.nameUUIDFromBytes("New player".getBytes()); diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java index b9ac1cd813..9b89a71edc 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java @@ -1,9 +1,6 @@ package fr.xephi.authme.data.limbo.persistence; import ch.jalu.injector.factory.Factory; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.LimboPlayer; @@ -11,13 +8,16 @@ import fr.xephi.authme.settings.properties.LimboSettings; import org.bukkit.entity.Player; import org.hamcrest.Matcher; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -25,7 +25,6 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -37,10 +36,9 @@ /** * Test for {@link LimboPersistence}. */ -@RunWith(DelayedInjectionRunner.class) -public class LimboPersistenceTest { +@ExtendWith(MockitoExtension.class) +class LimboPersistenceTest { - @InjectDelayed private LimboPersistence limboPersistence; @Mock @@ -49,27 +47,28 @@ public class LimboPersistenceTest { @Mock private Settings settings; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + 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(invocation.getArgument(0))); + .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(); @@ -89,7 +88,7 @@ public void shouldDelegateToHandler() { } @Test - public void shouldReloadProperly() { + void shouldReloadProperly() { // given given(settings.getProperty(LimboSettings.LIMBO_PERSISTENCE_TYPE)) .willReturn(LimboPersistenceType.INDIVIDUAL_FILES); @@ -102,7 +101,7 @@ public void shouldReloadProperly() { } @Test - public void shouldHandleExceptionWhenGettingLimbo() { + void shouldHandleExceptionWhenGettingLimbo() { // given Player player = mock(Player.class); Logger logger = TestHelper.setupLogger(); @@ -118,7 +117,7 @@ public void shouldHandleExceptionWhenGettingLimbo() { } @Test - public void shouldHandleExceptionWhenSavingLimbo() { + void shouldHandleExceptionWhenSavingLimbo() { // given Player player = mock(Player.class); LimboPlayer limbo = mock(LimboPlayer.class); @@ -134,7 +133,7 @@ public void shouldHandleExceptionWhenSavingLimbo() { } @Test - public void shouldHandleExceptionWhenRemovingLimbo() { + void shouldHandleExceptionWhenRemovingLimbo() { // given Player player = mock(Player.class); Logger logger = TestHelper.setupLogger(); diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTypeTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTypeTest.java index 248ab9c143..487e05ce15 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTypeTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTypeTest.java @@ -1,23 +1,23 @@ package fr.xephi.authme.data.limbo.persistence; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * 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()); diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java index d5cf31a9df..a0289e3999 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java @@ -1,6 +1,6 @@ package fr.xephi.authme.data.limbo.persistence; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; @@ -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.junit.Assert.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); diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentSizeTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentSizeTest.java index 1cc34693c5..4ecee772f6 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentSizeTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentSizeTest.java @@ -1,7 +1,7 @@ package fr.xephi.authme.data.limbo.persistence; import com.google.common.collect.ImmutableSet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; @@ -9,15 +9,15 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * 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<>(); diff --git a/src/test/java/fr/xephi/authme/datasource/AbstractDataSourceIntegrationTest.java b/src/test/java/fr/xephi/authme/datasource/AbstractDataSourceIntegrationTest.java index a5e50cb964..3caae01788 100644 --- a/src/test/java/fr/xephi/authme/datasource/AbstractDataSourceIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/datasource/AbstractDataSourceIntegrationTest.java @@ -5,7 +5,7 @@ import com.google.common.collect.Lists; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.security.crypts.HashedPassword; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashSet; @@ -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.junit.Assert.assertThat; -import static org.junit.Assume.assumeThat; /** * 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")); - assumeThat(dataSource.getAccountsRegistered(), equalTo(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(); diff --git a/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java index 5b2dca5885..33a11f5b5a 100644 --- a/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/AbstractResourceClosingTest.java @@ -5,10 +5,9 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.security.crypts.HashedPassword; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -44,36 +43,21 @@ * 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)}). */ -@RunWith(Parameterized.class) 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; - /** - * Constructor for the test instance verifying the given method. - * - * @param method The DataSource method to test - * @param name The name of the method - */ - public AbstractResourceClosingTest(Method method, String name) { - // Note ljacqu 20160227: The name parameter is necessary as we pass it from the @Parameters method; - // we use the method name in the annotation to name the test sensibly - this.method = method; - } - @BeforeClass - public static void initializeLogger() { + @BeforeAll + static void initializeLogger() { TestHelper.setupLogger(); } @@ -81,10 +65,13 @@ public static void initializeLogger() { * The actual test -- executes the method given through the constructor and then verifies that all * AutoCloseable mocks it constructed have been closed. */ - @Test - public void shouldCloseResources() throws IllegalAccessException, InvocationTargetException { + @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(); @@ -92,7 +79,7 @@ public void shouldCloseResources() throws IllegalAccessException, InvocationTarg /** * 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() + "'"); } @@ -202,27 +189,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; }; } diff --git a/src/test/java/fr/xephi/authme/datasource/AbstractSqlDataSourceResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/AbstractSqlDataSourceResourceClosingTest.java index 4443c54c74..fd83fb70b3 100644 --- a/src/test/java/fr/xephi/authme/datasource/AbstractSqlDataSourceResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/AbstractSqlDataSourceResourceClosingTest.java @@ -3,8 +3,7 @@ import com.google.common.collect.ImmutableSet; import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.Settings; -import org.junit.BeforeClass; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; import java.lang.reflect.Method; import java.sql.Connection; @@ -27,12 +26,8 @@ public abstract class AbstractSqlDataSourceResourceClosingTest extends AbstractR private static Settings settings; - AbstractSqlDataSourceResourceClosingTest(Method method, String name) { - super(method, name); - } - - @BeforeClass - public static void initializeSettings() { + @BeforeAll + static void initializeSettings() { settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); TestHelper.setupLogger(); @@ -54,8 +49,7 @@ protected DataSource getObjectUnderTest() { * * @return Test parameters */ - @Parameterized.Parameters(name = "{1}") - public static Collection data() { + public static Collection createParameters() { List methods = getDataSourceMethods(); List data = new ArrayList<>(); for (Method method : methods) { diff --git a/src/test/java/fr/xephi/authme/datasource/MySqlIntegrationTest.java b/src/test/java/fr/xephi/authme/datasource/MySqlIntegrationTest.java index 027608230e..5978fca375 100644 --- a/src/test/java/fr/xephi/authme/datasource/MySqlIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/datasource/MySqlIntegrationTest.java @@ -6,9 +6,9 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterEach; +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; @@ -35,8 +35,8 @@ public class MySqlIntegrationTest extends AbstractDataSourceIntegrationTest { /** * Set up the settings mock to return specific values for database settings and load {@link #sqlInitialize}. */ - @BeforeClass - public static void initializeSettings() throws IOException, ClassNotFoundException { + @BeforeAll + static void initializeSettings() throws IOException, ClassNotFoundException { // Check that we have an H2 driver Class.forName("org.h2.jdbcx.JdbcDataSource"); @@ -50,8 +50,8 @@ public static void initializeSettings() throws IOException, ClassNotFoundExcepti sqlInitialize = new String(Files.readAllBytes(sqlInitFile)); } - @Before - public void initializeConnectionAndTable() throws SQLException { + @BeforeEach + void initializeConnectionAndTable() throws SQLException { HikariConfig config = new HikariConfig(); config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); config.setConnectionTestQuery("VALUES 1"); @@ -70,8 +70,8 @@ public void initializeConnectionAndTable() throws SQLException { hikariSource = ds; } - @After - public void closeConnection() { + @AfterEach + void closeConnection() { silentClose(hikariSource); } diff --git a/src/test/java/fr/xephi/authme/datasource/MySqlResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/MySqlResourceClosingTest.java index 3500560b57..fcc75643cc 100644 --- a/src/test/java/fr/xephi/authme/datasource/MySqlResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/MySqlResourceClosingTest.java @@ -5,7 +5,6 @@ import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; import fr.xephi.authme.settings.Settings; -import java.lang.reflect.Method; import java.sql.Connection; import static org.mockito.ArgumentMatchers.any; @@ -15,11 +14,7 @@ /** * Resource closing test for {@link MySQL}. */ -public class MySqlResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { - - public MySqlResourceClosingTest(Method method, String name) { - super(method, name); - } +class MySqlResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { @Override protected DataSource createDataSource(Settings settings, Connection connection) throws Exception { diff --git a/src/test/java/fr/xephi/authme/datasource/PostgreSqlIntegrationTest.java b/src/test/java/fr/xephi/authme/datasource/PostgreSqlIntegrationTest.java index 54a00bf409..6d5afb53d9 100644 --- a/src/test/java/fr/xephi/authme/datasource/PostgreSqlIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/datasource/PostgreSqlIntegrationTest.java @@ -6,9 +6,9 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterEach; +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; @@ -35,8 +35,8 @@ public class PostgreSqlIntegrationTest extends AbstractDataSourceIntegrationTest /** * Set up the settings mock to return specific values for database settings and load {@link #sqlInitialize}. */ - @BeforeClass - public static void initializeSettings() throws IOException, ClassNotFoundException { + @BeforeAll + static void initializeSettings() throws IOException, ClassNotFoundException { // Check that we have an H2 driver Class.forName("org.h2.jdbcx.JdbcDataSource"); @@ -50,8 +50,8 @@ public static void initializeSettings() throws IOException, ClassNotFoundExcepti sqlInitialize = new String(Files.readAllBytes(sqlInitFile)); } - @Before - public void initializeConnectionAndTable() throws SQLException { + @BeforeEach + void initializeConnectionAndTable() throws SQLException { HikariConfig config = new HikariConfig(); config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); config.setConnectionTestQuery("VALUES 1"); @@ -68,8 +68,8 @@ public void initializeConnectionAndTable() throws SQLException { hikariSource = ds; } - @After - public void closeConnection() { + @AfterEach + void closeConnection() { silentClose(hikariSource); } diff --git a/src/test/java/fr/xephi/authme/datasource/PostgreSqlResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/PostgreSqlResourceClosingTest.java index 40a1d391f1..56e7cb1008 100644 --- a/src/test/java/fr/xephi/authme/datasource/PostgreSqlResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/PostgreSqlResourceClosingTest.java @@ -5,7 +5,6 @@ import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; import fr.xephi.authme.settings.Settings; -import java.lang.reflect.Method; import java.sql.Connection; import static org.mockito.ArgumentMatchers.any; @@ -15,11 +14,7 @@ /** * Resource closing test for {@link PostgreSqlDataSource}. */ -public class PostgreSqlResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { - - public PostgreSqlResourceClosingTest(Method method, String name) { - super(method, name); - } +class PostgreSqlResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { @Override protected DataSource createDataSource(Settings settings, Connection connection) throws Exception { @@ -29,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/src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java b/src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java index 06e60eeb6e..3675a71863 100644 --- a/src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/datasource/SQLiteIntegrationTest.java @@ -5,10 +5,10 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.DatabaseSettings; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +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 java.io.IOException; import java.nio.file.Files; @@ -18,15 +18,15 @@ import java.sql.SQLException; import java.sql.Statement; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; 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; @@ -38,8 +38,8 @@ public class SQLiteIntegrationTest extends AbstractDataSourceIntegrationTest { /** * Set up the settings mock to return specific values for database settings and load {@link #sqlInitialize}. */ - @BeforeClass - public static void initializeSettings() throws IOException, ClassNotFoundException { + @BeforeAll + static void initializeSettings() throws IOException, ClassNotFoundException { // Check that we have an implementation for SQLite Class.forName("org.sqlite.JDBC"); @@ -55,8 +55,8 @@ public static void initializeSettings() throws IOException, ClassNotFoundExcepti sqlInitialize = new String(Files.readAllBytes(sqlInitFile)).split(";(\\r?)\\n"); } - @Before - public void initializeConnectionAndTable() throws SQLException { + @BeforeEach + void initializeConnectionAndTable() throws SQLException { Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:"); try (Statement st = connection.createStatement()) { st.execute("DROP TABLE IF EXISTS authme"); @@ -67,13 +67,13 @@ public void initializeConnectionAndTable() throws SQLException { con = connection; } - @After - public void closeConnection() { + @AfterEach + 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 diff --git a/src/test/java/fr/xephi/authme/datasource/SQLiteResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/SQLiteResourceClosingTest.java index 2c8fe5dc15..8fd6779baa 100644 --- a/src/test/java/fr/xephi/authme/datasource/SQLiteResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/SQLiteResourceClosingTest.java @@ -2,21 +2,15 @@ import fr.xephi.authme.settings.Settings; -import java.lang.reflect.Method; import java.sql.Connection; /** * Resource closing test for {@link SQLite}. */ -public class SQLiteResourceClosingTest extends AbstractSqlDataSourceResourceClosingTest { - - public SQLiteResourceClosingTest(Method method, String name) { - super(method, name); - } +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/src/test/java/fr/xephi/authme/datasource/SqLiteMigraterIntegrationTest.java b/src/test/java/fr/xephi/authme/datasource/SqLiteMigraterIntegrationTest.java index b95a0b814c..bb014cfd17 100644 --- a/src/test/java/fr/xephi/authme/datasource/SqLiteMigraterIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/datasource/SqLiteMigraterIntegrationTest.java @@ -5,10 +5,10 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.settings.Settings; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -20,43 +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.junit.Assert.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; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Before - public void setup() throws SQLException, IOException, NoSuchMethodException { + @BeforeEach + 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(); diff --git a/src/test/java/fr/xephi/authme/datasource/SqlDataSourceUtilsTest.java b/src/test/java/fr/xephi/authme/datasource/SqlDataSourceUtilsTest.java index ae29740851..db75a7bbdd 100644 --- a/src/test/java/fr/xephi/authme/datasource/SqlDataSourceUtilsTest.java +++ b/src/test/java/fr/xephi/authme/datasource/SqlDataSourceUtilsTest.java @@ -1,18 +1,19 @@ package fr.xephi.authme.datasource; import fr.xephi.authme.TestHelper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.DatabaseMetaData; import java.sql.ResultSet; 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.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -21,17 +22,17 @@ /** * Test for {@link SqlDataSourceUtils}. */ -public class SqlDataSourceUtilsTest { +class SqlDataSourceUtilsTest { private Logger logger; - @Before - public void initLogger() { + @BeforeEach + void initLogger() { logger = TestHelper.setupLogger(); } @Test - public void shouldLogException() { + void shouldLogException() { // given String msg = "Hocus pocus did not work"; SQLException ex = new SQLException(msg); @@ -44,7 +45,7 @@ public void shouldLogException() { } @Test - public void shouldFetchNullableStatus() throws SQLException { + void shouldFetchNullableStatus() throws SQLException { // given String tableName = "data"; String columnName = "category"; @@ -62,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"; @@ -79,8 +80,8 @@ public void shouldReturnFalseForUnknownNullableStatus() throws SQLException { assertThat(result, equalTo(false)); } - @Test(expected = IllegalStateException.class) - public void shouldThrowForUnknownColumnInNullableCheck() throws SQLException { + @Test + void shouldThrowForUnknownColumnInNullableCheck() throws SQLException { // given String tableName = "data"; String columnName = "unknown"; @@ -89,14 +90,13 @@ public void shouldThrowForUnknownColumnInNullableCheck() throws SQLException { DatabaseMetaData metaData = mock(DatabaseMetaData.class); given(metaData.getColumns(null, null, tableName, columnName)).willReturn(resultSet); - // when - SqlDataSourceUtils.isNotNullColumn(metaData, tableName, columnName); - - // then - expect exception + // 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"; @@ -113,8 +113,8 @@ public void shouldGetDefaultValue() throws SQLException { assertThat(defaultValue, equalTo("Literature")); } - @Test(expected = IllegalStateException.class) - public void shouldThrowForUnknownColumnInDefaultValueRetrieval() throws SQLException { + @Test + void shouldThrowForUnknownColumnInDefaultValueRetrieval() throws SQLException { // given String tableName = "data"; String columnName = "unknown"; @@ -123,14 +123,13 @@ public void shouldThrowForUnknownColumnInDefaultValueRetrieval() throws SQLExcep DatabaseMetaData metaData = mock(DatabaseMetaData.class); given(metaData.getColumns(null, null, tableName, columnName)).willReturn(resultSet); - // when - SqlDataSourceUtils.getColumnDefaultValue(metaData, tableName, columnName); - - // then - expect exception + // 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"; diff --git a/src/test/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverterTest.java b/src/test/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverterTest.java index 5dd0324444..22db89cf43 100644 --- a/src/test/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverterTest.java +++ b/src/test/java/fr/xephi/authme/datasource/converter/AbstractDataSourceConverterTest.java @@ -5,8 +5,8 @@ import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSourceType; import org.bukkit.command.CommandSender; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Arrays; @@ -28,15 +28,15 @@ /** * Test for {@link AbstractDataSourceConverter}. */ -public class AbstractDataSourceConverterTest { +class AbstractDataSourceConverterTest { - @BeforeClass - public static void initLogger() { + @BeforeAll + 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/src/test/java/fr/xephi/authme/datasource/converter/CrazyLoginConverterTest.java b/src/test/java/fr/xephi/authme/datasource/converter/CrazyLoginConverterTest.java index 8819772de1..0b82dde202 100644 --- a/src/test/java/fr/xephi/authme/datasource/converter/CrazyLoginConverterTest.java +++ b/src/test/java/fr/xephi/authme/datasource/converter/CrazyLoginConverterTest.java @@ -1,27 +1,26 @@ package fr.xephi.authme.datasource.converter; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ConverterSettings; import org.bukkit.command.CommandSender; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.util.List; import static fr.xephi.authme.AuthMeMatchers.equalToHash; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -32,10 +31,9 @@ /** * Test for {@link CrazyLoginConverter}. */ -@RunWith(DelayedInjectionRunner.class) -public class CrazyLoginConverterTest { +@ExtendWith(MockitoExtension.class) +class CrazyLoginConverterTest { - @InjectDelayed private CrazyLoginConverter crazyLoginConverter; @Mock @@ -44,16 +42,20 @@ public class CrazyLoginConverterTest { @Mock private Settings settings; - @DataFolder private File dataFolder = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "/datasource/converter/"); - @BeforeClass - public static void initializeLogger() { + @BeforeAll + static void initializeLogger() { TestHelper.setupLogger(); } + @BeforeEach + void initConverter() { + crazyLoginConverter = new CrazyLoginConverter(dataFolder, dataSource, settings); + } + @Test - public void shouldImportUsers() { + void shouldImportUsers() { // given given(settings.getProperty(ConverterSettings.CRAZYLOGIN_FILE_NAME)).willReturn("crazylogin.db"); CommandSender sender = mock(CommandSender.class); @@ -72,7 +74,7 @@ public void shouldImportUsers() { } @Test - public void shouldStopForNonExistentFile() { + void shouldStopForNonExistentFile() { // given given(settings.getProperty(ConverterSettings.CRAZYLOGIN_FILE_NAME)).willReturn("invalid-file"); CommandSender sender = mock(CommandSender.class); diff --git a/src/test/java/fr/xephi/authme/datasource/converter/LoginSecurityConverterTest.java b/src/test/java/fr/xephi/authme/datasource/converter/LoginSecurityConverterTest.java index 54201fb719..db598be02c 100644 --- a/src/test/java/fr/xephi/authme/datasource/converter/LoginSecurityConverterTest.java +++ b/src/test/java/fr/xephi/authme/datasource/converter/LoginSecurityConverterTest.java @@ -1,21 +1,20 @@ package fr.xephi.authme.datasource.converter; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ConverterSettings; import org.bukkit.command.CommandSender; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -26,11 +25,11 @@ import static fr.xephi.authme.AuthMeMatchers.equalToHash; import static fr.xephi.authme.AuthMeMatchers.hasAuthLocation; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -39,27 +38,31 @@ /** * Test for {@link LoginSecurityConverter}. */ -@RunWith(DelayedInjectionRunner.class) -public class LoginSecurityConverterTest { +@ExtendWith(MockitoExtension.class) +class LoginSecurityConverterTest { - @InjectDelayed private LoginSecurityConverter converter; @Mock private DataSource dataSource; @Mock private Settings settings; - @DataFolder + private File dataFolder = new File("."); // not used but required for injection - @BeforeInjecting - public void initMocks() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); + } + + @BeforeEach + void setUpConverter() { given(settings.getProperty(ConverterSettings.LOGINSECURITY_USE_SQLITE)).willReturn(true); + converter = new LoginSecurityConverter(dataFolder, dataSource, settings); } @Test - public void shouldConvertFromSqlite() throws SQLException { + void shouldConvertFromSqlite() throws SQLException { // given Connection connection = converter.createSqliteConnection( TestHelper.TEST_RESOURCES_FOLDER + TestHelper.PROJECT_ROOT + "datasource/converter/LoginSecurity.db"); @@ -94,7 +97,7 @@ public void shouldConvertFromSqlite() throws SQLException { // For H2 it looks like Date#getTime returns the millis of the date at 12AM in the system's timezone, // so we check with a margin of 12 hours to cover most cases... @Test - public void shouldConvertFromMySql() throws IOException, SQLException { + void shouldConvertFromMySql() throws IOException, SQLException { // given Connection connection = initializeMySqlTable(); CommandSender sender = mock(CommandSender.class); diff --git a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/AbstractMySqlExtensionResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/AbstractMySqlExtensionResourceClosingTest.java index 3089e8b999..3c8889e468 100644 --- a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/AbstractMySqlExtensionResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/AbstractMySqlExtensionResourceClosingTest.java @@ -4,10 +4,8 @@ import fr.xephi.authme.datasource.AbstractResourceClosingTest; import fr.xephi.authme.datasource.Columns; import fr.xephi.authme.settings.Settings; -import org.junit.BeforeClass; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; -import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; @@ -23,12 +21,8 @@ public abstract class AbstractMySqlExtensionResourceClosingTest extends Abstract private static Settings settings; private static Columns columns; - public AbstractMySqlExtensionResourceClosingTest(Method method, String name) { - super(method, name); - } - - @BeforeClass - public static void initSettings() { + @BeforeAll + static void initSettings() { settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); columns = new Columns(settings); @@ -41,7 +35,6 @@ protected MySqlExtension getObjectUnderTest() { protected abstract MySqlExtension createExtension(Settings settings, Columns columns); - @Parameterized.Parameters(name = "{1}") public static List createParameters() { return Arrays.stream(MySqlExtension.class.getDeclaredMethods()) .filter(m -> Modifier.isPublic(m.getModifiers())) diff --git a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/Ipb4ExtensionResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/Ipb4ExtensionResourceClosingTest.java index 8629a6a7d7..e2398f13a7 100644 --- a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/Ipb4ExtensionResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/Ipb4ExtensionResourceClosingTest.java @@ -3,16 +3,10 @@ import fr.xephi.authme.datasource.Columns; import fr.xephi.authme.settings.Settings; -import java.lang.reflect.Method; - /** * Resource closing test for {@link Ipb4Extension}. */ -public class Ipb4ExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { - - public Ipb4ExtensionResourceClosingTest(Method method, String name) { - super(method, name); - } +class Ipb4ExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { @Override protected MySqlExtension createExtension(Settings settings, Columns columns) { diff --git a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/NoOpExtensionTest.java b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/NoOpExtensionTest.java index 40f98247f9..0317401fc4 100644 --- a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/NoOpExtensionTest.java +++ b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/NoOpExtensionTest.java @@ -5,10 +5,10 @@ import fr.xephi.authme.datasource.Columns; import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.settings.Settings; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +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; @@ -19,13 +19,13 @@ /** * Test for {@link NoOpExtension}. */ -@RunWith(MockitoJUnitRunner.class) -public class NoOpExtensionTest { +@ExtendWith(MockitoExtension.class) +class NoOpExtensionTest { private NoOpExtension extension; - @Before - public void createExtension() { + @BeforeEach + void createExtension() { Settings settings = mock(Settings.class); TestHelper.returnDefaultsForAllProperties(settings); Columns columns = new Columns(settings); @@ -33,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); diff --git a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/PhpBbExtensionResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/PhpBbExtensionResourceClosingTest.java index d1f43e1f45..64a252c966 100644 --- a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/PhpBbExtensionResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/PhpBbExtensionResourceClosingTest.java @@ -3,16 +3,10 @@ import fr.xephi.authme.datasource.Columns; import fr.xephi.authme.settings.Settings; -import java.lang.reflect.Method; - /** * Resource closing test for {@link PhpBbExtension}. */ -public class PhpBbExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { - - public PhpBbExtensionResourceClosingTest(Method method, String name) { - super(method, name); - } +class PhpBbExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { @Override protected MySqlExtension createExtension(Settings settings, Columns columns) { diff --git a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/WordpressExtensionResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/WordpressExtensionResourceClosingTest.java index 1ee141ffe0..62e737dc88 100644 --- a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/WordpressExtensionResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/WordpressExtensionResourceClosingTest.java @@ -3,16 +3,10 @@ import fr.xephi.authme.datasource.Columns; import fr.xephi.authme.settings.Settings; -import java.lang.reflect.Method; - /** * Resource closing test for {@link WordpressExtension}. */ -public class WordpressExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { - - public WordpressExtensionResourceClosingTest(Method method, String name) { - super(method, name); - } +class WordpressExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { @Override protected MySqlExtension createExtension(Settings settings, Columns columns) { diff --git a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/XfBcryptExtensionResourceClosingTest.java b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/XfBcryptExtensionResourceClosingTest.java index 7da4fb198b..aa7f3ab4f3 100644 --- a/src/test/java/fr/xephi/authme/datasource/mysqlextensions/XfBcryptExtensionResourceClosingTest.java +++ b/src/test/java/fr/xephi/authme/datasource/mysqlextensions/XfBcryptExtensionResourceClosingTest.java @@ -3,16 +3,10 @@ import fr.xephi.authme.datasource.Columns; import fr.xephi.authme.settings.Settings; -import java.lang.reflect.Method; - /** * Resource closing test for {@link XfBcryptExtension}. */ -public class XfBcryptExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { - - public XfBcryptExtensionResourceClosingTest(Method method, String name) { - super(method, name); - } +class XfBcryptExtensionResourceClosingTest extends AbstractMySqlExtensionResourceClosingTest { @Override protected MySqlExtension createExtension(Settings settings, Columns columns) { diff --git a/src/test/java/fr/xephi/authme/events/EventsConsistencyTest.java b/src/test/java/fr/xephi/authme/events/EventsConsistencyTest.java index bb722d3ef7..0830361772 100644 --- a/src/test/java/fr/xephi/authme/events/EventsConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/events/EventsConsistencyTest.java @@ -3,27 +3,27 @@ import fr.xephi.authme.ClassCollector; import fr.xephi.authme.TestHelper; import org.bukkit.event.Event; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; 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.junit.Assert.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; - @BeforeClass - public static void scanEventClasses() { + @BeforeAll + 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 { diff --git a/src/test/java/fr/xephi/authme/initialization/TaskCloserTest.java b/src/test/java/fr/xephi/authme/initialization/TaskCloserTest.java index 16613c1348..89d1b9d7b7 100644 --- a/src/test/java/fr/xephi/authme/initialization/TaskCloserTest.java +++ b/src/test/java/fr/xephi/authme/initialization/TaskCloserTest.java @@ -9,12 +9,12 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitWorker; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.List; @@ -22,8 +22,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doNothing; @@ -35,8 +35,8 @@ /** * Test for {@link TaskCloser}. */ -@RunWith(MockitoJUnitRunner.class) -public class TaskCloserTest { +@ExtendWith(MockitoExtension.class) +class TaskCloserTest { private static final int[] ACTIVE_WORKERS_ID = {2, 5}; @@ -50,8 +50,8 @@ public class TaskCloserTest { @Mock private DataSource dataSource; - @Before - public void initAuthMe() { + @BeforeEach + void initAuthMe() { Server server = mock(Server.class); given(server.getScheduler()).willReturn(bukkitScheduler); ReflectionTestUtils.setField(JavaPlugin.class, authMe, "server", server); @@ -60,7 +60,7 @@ public void initAuthMe() { } @Test - public void shouldWaitForTasksToClose() throws InterruptedException { + void shouldWaitForTasksToClose() throws InterruptedException { // given doNothing().when(taskCloser).sleep(); // avoid sleeping in tests mockActiveWorkers(); @@ -82,7 +82,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(); @@ -101,18 +101,15 @@ 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(); - executor.submit(new Runnable() { - @Override - public void run() { - try { - shouldStopForInterruptedThread0(); - } catch (Exception e) { - throw new IllegalStateException(e); - } + executor.submit(() -> { + try { + shouldStopForInterruptedThread0(); + } catch (Exception e) { + throw new IllegalStateException(e); } }).get(); } @@ -137,19 +134,41 @@ private void shouldStopForInterruptedThread0() throws InterruptedException { private void mockActiveWorkers() { Plugin otherOwner = mock(Plugin.class); List tasks = Arrays.asList( - mockBukkitWorker(authMe, ACTIVE_WORKERS_ID[0], false), - mockBukkitWorker(otherOwner, 3, false), - mockBukkitWorker(authMe, ACTIVE_WORKERS_ID[1], false), - mockBukkitWorker(authMe, 7, true), - mockBukkitWorker(otherOwner, 11, true)); + new BukkitWorkerTestImpl(authMe, ACTIVE_WORKERS_ID[0]), + new BukkitWorkerTestImpl(otherOwner, 3), + new BukkitWorkerTestImpl(authMe, ACTIVE_WORKERS_ID[1]), + new BukkitWorkerTestImpl(authMe, 7), + new BukkitWorkerTestImpl(otherOwner, 11)); given(bukkitScheduler.getActiveWorkers()).willReturn(tasks); + given(bukkitScheduler.isQueued(anyInt())).willAnswer(invocation -> { + int taskId = invocation.getArgument(0); + return taskId == 7 || taskId == 11; + }); } - private BukkitWorker mockBukkitWorker(Plugin owner, int taskId, boolean isQueued) { - BukkitWorker worker = mock(BukkitWorker.class); - given(worker.getOwner()).willReturn(owner); - given(worker.getTaskId()).willReturn(taskId); - given(bukkitScheduler.isQueued(taskId)).willReturn(isQueued); - return worker; + private static class BukkitWorkerTestImpl implements BukkitWorker { + + private final Plugin owner; + private final int taskId; + + BukkitWorkerTestImpl(Plugin owner, int taskId) { + this.owner = owner; + this.taskId = taskId; + } + + @Override + public int getTaskId() { + return taskId; + } + + @Override + public Plugin getOwner() { + return owner; + } + + @Override + public Thread getThread() { + return null; + } } } diff --git a/src/test/java/fr/xephi/authme/listener/BlockListenerTest.java b/src/test/java/fr/xephi/authme/listener/BlockListenerTest.java index 6925343a43..e82b9e1474 100644 --- a/src/test/java/fr/xephi/authme/listener/BlockListenerTest.java +++ b/src/test/java/fr/xephi/authme/listener/BlockListenerTest.java @@ -3,11 +3,11 @@ import org.bukkit.entity.Player; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -17,8 +17,8 @@ /** * Test for {@link BlockListener}. */ -@RunWith(MockitoJUnitRunner.class) -public class BlockListenerTest { +@ExtendWith(MockitoExtension.class) +class BlockListenerTest { @InjectMocks private BlockListener listener; @@ -27,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); @@ -43,7 +43,7 @@ public void shouldAllowPlaceEvent() { } @Test - public void shouldDenyPlaceEvent() { + void shouldDenyPlaceEvent() { // given Player player = mock(Player.class); BlockPlaceEvent event = mock(BlockPlaceEvent.class); @@ -60,7 +60,7 @@ public void shouldDenyPlaceEvent() { } @Test - public void shouldAllowBreakEvent() { + void shouldAllowBreakEvent() { // given Player player = mock(Player.class); BlockBreakEvent event = mock(BlockBreakEvent.class); @@ -76,7 +76,7 @@ public void shouldAllowBreakEvent() { } @Test - public void shouldDenyBreakEvent() { + void shouldDenyBreakEvent() { // given Player player = mock(Player.class); BlockBreakEvent event = mock(BlockBreakEvent.class); diff --git a/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java b/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java index ce9fabb072..e56353f84d 100644 --- a/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java +++ b/src/test/java/fr/xephi/authme/listener/EntityListenerTest.java @@ -12,15 +12,15 @@ import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.projectiles.ProjectileSource; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.listener.EventCancelVerifier.withServiceMock; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -32,8 +32,8 @@ /** * Test for {@link EntityListener}. */ -@RunWith(MockitoJUnitRunner.class) -public class EntityListenerTest { +@ExtendWith(MockitoExtension.class) +class EntityListenerTest { @InjectMocks private EntityListener listener; @@ -42,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) @@ -51,7 +51,7 @@ public void shouldHandleSimpleEvents() { } @Test - public void shouldCancelRegainHealthEvent() { + void shouldCancelRegainHealthEvent() { // given EntityRegainHealthEvent event = mock(EntityRegainHealthEvent.class); given(listenerService.shouldCancelEvent(event)).willReturn(true); @@ -66,7 +66,7 @@ public void shouldCancelRegainHealthEvent() { } @Test - public void shouldNotCancelRegainedHealth() { + void shouldNotCancelRegainedHealth() { // given EntityRegainHealthEvent event = mock(EntityRegainHealthEvent.class); given(listenerService.shouldCancelEvent(event)).willReturn(false); @@ -80,7 +80,7 @@ public void shouldNotCancelRegainedHealth() { } @Test - public void shouldCancelEntityDamageByEntityEvent() { + void shouldCancelEntityDamageByEntityEvent() { // given EntityDamageByEntityEvent event = mock(EntityDamageByEntityEvent.class); Entity player = mock(Player.class); @@ -96,7 +96,7 @@ public void shouldCancelEntityDamageByEntityEvent() { } @Test - public void shouldNotCancelEntityDamageByEntityEvent() { + void shouldNotCancelEntityDamageByEntityEvent() { // given EntityDamageByEntityEvent event = mock(EntityDamageByEntityEvent.class); Entity player = mock(Player.class); @@ -112,7 +112,7 @@ public void shouldNotCancelEntityDamageByEntityEvent() { } @Test - public void shouldCancelEntityDamageEvent() { + void shouldCancelEntityDamageEvent() { // given EntityDamageEvent event = mock(EntityDamageEvent.class); Entity entity = mock(Entity.class); @@ -130,7 +130,7 @@ public void shouldCancelEntityDamageEvent() { } @Test - public void shouldNotCancelEntityDamageEvent() { + void shouldNotCancelEntityDamageEvent() { // given EntityDamageEvent event = mock(EntityDamageEvent.class); given(listenerService.shouldCancelEvent(event)).willReturn(false); @@ -144,7 +144,7 @@ public void shouldNotCancelEntityDamageEvent() { } @Test - public void shouldAllowProjectileLaunchFromNonHuman() { + void shouldAllowProjectileLaunchFromNonHuman() { // given Projectile projectile = mock(Projectile.class); ProjectileSource source = mock(ProjectileSource.class); @@ -161,7 +161,7 @@ public void shouldAllowProjectileLaunchFromNonHuman() { } @Test - public void shouldAllowProjectileLaunchFromAuthedHuman() { + void shouldAllowProjectileLaunchFromAuthedHuman() { // given Projectile projectile = mock(Projectile.class); Player player = mock(Player.class); @@ -179,7 +179,7 @@ public void shouldAllowProjectileLaunchFromAuthedHuman() { } @Test - public void shouldRejectProjectileLaunchFromUnauthed() { + void shouldRejectProjectileLaunchFromUnauthed() { // given Projectile projectile = mock(Projectile.class); Player player = mock(Player.class); @@ -197,7 +197,7 @@ public void shouldRejectProjectileLaunchFromUnauthed() { } @Test - public void shouldHandleOldShooterMethod() { + void shouldHandleOldShooterMethod() { // given Projectile projectile = mock(Projectile.class); Player shooter = mock(Player.class); @@ -214,7 +214,7 @@ public void shouldHandleOldShooterMethod() { } @Test - public void shouldCancelEntityTargetEvent() { + void shouldCancelEntityTargetEvent() { // given EntityTargetEvent event = mock(EntityTargetEvent.class); Entity target = mock(Entity.class); @@ -230,7 +230,7 @@ public void shouldCancelEntityTargetEvent() { } @Test - public void shouldNotCancelEntityTargetEvent() { + void shouldNotCancelEntityTargetEvent() { // given EntityTargetEvent event = mock(EntityTargetEvent.class); Entity target = mock(Entity.class); diff --git a/src/test/java/fr/xephi/authme/listener/ListenerConsistencyTest.java b/src/test/java/fr/xephi/authme/listener/ListenerConsistencyTest.java index 7f320516e3..c953f80fca 100644 --- a/src/test/java/fr/xephi/authme/listener/ListenerConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/listener/ListenerConsistencyTest.java @@ -6,8 +6,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -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.junit.Assert.assertThat; -import static org.junit.Assert.fail; +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; - @BeforeClass - public static void collectListenerClasses() { + @BeforeAll + 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()) { diff --git a/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java b/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java index 76877fcace..76cc97e8d1 100644 --- a/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java +++ b/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.listener; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -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; @@ -13,12 +10,14 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.entity.EntityEvent; import org.bukkit.event.player.PlayerEvent; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; 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}. */ -@RunWith(DelayedInjectionRunner.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); } diff --git a/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java b/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java index 3667e1bea1..13e33895fa 100644 --- a/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java +++ b/src/test/java/fr/xephi/authme/listener/OnJoinVerifierTest.java @@ -20,22 +20,22 @@ import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -45,8 +45,8 @@ /** * Test for {@link OnJoinVerifier}. */ -@RunWith(MockitoJUnitRunner.class) -public class OnJoinVerifierTest { +@ExtendWith(MockitoExtension.class) +class OnJoinVerifierTest { @InjectMocks private OnJoinVerifier onJoinVerifier; @@ -68,16 +68,13 @@ public class OnJoinVerifierTest { @Mock private Server server; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldNotDoAnythingForNormalEvent() { + void shouldNotDoAnythingForNormalEvent() { // given PlayerLoginEvent event = mock(PlayerLoginEvent.class); given(event.getResult()).willReturn(PlayerLoginEvent.Result.ALLOWED); @@ -93,7 +90,7 @@ public void shouldNotDoAnythingForNormalEvent() { } @Test - public void shouldRefuseNonVipPlayerForFullServer() { + void shouldRefuseNonVipPlayerForFullServer() { // given Player player = mock(Player.class); PlayerLoginEvent event = new PlayerLoginEvent(player, "hostname", null); @@ -113,7 +110,7 @@ public void shouldRefuseNonVipPlayerForFullServer() { } @Test - public void shouldKickNonVipForJoiningVipPlayer() { + void shouldKickNonVipForJoiningVipPlayer() { // given Player player = mock(Player.class); PlayerLoginEvent event = new PlayerLoginEvent(player, "hostname", null); @@ -138,7 +135,7 @@ public void shouldKickNonVipForJoiningVipPlayer() { } @Test - public void shouldKickVipPlayerIfNoPlayerCanBeKicked() { + void shouldKickVipPlayerIfNoPlayerCanBeKicked() { // given Player player = mock(Player.class); PlayerLoginEvent event = new PlayerLoginEvent(player, "hostname", null); @@ -161,25 +158,23 @@ public void shouldKickVipPlayerIfNoPlayerCanBeKicked() { } @Test - public void shouldKickNonRegistered() throws FailedVerificationException { + void shouldKickNonRegistered() { // given given(settings.getProperty(RestrictionSettings.KICK_NON_REGISTERED)).willReturn(true); - // expect - expectValidationExceptionWith(MessageKey.MUST_REGISTER_MESSAGE); - - // when - onJoinVerifier.checkKickNonRegistered(false); + // 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); @@ -188,7 +183,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); @@ -200,51 +195,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 - // expect - expectValidationExceptionWith(MessageKey.INVALID_NAME_LENGTH); - - // when - 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 - // expect - expectValidationExceptionWith(MessageKey.INVALID_NAME_LENGTH); - - // when - onJoinVerifier.checkIsValidName("abc"); + // 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 - // expect - expectValidationExceptionWith(MessageKey.INVALID_NAME_CHARACTERS, "[a-zA-Z0-9]+"); - - // when - 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(); @@ -258,22 +247,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); - // expect - expectValidationExceptionWith(MessageKey.INVALID_NAME_CASE, "testeR", "Tester"); - // when / then - onJoinVerifier.checkNameCasing(name, auth); + 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(); @@ -287,7 +275,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(); @@ -301,7 +289,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(); @@ -315,7 +303,7 @@ public void shouldAcceptCasingMismatchForDisabledSetting() throws FailedVerifica } @Test - public void shouldAcceptNameForUnregisteredAccount() throws FailedVerificationException { + void shouldAcceptNameForUnregisteredAccount() throws FailedVerificationException { // given String name = "MyPlayer"; PlayerAuth auth = null; @@ -328,7 +316,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); @@ -342,7 +330,7 @@ public void shouldAcceptNameThatIsNotOnline() throws FailedVerificationException } @Test - public void shouldRejectNameAlreadyOnline() throws FailedVerificationException { + void shouldRejectNameAlreadyOnline() { // given String name = "Charlie"; @@ -351,15 +339,13 @@ public void shouldRejectNameAlreadyOnline() throws FailedVerificationException { given(bukkitService.getPlayerExact("Charlie")).willReturn(onlinePlayer); given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); - // expect - expectValidationExceptionWith(MessageKey.USERNAME_ALREADY_ONLINE_ERROR); - // when / then - onJoinVerifier.checkSingleSession(name); + 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); @@ -372,7 +358,7 @@ public void shouldAcceptAlreadyOnlineNameForDisabledSetting() throws FailedVerif } @Test - public void shouldAllowUser() throws FailedVerificationException { + void shouldAllowUser() throws FailedVerificationException { // given String name = "Bobby"; boolean isAuthAvailable = false; @@ -388,7 +374,7 @@ public void shouldAllowUser() throws FailedVerificationException { } @Test - public void shouldAllowUserWithAuth() throws FailedVerificationException { + void shouldAllowUserWithAuth() throws FailedVerificationException { // given String name = "Lacey"; boolean isAuthAvailable = true; @@ -401,7 +387,7 @@ public void shouldAllowUserWithAuth() throws FailedVerificationException { } @Test - public void shouldAllowUserWithBypassPermission() throws FailedVerificationException { + void shouldAllowUserWithBypassPermission() throws FailedVerificationException { // given String name = "Steward"; boolean isAuthAvailable = false; @@ -416,7 +402,7 @@ public void shouldAllowUserWithBypassPermission() throws FailedVerificationExcep } @Test - public void shouldKickUserForFailedAntibotCheck() { + void shouldKickUserForFailedAntibotCheck() { // given String name = "D3"; boolean isAuthAvailable = false; @@ -438,7 +424,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"; @@ -455,7 +441,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"; @@ -470,7 +456,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"; @@ -486,22 +472,21 @@ 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); - // expect - expectValidationExceptionWith(MessageKey.COUNTRY_BANNED_ERROR); - - // when - onJoinVerifier.checkPlayerCountry(name, ip, false); + // when / then + expectValidationExceptionWith(() -> onJoinVerifier.checkPlayerCountry(name, ip, false), + MessageKey.COUNTRY_BANNED_ERROR); } - private void expectValidationExceptionWith(MessageKey messageKey, String... args) { - expectedException.expect(exceptionWithData(messageKey, args)); + private void expectValidationExceptionWith(Executable executable, MessageKey messageKey, String... args) { + FailedVerificationException exception = assertThrows(FailedVerificationException.class, executable); + assertThat(exception, exceptionWithData(messageKey, args)); } private static Matcher exceptionWithData(final MessageKey messageKey, diff --git a/src/test/java/fr/xephi/authme/listener/PlayerListener111Test.java b/src/test/java/fr/xephi/authme/listener/PlayerListener111Test.java index b7b2c60571..08422e77d9 100644 --- a/src/test/java/fr/xephi/authme/listener/PlayerListener111Test.java +++ b/src/test/java/fr/xephi/authme/listener/PlayerListener111Test.java @@ -1,19 +1,19 @@ package fr.xephi.authme.listener; import org.bukkit.event.entity.EntityAirChangeEvent; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.listener.EventCancelVerifier.withServiceMock; /** * Test for {@link PlayerListener111}. */ -@RunWith(MockitoJUnitRunner.class) -public class PlayerListener111Test { +@ExtendWith(MockitoExtension.class) +class PlayerListener111Test { @InjectMocks private PlayerListener111 listener; @@ -22,7 +22,7 @@ public class PlayerListener111Test { private ListenerService listenerService; @Test - public void shouldCancelEvent() { + void shouldCancelEvent() { withServiceMock(listenerService) .check(listener::onPlayerAirChange, EntityAirChangeEvent.class); } diff --git a/src/test/java/fr/xephi/authme/listener/PlayerListener19Test.java b/src/test/java/fr/xephi/authme/listener/PlayerListener19Test.java index b870ac069c..c2950b58a8 100644 --- a/src/test/java/fr/xephi/authme/listener/PlayerListener19Test.java +++ b/src/test/java/fr/xephi/authme/listener/PlayerListener19Test.java @@ -1,19 +1,19 @@ package fr.xephi.authme.listener; import org.bukkit.event.player.PlayerSwapHandItemsEvent; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.listener.EventCancelVerifier.withServiceMock; /** * Test for {@link PlayerListener19}. */ -@RunWith(MockitoJUnitRunner.class) -public class PlayerListener19Test { +@ExtendWith(MockitoExtension.class) +class PlayerListener19Test { @InjectMocks private PlayerListener19 listener; @@ -22,7 +22,7 @@ public class PlayerListener19Test { private ListenerService listenerService; @Test - public void shouldCancelEvent() { + void shouldCancelEvent() { withServiceMock(listenerService) .check(listener::onPlayerSwapHandItems, PlayerSwapHandItemsEvent.class); } diff --git a/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java b/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java index 6ea299732c..fdfe9599a6 100644 --- a/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java +++ b/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java @@ -48,11 +48,11 @@ import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerShearEntityEvent; import org.bukkit.inventory.InventoryView; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetAddress; import java.util.ArrayList; @@ -65,12 +65,13 @@ import static com.google.common.collect.Sets.newHashSet; import static fr.xephi.authme.listener.EventCancelVerifier.withServiceMock; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay; +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.hasSize; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; @@ -89,8 +90,8 @@ /** * Test for {@link PlayerListener}. */ -@RunWith(MockitoJUnitRunner.class) -public class PlayerListenerTest { +@ExtendWith(MockitoExtension.class) +class PlayerListenerTest { @InjectMocks private PlayerListener listener; @@ -129,7 +130,7 @@ public class PlayerListenerTest { * should be CANCELED when single session is enabled. */ @Test - public void shouldCancelKick() { + void shouldCancelKick() { // given given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); Player player = mock(Player.class); @@ -144,7 +145,7 @@ public void shouldCancelKick() { } @Test - public void shouldNotCancelKick() { + void shouldNotCancelKick() { // given given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(false); String name = "Bobby"; @@ -162,7 +163,7 @@ public void shouldNotCancelKick() { } @Test - public void shouldNotCancelOrdinaryKick() { + void shouldNotCancelOrdinaryKick() { // given given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); String name = "Bobby"; @@ -180,7 +181,7 @@ public void shouldNotCancelOrdinaryKick() { } @Test - public void shouldHandleSimpleCancelableEvents() { + void shouldHandleSimpleCancelableEvents() { withServiceMock(listenerService) .check(listener::onPlayerShear, PlayerShearEntityEvent.class) .check(listener::onPlayerFish, PlayerFishEvent.class) @@ -195,7 +196,7 @@ public void shouldHandleSimpleCancelableEvents() { } @Test - public void shouldAllowEssentialsMotd() { + void shouldAllowEssentialsMotd() { // given given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(true); PlayerCommandPreprocessEvent event = mockCommandEvent("/MOTD"); @@ -209,7 +210,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")); @@ -224,7 +225,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()); @@ -245,7 +246,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")); @@ -264,7 +265,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")); @@ -281,7 +282,7 @@ public void shouldCancelFastCommandEvent() { } @Test - public void shouldAllowChat() { + void shouldAllowChat() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(true); AsyncPlayerChatEvent event = mock(AsyncPlayerChatEvent.class); @@ -294,7 +295,7 @@ public void shouldAllowChat() { } @Test - public void shouldCancelChatForUnauthedPlayer() { + void shouldCancelChatForUnauthedPlayer() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -312,7 +313,7 @@ public void shouldCancelChatForUnauthedPlayer() { } @Test - public void shouldSendChatToEveryone() { + void shouldSendChatToEveryone() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -328,7 +329,7 @@ public void shouldSendChatToEveryone() { } @Test - public void shouldHideChatFromUnauthed() { + void shouldHideChatFromUnauthed() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -349,7 +350,7 @@ public void shouldHideChatFromUnauthed() { } @Test - public void shouldCancelChatEventForNoRemainingRecipients() { + void shouldCancelChatEventForNoRemainingRecipients() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -369,7 +370,7 @@ public void shouldCancelChatEventForNoRemainingRecipients() { } @Test - public void shouldAllowChatForBypassPermission() { + void shouldAllowChatForBypassPermission() { // given given(settings.getProperty(RestrictionSettings.ALLOW_CHAT)).willReturn(false); AsyncPlayerChatEvent event = newAsyncChatEvent(); @@ -388,7 +389,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); @@ -404,7 +405,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); @@ -420,7 +421,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); @@ -438,7 +439,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); @@ -457,7 +458,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); @@ -484,7 +485,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); @@ -512,7 +513,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); @@ -540,7 +541,7 @@ public void shouldRejectMovementOutsideOfRadius() { } @Test - public void shouldIgnorePlayerRespawnWithNoTeleport() { + void shouldIgnorePlayerRespawnWithNoTeleport() { // given Player player = mock(Player.class); Location respawnLocation = mock(Location.class); @@ -556,7 +557,7 @@ public void shouldIgnorePlayerRespawnWithNoTeleport() { } @Test - public void shouldIgnorePlayerRespawn() { + void shouldIgnorePlayerRespawn() { // given Player player = mock(Player.class); Location respawnLocation = mock(Location.class); @@ -573,7 +574,7 @@ public void shouldIgnorePlayerRespawn() { } @Test - public void shouldHandlePlayerRespawn() { + void shouldHandlePlayerRespawn() { // given Player player = mock(Player.class); Location originalLocation = mock(Location.class); @@ -594,7 +595,7 @@ public void shouldHandlePlayerRespawn() { } @Test - public void shouldIgnorePlayerRespawnUnloadedWorld() { + void shouldIgnorePlayerRespawnUnloadedWorld() { // given Player player = mock(Player.class); Location originalLocation = mock(Location.class); @@ -614,7 +615,7 @@ public void shouldIgnorePlayerRespawnUnloadedWorld() { } @Test - public void shouldHandlePlayerRespawnNoChanges() { + void shouldHandlePlayerRespawnNoChanges() { // given Player player = mock(Player.class); Location originalLocation = mock(Location.class); @@ -632,7 +633,7 @@ public void shouldHandlePlayerRespawnNoChanges() { } @Test - public void shouldHandlePlayerJoining() { + void shouldHandlePlayerJoining() { // given Player player = mock(Player.class); PlayerJoinEvent event = new PlayerJoinEvent(player, "join message"); @@ -646,7 +647,7 @@ public void shouldHandlePlayerJoining() { } @Test - public void shouldNotInterfereWithUnrestrictedUser() throws FailedVerificationException { + void shouldNotInterfereWithUnrestrictedUser() throws FailedVerificationException { // given String name = "Player01"; Player player = mockPlayerWithName(name); @@ -664,7 +665,7 @@ public void shouldNotInterfereWithUnrestrictedUser() throws FailedVerificationEx } @Test - public void shouldStopHandlingForFullServer() throws FailedVerificationException { + void shouldStopHandlingForFullServer() throws FailedVerificationException { // given String name = "someone"; Player player = mockPlayerWithName(name); @@ -684,7 +685,7 @@ public void shouldStopHandlingForFullServer() throws FailedVerificationException } @Test - public void shouldStopHandlingEventForBadResult() throws FailedVerificationException { + void shouldStopHandlingEventForBadResult() throws FailedVerificationException { // given String name = "someone"; Player player = mockPlayerWithName(name); @@ -705,13 +706,12 @@ public void shouldStopHandlingEventForBadResult() throws FailedVerificationExcep } @Test - public void shouldPerformAllJoinVerificationsSuccessfullyPreLoginLowest() throws FailedVerificationException { + void shouldPerformAllJoinVerificationsSuccessfullyPreLoginLowest() throws FailedVerificationException { // given String name = "someone"; UUID uniqueId = UUID.fromString("753493c9-33ba-4a4a-bf61-1bce9d3c9a71"); - String ip = "12.34.56.78"; - AsyncPlayerPreLoginEvent preLoginEvent = spy(new AsyncPlayerPreLoginEvent(name, mockAddrWithIp(ip), uniqueId)); + AsyncPlayerPreLoginEvent preLoginEvent = spy(new AsyncPlayerPreLoginEvent(name, mock(InetAddress.class), uniqueId)); given(validationService.isUnrestricted(name)).willReturn(false); // when @@ -725,12 +725,11 @@ public void shouldPerformAllJoinVerificationsSuccessfullyPreLoginLowest() throws } @Test - public void shouldKickPreLoginLowestUnresolvedHostname() { + void shouldKickPreLoginLowestUnresolvedHostname() { // given String name = "someone"; UUID uniqueId = UUID.fromString("753493c9-33ba-4a4a-bf61-1bce9d3c9a71"); - - @SuppressWarnings("ConstantConditions") + AsyncPlayerPreLoginEvent preLoginEvent = spy(new AsyncPlayerPreLoginEvent(name, null, uniqueId)); given(messages.retrieveSingle(name, MessageKey.KICK_UNRESOLVED_HOSTNAME)).willReturn("Unresolved hostname"); @@ -743,7 +742,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"); @@ -767,13 +766,12 @@ public void shouldPerformAllJoinVerificationsSuccessfullyPreLoginHighest() throw } @Test - public void shouldPerformAllJoinVerificationsSuccessfullyLogin() { + void shouldPerformAllJoinVerificationsSuccessfullyLogin() { // given String name = "someone"; Player player = mockPlayerWithName(name); - String ip = "12.34.56.78"; - PlayerLoginEvent loginEvent = spy(new PlayerLoginEvent(player, "", mockAddrWithIp(ip))); + PlayerLoginEvent loginEvent = spy(new PlayerLoginEvent(player, "", mock(InetAddress.class))); given(validationService.isUnrestricted(name)).willReturn(false); given(onJoinVerifier.refusePlayerForFullServer(loginEvent)).willReturn(false); @@ -788,11 +786,11 @@ 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"); - InetAddress ip = mockAddrWithIp("33.32.33.33"); + InetAddress ip = mock(InetAddress.class); AsyncPlayerPreLoginEvent event = spy(new AsyncPlayerPreLoginEvent(name, ip, uniqueId)); given(validationService.isUnrestricted(name)).willReturn(false); FailedVerificationException exception = new FailedVerificationException( @@ -814,7 +812,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); @@ -831,7 +829,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); @@ -851,7 +849,7 @@ public void shouldRemoveMessageForUnloggedUser() { } @Test - public void shouldProcessPlayerAndKeepQuitMessage() { + void shouldProcessPlayerAndKeepQuitMessage() { // given String name = "Louis"; Player player = mockPlayerWithName(name); @@ -871,7 +869,7 @@ public void shouldProcessPlayerAndKeepQuitMessage() { } @Test - public void shouldCancelInventoryClickEvent() { + void shouldCancelInventoryClickEvent() { // given InventoryClickEvent event = mock(InventoryClickEvent.class); HumanEntity player = mock(Player.class); @@ -886,7 +884,7 @@ public void shouldCancelInventoryClickEvent() { } @Test - public void shouldAllowInventoryClickEvent() { + void shouldAllowInventoryClickEvent() { // given InventoryClickEvent event = mock(InventoryClickEvent.class); HumanEntity player = mock(Player.class); @@ -901,7 +899,7 @@ public void shouldAllowInventoryClickEvent() { } @Test - public void shouldAllowSignChangeEvent() { + void shouldAllowSignChangeEvent() { // given SignChangeEvent event = mock(SignChangeEvent.class); Player player = mock(Player.class); @@ -916,7 +914,7 @@ public void shouldAllowSignChangeEvent() { } @Test - public void shouldCancelSignChangeEvent() { + void shouldCancelSignChangeEvent() { // given SignChangeEvent event = mock(SignChangeEvent.class); Player player = mock(Player.class); @@ -931,7 +929,7 @@ public void shouldCancelSignChangeEvent() { } @Test - public void shouldAllowInventoryOpen() { + void shouldAllowInventoryOpen() { // given HumanEntity player = mock(Player.class); InventoryView transaction = mock(InventoryView.class); @@ -948,7 +946,7 @@ public void shouldAllowInventoryOpen() { } @Test - public void shouldCancelInventoryOpen() { + void shouldCancelInventoryOpen() { // given HumanEntity player = mock(Player.class); InventoryView transaction = mock(InventoryView.class); @@ -968,7 +966,7 @@ public void shouldCancelInventoryOpen() { } @Test - public void shouldNotModifyJoinMessage() { + void shouldNotModifyJoinMessage() { // given Player player = mock(Player.class); String joinMsg = "The player joined"; @@ -986,7 +984,7 @@ public void shouldNotModifyJoinMessage() { } @Test - public void shouldRemoveJoinMessage() { + void shouldRemoveJoinMessage() { // given Player player = mock(Player.class); String joinMsg = "The player joined"; @@ -1002,7 +1000,7 @@ public void shouldRemoveJoinMessage() { } @Test - public void shouldUseCustomMessage() { + void shouldUseCustomMessage() { // given Player player = mock(Player.class); given(player.getName()).willReturn("doooew"); @@ -1023,7 +1021,7 @@ public void shouldUseCustomMessage() { } @Test - public void shouldDelayJoinMessage() { + void shouldDelayJoinMessage() { // given Player player = mock(Player.class); given(player.getName()).willReturn("thename0"); @@ -1044,13 +1042,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); } @@ -1067,10 +1065,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; diff --git a/src/test/java/fr/xephi/authme/listener/ServerListenerTest.java b/src/test/java/fr/xephi/authme/listener/ServerListenerTest.java index 51ce46f08d..b5629d3853 100644 --- a/src/test/java/fr/xephi/authme/listener/ServerListenerTest.java +++ b/src/test/java/fr/xephi/authme/listener/ServerListenerTest.java @@ -9,12 +9,12 @@ import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.event.server.PluginEvent; import org.bukkit.plugin.Plugin; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -26,8 +26,8 @@ /** * Test for {@link ServerListener}. */ -@RunWith(MockitoJUnitRunner.class) -public class ServerListenerTest { +@ExtendWith(MockitoExtension.class) +class ServerListenerTest { private static final String ESSENTIALS = "Essentials"; private static final String ESSENTIALS_SPAWN = "EssentialsSpawn"; @@ -50,13 +50,13 @@ public class ServerListenerTest { @Mock private SpawnLoader spawnLoader; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldForwardPluginNameOnEnable() { + void shouldForwardPluginNameOnEnable() { checkEnableHandling(ESSENTIALS, () -> verify(pluginHookService).tryHookToEssentials()); checkEnableHandling(ESSENTIALS_SPAWN, () -> verify(spawnLoader).loadEssentialsSpawn()); checkEnableHandling(CMI, () -> { @@ -69,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, () -> { diff --git a/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java b/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java index 96492daa9c..7a426a2ba3 100644 --- a/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java +++ b/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java @@ -1,29 +1,25 @@ package fr.xephi.authme.mail; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -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; import fr.xephi.authme.settings.properties.SecuritySettings; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +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.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; -import java.io.IOException; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; 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}. */ -@RunWith(DelayedInjectionRunner.class) -public class EmailServiceTest { +@ExtendWith(MockitoExtension.class) +class EmailServiceTest { - @InjectDelayed private EmailService emailService; @Mock private Settings settings; @Mock private SendMailSsl sendMailSsl; - @DataFolder - private File dataFolder; + @TempDir + File dataFolder; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @BeforeClass - public static void initLogger() { + @BeforeAll + 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); @@ -96,8 +89,9 @@ public void shouldSendPasswordMail() throws EmailException { } @Test - public void shouldHandleMailCreationError() throws EmailException { + void shouldHandleMailCreationError() throws EmailException { // given + given(sendMailSsl.hasAllInformation()).willReturn(true); doThrow(EmailException.class).when(sendMailSsl).initializeMail(anyString()); // when @@ -110,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); @@ -130,9 +126,10 @@ public void shouldHandleMailSendingFailure() throws EmailException { } @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); @@ -151,7 +148,7 @@ public void shouldSendRecoveryCode() throws EmailException { } @Test - public void shouldHandleMailCreationErrorForRecoveryCode() throws EmailException { + void shouldHandleMailCreationErrorForRecoveryCode() throws EmailException { // given given(sendMailSsl.initializeMail(anyString())).willThrow(EmailException.class); @@ -165,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); @@ -182,7 +180,6 @@ public void shouldHandleFailureToSendRecoveryCode() throws EmailException { 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/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java b/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java index cd5b215234..f5cc180783 100644 --- a/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java +++ b/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.mail; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.settings.Settings; @@ -10,66 +7,62 @@ import fr.xephi.authme.settings.properties.PluginSettings; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +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.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.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; /** * Test for {@link SendMailSsl}. */ -@RunWith(DelayedInjectionRunner.class) -public class SendMailSslTest { +@ExtendWith(MockitoExtension.class) +class SendMailSslTest { - @InjectDelayed + @InjectMocks private SendMailSsl sendMailSsl; @Mock private Settings settings; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @BeforeClass - public static void initLogger() { + @BeforeAll + 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); - } - @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(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.DEBUG); // when @@ -86,17 +79,20 @@ 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(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); // when HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); @@ -112,7 +108,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"); @@ -120,6 +116,11 @@ 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(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); // when HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); diff --git a/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java b/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java index b6fcba7ccc..682934f953 100644 --- a/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/message/HelpMessageConsistencyTest.java @@ -7,8 +7,8 @@ import fr.xephi.authme.command.help.HelpSection; import fr.xephi.authme.permission.DefaultPermission; import org.hamcrest.Matcher; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.Arrays; @@ -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.junit.Assert.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; - @Before - public void findHelpMessagesFiles() { + @BeforeEach + 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); diff --git a/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java b/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java index 0966902ba3..bb016bdbc7 100644 --- a/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java +++ b/src/test/java/fr/xephi/authme/message/MessageFilePlaceholderTest.java @@ -5,9 +5,8 @@ import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import fr.xephi.authme.TestHelper; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.io.File; import java.util.ArrayList; @@ -17,15 +16,14 @@ import java.util.stream.Collectors; import static fr.xephi.authme.message.MessagePathHelper.MESSAGES_FOLDER; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static tools.utils.FileIoUtils.listFilesOrThrow; /** * Checks that the entries in messages_xx.yml files have the {@link MessageKey#getTags() placeholders} * that are defined for the given message. */ -@RunWith(Parameterized.class) -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() @@ -33,17 +31,10 @@ public class MessageFilePlaceholderTest { .putAll(MessageKey.MAX_REGISTER_EXCEEDED, "%max_acc", "%reg_count", "%reg_names") .build(); - private File messagesFile; - private String messagesFilename; - - // Note ljacqu 20170506: We pass the file name separately so we can reference it for the name in @Parameters - public MessageFilePlaceholderTest(File messagesFile, String name) { - this.messagesFile = messagesFile; - this.messagesFilename = name; - } - - @Test - public void shouldHaveAllPlaceholders() { + // 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) { // given PropertyReader reader = new YamlFileReader(messagesFile); List errors = new ArrayList<>(0); @@ -72,8 +63,7 @@ private List findMissingTags(MessageKey key, PropertyReader reader) { return Collections.emptyList(); } - @Parameterized.Parameters(name = "{1}") - public static List buildParams() { + private static List buildParams() { File folder = TestHelper.getJarFile("/" + MESSAGES_FOLDER); List messageFiles = Arrays.stream(listFilesOrThrow(folder)) diff --git a/src/test/java/fr/xephi/authme/message/MessageKeyTest.java b/src/test/java/fr/xephi/authme/message/MessageKeyTest.java index c60305d68c..a30b153892 100644 --- a/src/test/java/fr/xephi/authme/message/MessageKeyTest.java +++ b/src/test/java/fr/xephi/authme/message/MessageKeyTest.java @@ -1,23 +1,23 @@ package fr.xephi.authme.message; import fr.xephi.authme.util.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.matchesPattern; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +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(); diff --git a/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java b/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java index 7e12aa4f59..76b7742ff2 100644 --- a/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java +++ b/src/test/java/fr/xephi/authme/message/MessagePathHelperTest.java @@ -1,33 +1,33 @@ package fr.xephi.authme.message; import fr.xephi.authme.settings.properties.PluginSettings; -import org.junit.Test; +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.junit.Assert.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)); diff --git a/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java b/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java index 5243528fc2..ee0ae647d6 100644 --- a/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/message/MessagesFileConsistencyTest.java @@ -4,25 +4,25 @@ import ch.jalu.configme.resource.YamlFileReader; import fr.xephi.authme.TestHelper; import fr.xephi.authme.util.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests that the project's default language file contains a text for all message keys. *

* 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<>(); diff --git a/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java b/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java index bc1e9769d0..0e49a4e7e0 100644 --- a/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java @@ -12,12 +12,11 @@ import fr.xephi.authme.util.expiring.Duration; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +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.io.TempDir; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -27,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.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -43,19 +42,18 @@ /** * Test for {@link Messages}. */ -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; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private File dataFolder; + @TempDir + File dataFolder; - @BeforeClass - public static void setup() { + @BeforeAll + static void setup() { TestHelper.setupLogger(); } @@ -67,9 +65,8 @@ public static void setup() { * Similarly, the {@code messages_default.yml} from the test resources represents a default * file that should contain all messages, but again, for testing, it just contains a few. */ - @Before - public void setUpMessages() throws IOException { - dataFolder = temporaryFolder.newFolder(); + @BeforeEach + void setUpMessages() throws IOException { File testFile = new File(dataFolder, MessagePathHelper.createMessageFilePath("test")); new File(dataFolder, MessagePathHelper.MESSAGES_FOLDER).mkdirs(); FileUtils.create(testFile); @@ -79,13 +76,13 @@ public void setUpMessages() throws IOException { messages = new Messages(messagesFileHandler); } - @AfterClass - 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); @@ -100,7 +97,7 @@ public void shouldLoadMessageAndSplitAtNewLines() { } @Test - public void shouldLoadMessageAsStringWithNewLines() { + void shouldLoadMessageAsStringWithNewLines() { // given MessageKey key = MessageKey.UNKNOWN_USER; CommandSender sender = mock(CommandSender.class); @@ -114,7 +111,7 @@ public void shouldLoadMessageAsStringWithNewLines() { } @Test - public void shouldFormatColorCodes() { + void shouldFormatColorCodes() { // given MessageKey key = MessageKey.LOGIN_SUCCESS; CommandSender sender = mock(CommandSender.class); @@ -129,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); @@ -143,7 +140,7 @@ public void shouldNotSendEmptyMessage() { } @Test - public void shouldSendMessageToPlayer() { + void shouldSendMessageToPlayer() { // given MessageKey key = MessageKey.LOGIN_SUCCESS; Player player = Mockito.mock(Player.class); @@ -158,7 +155,7 @@ public void shouldSendMessageToPlayer() { } @Test - public void shouldSendMultiLineMessageToPlayer() { + void shouldSendMultiLineMessageToPlayer() { // given MessageKey key = MessageKey.UNKNOWN_USER; Player player = Mockito.mock(Player.class); @@ -176,7 +173,7 @@ public void shouldSendMultiLineMessageToPlayer() { } @Test - public void shouldSendMessageToPlayerWithNameReplacement() { + void shouldSendMessageToPlayerWithNameReplacement() { // given MessageKey key = MessageKey.REGISTER_MESSAGE; Player player = Mockito.mock(Player.class); @@ -191,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); @@ -205,7 +202,7 @@ public void shouldSendMessageToPlayerWithTagReplacement() { } @Test - public void shouldNotLogErrorForKeyWithNoTagReplacements() { + void shouldNotLogErrorForKeyWithNoTagReplacements() { // given MessageKey key = MessageKey.CAPTCHA_WRONG_ERROR; CommandSender sender = mock(CommandSender.class); @@ -219,7 +216,7 @@ public void shouldNotLogErrorForKeyWithNoTagReplacements() { } @Test - public void shouldLogErrorForInvalidReplacementCount() { + void shouldLogErrorForInvalidReplacementCount() { // given Logger logger = mock(Logger.class); ConsoleLogger.initialize(logger, null); @@ -235,7 +232,7 @@ public void shouldLogErrorForInvalidReplacementCount() { } @Test - public void shouldSendErrorForReplacementsOnKeyWithNoTags() { + void shouldSendErrorForReplacementsOnKeyWithNoTags() { // given Logger logger = mock(Logger.class); ConsoleLogger.initialize(logger, null); @@ -251,7 +248,7 @@ public void shouldSendErrorForReplacementsOnKeyWithNoTags() { } @Test - public void shouldNotUseMessageFromDefaultFile() { + void shouldNotUseMessageFromDefaultFile() { // given // Key is present in both files MessageKey key = MessageKey.WRONG_PASSWORD; @@ -266,7 +263,7 @@ public void shouldNotUseMessageFromDefaultFile() { } @Test - public void shouldRetrieveMessageWithReplacements() { + void shouldRetrieveMessageWithReplacements() { // given MessageKey key = MessageKey.CAPTCHA_WRONG_ERROR; CommandSender sender = mock(CommandSender.class); @@ -280,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")); @@ -308,10 +305,7 @@ private MessagesFileHandler createMessagesFileHandler() { Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); - MessagesFileHandler messagesFileHandler = new MessagesFileHandler(); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "settings", settings); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "dataFolder", dataFolder); - ReflectionTestUtils.setField(MessagesFileHandler.class, messagesFileHandler, "messageUpdater", mock(MessageUpdater.class)); + MessagesFileHandler messagesFileHandler = new MessagesFileHandler(dataFolder, settings, mock(MessageUpdater.class)); ReflectionTestUtils.invokePostConstructMethods(messagesFileHandler); return messagesFileHandler; } diff --git a/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java b/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java index 59c7b1b5a5..d6959b6583 100644 --- a/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java +++ b/src/test/java/fr/xephi/authme/message/YamlTextFileCheckerTest.java @@ -6,8 +6,8 @@ import fr.xephi.authme.command.help.HelpSection; import fr.xephi.authme.util.ExceptionUtils; import fr.xephi.authme.util.StringUtils; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.ArrayList; @@ -15,32 +15,32 @@ import java.util.function.Predicate; import static fr.xephi.authme.message.MessagePathHelper.MESSAGES_FOLDER; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static tools.utils.FileIoUtils.listFilesOrThrow; /** * 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; - @BeforeClass - public static void loadMessagesFiles() { + @BeforeAll + static void loadMessagesFiles() { File folder = TestHelper.getJarFile("/" + MESSAGES_FOLDER); messageFiles = listFilesOrThrow(folder); } @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()); diff --git a/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java b/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java index eac3b67e33..16600c889b 100644 --- a/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java +++ b/src/test/java/fr/xephi/authme/message/updater/MessageUpdaterTest.java @@ -6,10 +6,9 @@ import com.google.common.io.Files; import fr.xephi.authme.TestHelper; import fr.xephi.authme.message.MessageKey; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -19,30 +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.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link MessageUpdater}. */ -public class MessageUpdaterTest { +class MessageUpdaterTest { private MessageUpdater messageUpdater = new MessageUpdater(); - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File temporaryFolder; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + 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(); @@ -55,9 +55,9 @@ public void shouldNotUpdateDefaultFile() throws IOException { } @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 @@ -75,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 @@ -101,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 @@ -118,7 +118,7 @@ public void shouldPerformNewerMigrations() throws IOException { } @Test - public void shouldHaveAllKeysInConfigurationData() { + void shouldHaveAllKeysInConfigurationData() { // given Set messageKeysFromEnum = Arrays.stream(MessageKey.values()) .map(MessageKey::getKey) @@ -134,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]) diff --git a/src/test/java/fr/xephi/authme/message/updater/MigraterYamlFileResourceTest.java b/src/test/java/fr/xephi/authme/message/updater/MigraterYamlFileResourceTest.java index 03d79e71f6..60fcfec8ef 100644 --- a/src/test/java/fr/xephi/authme/message/updater/MigraterYamlFileResourceTest.java +++ b/src/test/java/fr/xephi/authme/message/updater/MigraterYamlFileResourceTest.java @@ -7,30 +7,29 @@ import ch.jalu.configme.resource.PropertyReader; import com.google.common.io.Files; import fr.xephi.authme.TestHelper; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +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.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link MigraterYamlFileResource}. */ -public class MigraterYamlFileResourceTest { +class MigraterYamlFileResourceTest { private static final String CHINESE_MESSAGES_FILE = TestHelper.PROJECT_ROOT + "message/chinese_texts.yml"; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File temporaryFolder; @Test - public void shouldReadChineseFile() { + void shouldReadChineseFile() { // given File file = TestHelper.getJarFile(CHINESE_MESSAGES_FILE); MigraterYamlFileResource resource = new MigraterYamlFileResource(file); @@ -45,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(); diff --git a/src/test/java/fr/xephi/authme/message/updater/OldMessageKeysMigraterTest.java b/src/test/java/fr/xephi/authme/message/updater/OldMessageKeysMigraterTest.java index be10559ef5..70101d699f 100644 --- a/src/test/java/fr/xephi/authme/message/updater/OldMessageKeysMigraterTest.java +++ b/src/test/java/fr/xephi/authme/message/updater/OldMessageKeysMigraterTest.java @@ -1,7 +1,7 @@ package fr.xephi.authme.message.updater; import fr.xephi.authme.message.MessageKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashSet; @@ -9,15 +9,15 @@ import java.util.Set; import java.util.stream.Collectors; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link OldMessageKeysMigrater}. */ -public class OldMessageKeysMigraterTest { +class OldMessageKeysMigraterTest { @Test - public void shouldHasOldKeysThatAreNewParentsFirstInMap() { + void shouldHasOldKeysThatAreNewParentsFirstInMap() { // given Set parentPaths = collectParentPathsFromMessageKeys(); Set encounteredParents = new HashSet<>(); diff --git a/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java b/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java index 8975068f64..8e38362eca 100644 --- a/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java +++ b/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java @@ -1,12 +1,12 @@ package fr.xephi.authme.output; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.logging.LogRecord; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -14,7 +14,7 @@ /** * Test for {@link ConsoleFilter}. */ -public class ConsoleFilterTest { +class ConsoleFilterTest { private final ConsoleFilter filter = new ConsoleFilter(); @@ -23,7 +23,7 @@ public class ConsoleFilterTest { @Test - public void shouldReplaceSensitiveRecord() { + void shouldReplaceSensitiveRecord() { // given LogRecord record = createRecord(SENSITIVE_COMMAND); @@ -36,7 +36,7 @@ public void shouldReplaceSensitiveRecord() { } @Test - public void shouldNotFilterRegularCommand() { + void shouldNotFilterRegularCommand() { // given LogRecord record = createRecord(NORMAL_COMMAND); @@ -49,7 +49,7 @@ public void shouldNotFilterRegularCommand() { } @Test - public void shouldManageRecordWithNullMessage() { + void shouldManageRecordWithNullMessage() { // given LogRecord record = createRecord(null); diff --git a/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java b/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java index fe53383b4f..83440ea798 100644 --- a/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java +++ b/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java @@ -7,33 +7,33 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.SecuritySettings; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Map; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link ConsoleLoggerFactory}. */ -public class ConsoleLoggerFactoryTest { +class ConsoleLoggerFactoryTest { - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { removeSettingsAndClearMap(); TestHelper.setupLogger(); } - @After - public void resetConsoleLoggerFactoryToDefaults() { + @AfterEach + void resetConsoleLoggerFactoryToDefaults() { removeSettingsAndClearMap(); } @@ -43,7 +43,7 @@ private static void removeSettingsAndClearMap() { } @Test - public void shouldCreateLoggerWithProperNameAndDefaultLogLevel() { + void shouldCreateLoggerWithProperNameAndDefaultLogLevel() { // given / when ConsoleLogger logger = ConsoleLoggerFactory.get(AuthMe.class); @@ -54,7 +54,7 @@ public void shouldCreateLoggerWithProperNameAndDefaultLogLevel() { } @Test - public void shouldReturnSameInstanceForName() { + void shouldReturnSameInstanceForName() { // given / when ConsoleLogger logger1 = ConsoleLoggerFactory.get(String.class); ConsoleLogger logger2 = ConsoleLoggerFactory.get(Number.class); @@ -67,7 +67,7 @@ public void shouldReturnSameInstanceForName() { } @Test - public void shouldInitializeAccordingToSettings() { + void shouldInitializeAccordingToSettings() { // given Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.FINE); diff --git a/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java b/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java index 91228c5fc4..2894be180a 100644 --- a/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java +++ b/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java @@ -1,22 +1,19 @@ package fr.xephi.authme.output; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.core.Filter.Result; import org.apache.logging.log4j.core.LogEvent; -import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.message.Message; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.when; + /** * Test for {@link Log4JFilter}. */ -public class Log4JFilterTest { +class Log4JFilterTest { private final Log4JFilter log4JFilter = new Log4JFilter(); @@ -28,7 +25,7 @@ public class Log4JFilterTest { // Test the filter(LogEvent) method // --------- @Test - public void shouldFilterSensitiveLogEvent() { + void shouldFilterSensitiveLogEvent() { // given Message message = mockMessage(SENSITIVE_COMMAND); LogEvent event = Mockito.mock(LogEvent.class); @@ -42,7 +39,7 @@ public void shouldFilterSensitiveLogEvent() { } @Test - public void shouldNotFilterIrrelevantLogEvent() { + void shouldNotFilterIrrelevantLogEvent() { // given Message message = mockMessage(NORMAL_COMMAND); LogEvent event = Mockito.mock(LogEvent.class); @@ -56,7 +53,7 @@ public void shouldNotFilterIrrelevantLogEvent() { } @Test - public void shouldNotFilterNonCommandLogEvent() { + void shouldNotFilterNonCommandLogEvent() { // given Message message = mockMessage(OTHER_COMMAND); LogEvent event = Mockito.mock(LogEvent.class); @@ -70,7 +67,7 @@ public void shouldNotFilterNonCommandLogEvent() { } @Test - public void shouldNotFilterLogEventWithNullMessage() { + void shouldNotFilterLogEventWithNullMessage() { // given Message message = mockMessage(null); LogEvent event = Mockito.mock(LogEvent.class); @@ -84,7 +81,7 @@ public void shouldNotFilterLogEventWithNullMessage() { } @Test - public void shouldNotFilterWhenLogEventIsNull() { + void shouldNotFilterWhenLogEventIsNull() { // given / when Result result = log4JFilter.filter(null); @@ -96,7 +93,7 @@ public void shouldNotFilterWhenLogEventIsNull() { // Test filter(Logger, Level, Marker, String, Object...) // ---------- @Test - public void shouldFilterSensitiveStringMessage() { + void shouldFilterSensitiveStringMessage() { // given / when Result result = log4JFilter.filter(null, null, null, SENSITIVE_COMMAND); @@ -105,7 +102,7 @@ public void shouldFilterSensitiveStringMessage() { } @Test - public void shouldNotFilterNormalStringMessage() { + void shouldNotFilterNormalStringMessage() { // given / when Result result = log4JFilter.filter(null, null, null, NORMAL_COMMAND); @@ -114,7 +111,7 @@ public void shouldNotFilterNormalStringMessage() { } @Test - public void shouldNotFilterNonCommandStringMessage() { + void shouldNotFilterNonCommandStringMessage() { // given / when Result result = log4JFilter.filter(null, null, null, OTHER_COMMAND); @@ -123,7 +120,7 @@ public void shouldNotFilterNonCommandStringMessage() { } @Test - public void shouldReturnNeutralForNullMessage() { + void shouldReturnNeutralForNullMessage() { // given / when Result result = log4JFilter.filter(null, null, null, null); @@ -135,7 +132,7 @@ public void shouldReturnNeutralForNullMessage() { // Test filter(Logger, Level, Marker, Object, Throwable) // -------- @Test - public void shouldFilterSensitiveObjectMessage() { + void shouldFilterSensitiveObjectMessage() { // given / when Result result = log4JFilter.filter(null, null, null, (Object) SENSITIVE_COMMAND, new Exception()); @@ -144,7 +141,7 @@ public void shouldFilterSensitiveObjectMessage() { } @Test - public void shouldNotFilterNullObjectParam() { + void shouldNotFilterNullObjectParam() { // given / when Result result = log4JFilter.filter(null, null, null, (Object) null, new Exception()); @@ -153,7 +150,7 @@ public void shouldNotFilterNullObjectParam() { } @Test - public void shouldNotFilterIrrelevantMessage() { + void shouldNotFilterIrrelevantMessage() { // given / when Result result = log4JFilter.filter(null, null, null, (Object) OTHER_COMMAND, new Exception()); @@ -162,7 +159,7 @@ public void shouldNotFilterIrrelevantMessage() { } @Test - public void shouldNotFilterNonSensitiveCommand() { + void shouldNotFilterNonSensitiveCommand() { // given / when Result result = log4JFilter.filter(null, null, null, (Object) NORMAL_COMMAND, new Exception()); @@ -174,7 +171,7 @@ public void shouldNotFilterNonSensitiveCommand() { // Test filter(Logger, Level, Marker, Message, Throwable) // -------- @Test - public void shouldFilterSensitiveMessage() { + void shouldFilterSensitiveMessage() { // given Message message = mockMessage(SENSITIVE_COMMAND); @@ -186,7 +183,7 @@ public void shouldFilterSensitiveMessage() { } @Test - public void shouldNotFilterNonSensitiveMessage() { + void shouldNotFilterNonSensitiveMessage() { // given Message message = mockMessage(NORMAL_COMMAND); @@ -198,7 +195,7 @@ public void shouldNotFilterNonSensitiveMessage() { } @Test - public void shouldNotFilterNonCommandMessage() { + void shouldNotFilterNonCommandMessage() { // given Message message = mockMessage(OTHER_COMMAND); @@ -210,7 +207,7 @@ public void shouldNotFilterNonCommandMessage() { } @Test - public void shouldNotFilterNullMessage() { + void shouldNotFilterNullMessage() { // given / when Result result = log4JFilter.filter(null, null, null, (Object) null, new Exception()); diff --git a/src/test/java/fr/xephi/authme/output/LogFilterHelperTest.java b/src/test/java/fr/xephi/authme/output/LogFilterHelperTest.java index 302345fb9c..8fb53f7fa4 100644 --- a/src/test/java/fr/xephi/authme/output/LogFilterHelperTest.java +++ b/src/test/java/fr/xephi/authme/output/LogFilterHelperTest.java @@ -3,19 +3,19 @@ import com.google.common.collect.Lists; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.CommandInitializer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertThat; /** * Test for {@link LogFilterHelper}. */ -public class LogFilterHelperTest { +class LogFilterHelperTest { private static final List ALL_COMMANDS = new CommandInitializer().getCommands(); @@ -24,7 +24,7 @@ public class LogFilterHelperTest { * (commands with password argument). */ @Test - public void shouldBlacklistAllSensitiveCommands() { + void shouldBlacklistAllSensitiveCommands() { // given List sensitiveCommands = Arrays.asList( getCommand("register"), getCommand("login"), getCommand("changepassword"), getCommand("unregister"), diff --git a/src/test/java/fr/xephi/authme/output/LogLevelTest.java b/src/test/java/fr/xephi/authme/output/LogLevelTest.java index aa313ae769..41d80cade8 100644 --- a/src/test/java/fr/xephi/authme/output/LogLevelTest.java +++ b/src/test/java/fr/xephi/authme/output/LogLevelTest.java @@ -1,18 +1,18 @@ package fr.xephi.authme.output; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static java.lang.String.format; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link LogLevel}. */ -public class LogLevelTest { +class LogLevelTest { @Test - public void shouldIncludeProperLevels() { + void shouldIncludeProperLevels() { checkLevelInclusion(LogLevel.INFO, true, false, false); checkLevelInclusion(LogLevel.FINE, true, true, false); checkLevelInclusion(LogLevel.DEBUG, true, true, true); diff --git a/src/test/java/fr/xephi/authme/permission/AbstractPermissionsEnumTest.java b/src/test/java/fr/xephi/authme/permission/AbstractPermissionsEnumTest.java index 4b327ec45f..71799d842a 100644 --- a/src/test/java/fr/xephi/authme/permission/AbstractPermissionsEnumTest.java +++ b/src/test/java/fr/xephi/authme/permission/AbstractPermissionsEnumTest.java @@ -1,11 +1,11 @@ package fr.xephi.authme.permission; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Has common tests for enums implementing {@link PermissionNode}. @@ -13,7 +13,7 @@ public abstract class AbstractPermissionsEnumTest { @Test - public void shouldAllStartWitRequiredPrefix() { + void shouldAllStartWitRequiredPrefix() { // given String requiredPrefix = getRequiredPrefix(); @@ -27,7 +27,7 @@ public void shouldAllStartWitRequiredPrefix() { } @Test - public void shouldHaveUniqueNodes() { + void shouldHaveUniqueNodes() { // given Set nodes = new HashSet<>(); diff --git a/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java b/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java index f3e4f1fde8..f98f6452a1 100644 --- a/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java +++ b/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java @@ -3,7 +3,7 @@ /** * Test for {@link AdminPermission}. */ -public class AdminPermissionTest extends AbstractPermissionsEnumTest { +class AdminPermissionTest extends AbstractPermissionsEnumTest { @Override protected PermissionNode[] getPermissionNodes() { diff --git a/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java b/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java index 3e0a9f0136..2da9aa1ce4 100644 --- a/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java +++ b/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java @@ -3,7 +3,7 @@ /** * Test for {@link DebugSectionPermissions}. */ -public class DebugSectionPermissionsTest extends AbstractPermissionsEnumTest { +class DebugSectionPermissionsTest extends AbstractPermissionsEnumTest { @Override protected PermissionNode[] getPermissionNodes() { diff --git a/src/test/java/fr/xephi/authme/permission/PermissionConsistencyTest.java b/src/test/java/fr/xephi/authme/permission/PermissionConsistencyTest.java index 6d7a37e2f6..728f684d79 100644 --- a/src/test/java/fr/xephi/authme/permission/PermissionConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/permission/PermissionConsistencyTest.java @@ -8,8 +8,8 @@ import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -22,12 +22,12 @@ import java.util.stream.Collectors; import static fr.xephi.authme.TestHelper.getJarFile; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests that the permissions listed in plugin.yml correspond to the ones in the code. */ -public class PermissionConsistencyTest { +class PermissionConsistencyTest { /** Wildcard permissions (present in plugin.yml but not in the codebase). */ private static final Set PLUGIN_YML_PERMISSIONS_WILDCARDS = @@ -45,8 +45,8 @@ public class PermissionConsistencyTest { /** All permissions listed in plugin.yml. */ private static Map pluginYmlPermissions; - @BeforeClass - public static void gatherPermissionNodes() { + @BeforeAll + static void gatherPermissionNodes() { permissionClasses = new ClassCollector(TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT + "permission") .collectClasses(PermissionNode.class).stream() .filter(clz -> !clz.isInterface()) @@ -56,7 +56,7 @@ public static void gatherPermissionNodes() { } @Test - public void shouldHaveAllPermissionsInPluginYml() { + void shouldHaveAllPermissionsInPluginYml() { // given List errors = new ArrayList<>(); @@ -77,7 +77,7 @@ public void shouldHaveAllPermissionsInPluginYml() { } @Test - public void shouldNotHaveUnknownPermissionsInPluginYml() { + void shouldNotHaveUnknownPermissionsInPluginYml() { // given List errors = new ArrayList<>(); diff --git a/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java b/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java index bdd1c5e633..ce34538671 100644 --- a/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java +++ b/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java @@ -19,14 +19,14 @@ import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.ServicesManager; -import org.junit.AssumptionViolatedException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.tyrannyofheaven.bukkit.zPermissions.ZPermissionsService; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; @@ -36,10 +36,11 @@ import static fr.xephi.authme.permission.PermissionsSystemType.PERMISSIONS_EX; import static fr.xephi.authme.permission.PermissionsSystemType.VAULT; import static fr.xephi.authme.permission.PermissionsSystemType.Z_PERMISSIONS; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; @@ -48,13 +49,7 @@ /** * Tests the initialization of {@link PermissionHandler} in {@link PermissionsManager}. */ -@RunWith(Parameterized.class) -public class PermissionsManagerInitializationTest { - - @Parameterized.Parameter(0) - public PermissionsSystemType permissionsSystemType; - @Parameterized.Parameter(1) - public Class expectedHandlerType; +class PermissionsManagerInitializationTest { private Settings settings = mock(Settings.class); private ServicesManager servicesManager = mock(ServicesManager.class); @@ -62,21 +57,21 @@ public class PermissionsManagerInitializationTest { private PluginManager pluginManager = mock(PluginManager.class); private PermissionsManager permissionsManager = new PermissionsManager(server, pluginManager, settings); - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } - @Before - public void setUp() { + @BeforeEach + void setUp() { ReflectionTestUtils.setField(Bukkit.class, null, "server", server); given(server.getServicesManager()).willReturn(servicesManager); } - @Test - public void shouldInitializeHandler() { + @ParamTest + void shouldInitializeHandler(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { // given - setUpForPermissionSystemTest(); + setUpForPermissionSystemTest(permissionsSystemType); given(settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)).willReturn(false); Plugin plugin = mock(Plugin.class); given(plugin.isEnabled()).willReturn(true); @@ -91,8 +86,8 @@ public void shouldInitializeHandler() { assertThat(handler.getPermissionSystem(), equalTo(permissionsSystemType)); } - @Test - public void shouldInitializeToVaultIfSoConfigured() { + @ParamTest + void shouldInitializeToVaultIfSoConfigured(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { // given setUpForVault(); given(settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)).willReturn(true); @@ -109,8 +104,8 @@ public void shouldInitializeToVaultIfSoConfigured() { verify(pluginManager, only()).getPlugin(VAULT.getPluginName()); } - @Test - public void shouldNotHookIntoDisabledPlugin() { + @ParamTest + void shouldNotHookIntoDisabledPlugin(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { // given given(settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)).willReturn(false); Plugin plugin = mock(Plugin.class); @@ -124,8 +119,8 @@ public void shouldNotHookIntoDisabledPlugin() { assertThat(getHandlerFieldValue(), nullValue()); } - @Test - public void shouldCatchInitializationException() { + @ParamTest + void shouldCatchInitializationException(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { // given given(settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)).willReturn(false); Plugin plugin = mock(Plugin.class); @@ -140,8 +135,7 @@ public void shouldCatchInitializationException() { assertThat(getHandlerFieldValue(), nullValue()); } - @Parameterized.Parameters(name = "{0}") - public static Collection createParameters() { + static Collection createParameters() { Map> handlersByPermissionSystemType = ImmutableMap.of( LUCK_PERMS, LuckPermsHandler.class, PERMISSIONS_EX, PermissionsExHandler.class, @@ -160,12 +154,12 @@ public static Collection createParameters() { .collect(Collectors.toList()); } - private void setUpForPermissionSystemTest() { + private void setUpForPermissionSystemTest(PermissionsSystemType permissionsSystemType) { if (permissionsSystemType == LUCK_PERMS) { LuckPerms api = mock(LuckPerms.class); ReflectionTestUtils.setField(LuckPermsProvider.class, null, "instance", api); } else if (permissionsSystemType == PERMISSIONS_EX) { - throw new AssumptionViolatedException( + assumeTrue(false, "PermissionsEx instance cannot be mocked because of missing dependencies -- skipping"); } else if (permissionsSystemType == Z_PERMISSIONS) { ZPermissionsService zPermissionsService = mock(ZPermissionsService.class); @@ -187,4 +181,10 @@ private void setUpForVault() { private PermissionHandler getHandlerFieldValue() { return ReflectionTestUtils.getFieldValue(PermissionsManager.class, permissionsManager, "handler"); } + + @ParameterizedTest(name = "{0}") + @MethodSource("createParameters") + @Retention(RetentionPolicy.RUNTIME) + @interface ParamTest { + } } diff --git a/src/test/java/fr/xephi/authme/permission/PermissionsManagerTest.java b/src/test/java/fr/xephi/authme/permission/PermissionsManagerTest.java index 6c7efb4520..cd4373794f 100644 --- a/src/test/java/fr/xephi/authme/permission/PermissionsManagerTest.java +++ b/src/test/java/fr/xephi/authme/permission/PermissionsManagerTest.java @@ -4,22 +4,22 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link PermissionsManager}. */ -@RunWith(MockitoJUnitRunner.class) -public class PermissionsManagerTest { +@ExtendWith(MockitoExtension.class) +class PermissionsManagerTest { @InjectMocks private PermissionsManager permissionsManager; @@ -31,7 +31,7 @@ public class PermissionsManagerTest { private PluginManager pluginManager; @Test - public void shouldUseDefaultPermissionForCommandSender() { + void shouldUseDefaultPermissionForCommandSender() { // given PermissionNode node = TestPermissions.LOGIN; CommandSender sender = mock(CommandSender.class); @@ -44,7 +44,7 @@ public void shouldUseDefaultPermissionForCommandSender() { } @Test - public void shouldGrantToOpCommandSender() { + void shouldGrantToOpCommandSender() { // given PermissionNode node = TestPermissions.DELETE_USER; CommandSender sender = mock(CommandSender.class); @@ -58,7 +58,7 @@ public void shouldGrantToOpCommandSender() { } @Test - public void shouldDenyPermissionEvenForOpCommandSender() { + void shouldDenyPermissionEvenForOpCommandSender() { // given PermissionNode node = TestPermissions.WORLD_DOMINATION; CommandSender sender = mock(CommandSender.class); @@ -71,7 +71,7 @@ public void shouldDenyPermissionEvenForOpCommandSender() { } @Test - public void shouldAllowForNonOpPlayer() { + void shouldAllowForNonOpPlayer() { // given PermissionNode node = TestPermissions.LOGIN; Player player = mock(Player.class); @@ -84,7 +84,7 @@ public void shouldAllowForNonOpPlayer() { } @Test - public void shouldDenyForNonOpPlayer() { + void shouldDenyForNonOpPlayer() { // given PermissionNode node = TestPermissions.DELETE_USER; Player player = mock(Player.class); @@ -97,7 +97,7 @@ public void shouldDenyForNonOpPlayer() { } @Test - public void shouldAllowForOpPlayer() { + void shouldAllowForOpPlayer() { // given PermissionNode node = TestPermissions.DELETE_USER; Player player = mock(Player.class); @@ -111,7 +111,7 @@ public void shouldAllowForOpPlayer() { } @Test - public void shouldDenyEvenForOpPlayer() { + void shouldDenyEvenForOpPlayer() { // given PermissionNode node = TestPermissions.WORLD_DOMINATION; Player player = mock(Player.class); @@ -124,7 +124,7 @@ public void shouldDenyEvenForOpPlayer() { } @Test - public void shouldHandleNullPermissionForCommandSender() { + void shouldHandleNullPermissionForCommandSender() { // given PermissionNode node = null; CommandSender sender = mock(CommandSender.class); @@ -137,7 +137,7 @@ public void shouldHandleNullPermissionForCommandSender() { } @Test - public void shouldHandleNullPermissionForPlayer() { + void shouldHandleNullPermissionForPlayer() { // given PermissionNode node = null; Player player = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/permission/PermissionsSystemTypeTest.java b/src/test/java/fr/xephi/authme/permission/PermissionsSystemTypeTest.java index 79b513a146..2748948cba 100644 --- a/src/test/java/fr/xephi/authme/permission/PermissionsSystemTypeTest.java +++ b/src/test/java/fr/xephi/authme/permission/PermissionsSystemTypeTest.java @@ -1,23 +1,23 @@ package fr.xephi.authme.permission; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; /** * Test for {@link PermissionsSystemType}. */ -public class PermissionsSystemTypeTest { +class PermissionsSystemTypeTest { @Test - public void shouldHaveDefinedAndUniqueNames() { + void shouldHaveDefinedAndUniqueNames() { // given / when / then List names = new ArrayList<>(PermissionsSystemType.values().length); List pluginNames = new ArrayList<>(PermissionsSystemType.values().length); @@ -37,7 +37,7 @@ public void shouldHaveDefinedAndUniqueNames() { } @Test - public void shouldRecognizePermissionSystemType() { + void shouldRecognizePermissionSystemType() { assertThat(PermissionsSystemType.isPermissionSystem("bogus"), equalTo(false)); assertThat(PermissionsSystemType.isPermissionSystem("PermissionsEx"), equalTo(true)); } diff --git a/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java b/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java index 32a45b98de..f4822d2ef7 100644 --- a/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java +++ b/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java @@ -3,7 +3,7 @@ /** * Test for {@link PlayerPermission}. */ -public class PlayerPermissionTest extends AbstractPermissionsEnumTest { +class PlayerPermissionTest extends AbstractPermissionsEnumTest { @Override protected PermissionNode[] getPermissionNodes() { diff --git a/src/test/java/fr/xephi/authme/permission/PlayerStatePermissionTest.java b/src/test/java/fr/xephi/authme/permission/PlayerStatePermissionTest.java index 56e5e1ce1e..9ebc3bf04a 100644 --- a/src/test/java/fr/xephi/authme/permission/PlayerStatePermissionTest.java +++ b/src/test/java/fr/xephi/authme/permission/PlayerStatePermissionTest.java @@ -1,20 +1,20 @@ package fr.xephi.authme.permission; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.Set; import static com.google.common.collect.Sets.newHashSet; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link PlayerStatePermission}. */ -public class PlayerStatePermissionTest extends AbstractPermissionsEnumTest { +class PlayerStatePermissionTest extends AbstractPermissionsEnumTest { @Test - public void shouldNotStartWithOtherPrefixes() { + void shouldNotStartWithOtherPrefixes() { // given Set forbiddenPrefixes = newHashSet("authme.player", "authme.admin", "authme.debug"); diff --git a/src/test/java/fr/xephi/authme/permission/handlers/VaultHandlerTest.java b/src/test/java/fr/xephi/authme/permission/handlers/VaultHandlerTest.java index 852dcaefb9..e559a6971e 100644 --- a/src/test/java/fr/xephi/authme/permission/handlers/VaultHandlerTest.java +++ b/src/test/java/fr/xephi/authme/permission/handlers/VaultHandlerTest.java @@ -4,15 +4,14 @@ import net.milkbowl.vault.permission.Permission; import org.bukkit.Server; import org.bukkit.entity.Player; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -20,12 +19,12 @@ /** * Test for {@link VaultHandler}. */ -public class VaultHandlerTest { +class VaultHandlerTest { private VaultHandlerTestImpl vaultHandlerTest = VaultHandlerTestImpl.create(); @Test - public void shouldReturnGroups() { + void shouldReturnGroups() { // given Permission permissionMock = vaultHandlerTest.permissionMock; Player player = mock(Player.class); @@ -44,7 +43,7 @@ public void shouldReturnGroups() { * Bug #1702: VaultHandler may return null for groups list. */ @Test - public void shouldHandleNullAsGroups() { + void shouldHandleNullAsGroups() { // given Permission permissionMock = vaultHandlerTest.permissionMock; Player player = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/process/changepassword/AsyncChangePasswordTest.java b/src/test/java/fr/xephi/authme/process/changepassword/AsyncChangePasswordTest.java index b0dd97bbee..9606572495 100644 --- a/src/test/java/fr/xephi/authme/process/changepassword/AsyncChangePasswordTest.java +++ b/src/test/java/fr/xephi/authme/process/changepassword/AsyncChangePasswordTest.java @@ -9,12 +9,12 @@ import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.bungeecord.BungeeSender; import org.bukkit.command.CommandSender; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -24,8 +24,8 @@ /** * Test for {@link AsyncChangePassword}. */ -@RunWith(MockitoJUnitRunner.class) -public class AsyncChangePasswordTest { +@ExtendWith(MockitoExtension.class) +class AsyncChangePasswordTest { @InjectMocks private AsyncChangePassword asyncChangePassword; @@ -41,13 +41,13 @@ public class AsyncChangePasswordTest { @Mock private BungeeSender bungeeSender; - @Before - public void setUpLogger() { + @BeforeEach + void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldRejectCommandForUnknownUser() { + void shouldRejectCommandForUnknownUser() { // given CommandSender sender = mock(CommandSender.class); String player = "player"; @@ -64,7 +64,7 @@ public void shouldRejectCommandForUnknownUser() { } @Test - public void shouldUpdatePasswordOfLoggedInUser() { + void shouldUpdatePasswordOfLoggedInUser() { // given CommandSender sender = mock(CommandSender.class); String player = "my_user12"; @@ -85,7 +85,7 @@ public void shouldUpdatePasswordOfLoggedInUser() { } @Test - public void shouldUpdatePasswordOfOfflineUser() { + void shouldUpdatePasswordOfOfflineUser() { // given CommandSender sender = mock(CommandSender.class); String player = "my_user12"; @@ -107,7 +107,7 @@ public void shouldUpdatePasswordOfOfflineUser() { } @Test - public void shouldReportWhenSaveFailed() { + void shouldReportWhenSaveFailed() { // given CommandSender sender = mock(CommandSender.class); String player = "my_user12"; diff --git a/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java b/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java index 6d2fdd2227..4e32e33f2f 100644 --- a/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java +++ b/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java @@ -11,12 +11,13 @@ import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.service.bungeecord.BungeeSender; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; + import java.util.function.Function; import static org.mockito.ArgumentMatchers.any; @@ -29,8 +30,8 @@ /** * Test for {@link AsyncAddEmail}. */ -@RunWith(MockitoJUnitRunner.class) -public class AsyncAddEmailTest { +@ExtendWith(MockitoExtension.class) +class AsyncAddEmailTest { @InjectMocks private AsyncAddEmail asyncAddEmail; @@ -56,13 +57,13 @@ public class AsyncAddEmailTest { @Mock private BukkitService bukkitService; - @BeforeClass - public static void setUp() { + @BeforeAll + static void setUp() { TestHelper.setupLogger(); } @Test - public void shouldAddEmail() { + void shouldAddEmail() { // given String email = "my.mail@example.org"; given(player.getName()).willReturn("testEr"); @@ -87,7 +88,7 @@ public void shouldAddEmail() { } @Test - public void shouldReturnErrorWhenMailCannotBeSaved() { + void shouldReturnErrorWhenMailCannotBeSaved() { // given String email = "my.mail@example.org"; given(player.getName()).willReturn("testEr"); @@ -110,7 +111,7 @@ public void shouldReturnErrorWhenMailCannotBeSaved() { } @Test - public void shouldNotAddMailIfPlayerAlreadyHasEmail() { + void shouldNotAddMailIfPlayerAlreadyHasEmail() { // given given(player.getName()).willReturn("my_Player"); given(playerCache.isAuthenticated("my_player")).willReturn(true); @@ -127,7 +128,7 @@ public void shouldNotAddMailIfPlayerAlreadyHasEmail() { } @Test - public void shouldNotAddMailIfItIsInvalid() { + void shouldNotAddMailIfItIsInvalid() { // given String email = "invalid_mail"; given(player.getName()).willReturn("my_Player"); @@ -146,7 +147,7 @@ public void shouldNotAddMailIfItIsInvalid() { } @Test - public void shouldNotAddMailIfAlreadyUsed() { + void shouldNotAddMailIfAlreadyUsed() { // given String email = "player@mail.tld"; given(player.getName()).willReturn("TestName"); @@ -166,7 +167,7 @@ public void shouldNotAddMailIfAlreadyUsed() { } @Test - public void shouldShowLoginMessage() { + void shouldShowLoginMessage() { // given given(player.getName()).willReturn("Username12"); given(playerCache.isAuthenticated("username12")).willReturn(false); @@ -181,7 +182,7 @@ public void shouldShowLoginMessage() { } @Test - public void shouldShowRegisterMessage() { + void shouldShowRegisterMessage() { // given given(player.getName()).willReturn("user"); given(playerCache.isAuthenticated("user")).willReturn(false); @@ -196,7 +197,7 @@ public void shouldShowRegisterMessage() { } @Test - public void shouldNotAddOnCancelledEvent() { + void shouldNotAddOnCancelledEvent() { // given String email = "player@mail.tld"; given(player.getName()).willReturn("TestName"); diff --git a/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java b/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java index b0f3e971c1..cbf890d8c6 100644 --- a/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java +++ b/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java @@ -11,12 +11,12 @@ import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.service.bungeecord.BungeeSender; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.function.Function; @@ -31,8 +31,8 @@ /** * Test for {@link AsyncChangeEmail}. */ -@RunWith(MockitoJUnitRunner.class) -public class AsyncChangeEmailTest { +@ExtendWith(MockitoExtension.class) +class AsyncChangeEmailTest { @InjectMocks private AsyncChangeEmail process; @@ -58,13 +58,13 @@ public class AsyncChangeEmailTest { @Mock private BukkitService bukkitService; - @BeforeClass - public static void setUp() { + @BeforeAll + static void setUp() { TestHelper.setupLogger(); } @Test - public void shouldChangeEmail() { + void shouldChangeEmail() { // given String newEmail = "new@mail.tld"; given(player.getName()).willReturn("Bobby"); @@ -87,7 +87,7 @@ public void shouldChangeEmail() { } @Test - public void shouldNotBeCaseSensitiveWhenComparingEmails() { + void shouldNotBeCaseSensitiveWhenComparingEmails() { // given String newEmail = "newmail@example.com"; given(player.getName()).willReturn("Debra"); @@ -111,7 +111,7 @@ public void shouldNotBeCaseSensitiveWhenComparingEmails() { } @Test - public void shouldShowErrorIfSaveFails() { + void shouldShowErrorIfSaveFails() { // given String newEmail = "new@mail.tld"; given(player.getName()).willReturn("Bobby"); @@ -134,7 +134,7 @@ public void shouldShowErrorIfSaveFails() { } @Test - public void shouldShowAddEmailUsage() { + void shouldShowAddEmailUsage() { // given given(player.getName()).willReturn("Bobby"); given(playerCache.isAuthenticated("bobby")).willReturn(true); @@ -151,7 +151,7 @@ public void shouldShowAddEmailUsage() { } @Test - public void shouldRejectInvalidNewMail() { + void shouldRejectInvalidNewMail() { // given String newEmail = "bogus"; given(player.getName()).willReturn("Bobby"); @@ -170,7 +170,7 @@ public void shouldRejectInvalidNewMail() { } @Test - public void shouldRejectInvalidOldEmail() { + void shouldRejectInvalidOldEmail() { // given String newEmail = "new@mail.tld"; given(player.getName()).willReturn("Bobby"); @@ -189,7 +189,7 @@ public void shouldRejectInvalidOldEmail() { } @Test - public void shouldRejectAlreadyUsedEmail() { + void shouldRejectAlreadyUsedEmail() { // given String newEmail = "new@example.com"; given(player.getName()).willReturn("Username"); @@ -209,7 +209,7 @@ public void shouldRejectAlreadyUsedEmail() { } @Test - public void shouldSendLoginMessage() { + void shouldSendLoginMessage() { // given given(player.getName()).willReturn("Bobby"); given(playerCache.isAuthenticated("bobby")).willReturn(false); @@ -225,7 +225,7 @@ public void shouldSendLoginMessage() { } @Test - public void shouldShowRegistrationMessage() { + void shouldShowRegistrationMessage() { // given given(player.getName()).willReturn("Bobby"); given(playerCache.isAuthenticated("bobby")).willReturn(false); @@ -241,7 +241,7 @@ public void shouldShowRegistrationMessage() { } @Test - public void shouldNotChangeOnCancelledEvent() { + void shouldNotChangeOnCancelledEvent() { // given String newEmail = "new@example.com"; String oldEmail = "old@example.com"; diff --git a/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java b/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java index 673282a477..4773614a85 100644 --- a/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java +++ b/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java @@ -15,20 +15,22 @@ import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer; import java.util.Arrays; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -42,8 +44,9 @@ /** * Test for {@link AsynchronousLogin}. */ -@RunWith(MockitoJUnitRunner.class) -public class AsynchronousLoginTest { +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(MockitoExtension.class) +class AsynchronousLoginTest { @InjectMocks @Spy @@ -60,13 +63,13 @@ public class AsynchronousLoginTest { @Mock private BukkitService bukkitService; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldNotForceLoginAlreadyLoggedInPlayer() { + void shouldNotForceLoginAlreadyLoggedInPlayer() { // given String name = "bobby"; Player player = mockPlayer(name); @@ -82,7 +85,7 @@ public void shouldNotForceLoginAlreadyLoggedInPlayer() { } @Test - public void shouldNotForceLoginNonExistentUser() { + void shouldNotForceLoginNonExistentUser() { // given String name = "oscar"; Player player = mockPlayer(name); @@ -99,7 +102,7 @@ public void shouldNotForceLoginNonExistentUser() { } @Test - public void shouldNotForceLoginInactiveUser() { + void shouldNotForceLoginInactiveUser() { // given String name = "oscar"; Player player = mockPlayer(name); @@ -120,7 +123,7 @@ public void shouldNotForceLoginInactiveUser() { } @Test - public void shouldNotForceLoginUserWithAlreadyOnlineIp() { + void shouldNotForceLoginUserWithAlreadyOnlineIp() { // given String name = "oscar"; String ip = "1.1.1.245"; @@ -143,7 +146,7 @@ public void shouldNotForceLoginUserWithAlreadyOnlineIp() { } @Test - public void shouldNotForceLoginForCanceledEvent() { + void shouldNotForceLoginForCanceledEvent() { // given String name = "oscar"; String ip = "1.1.1.245"; @@ -169,11 +172,10 @@ public void shouldNotForceLoginForCanceledEvent() { verify(asynchronousLogin).hasReachedMaxLoggedInPlayersForIp(player, ip); } - @Test - public void shouldPassMaxLoginPerIpCheck() { + void shouldPassMaxLoginPerIpCheck() { // given - Player player = mockPlayer("Carl"); + Player player = mock(Player.class); given(commonService.getProperty(RestrictionSettings.MAX_LOGIN_PER_IP)).willReturn(2); given(commonService.hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)).willReturn(false); mockOnlinePlayersInBukkitService(); @@ -188,9 +190,9 @@ public void shouldPassMaxLoginPerIpCheck() { } @Test - public void shouldSkipIpCheckForZeroThreshold() { + void shouldSkipIpCheckForZeroThreshold() { // given - Player player = mockPlayer("Fiona"); + Player player = mock(Player.class); given(commonService.getProperty(RestrictionSettings.MAX_LOGIN_PER_IP)).willReturn(0); // when @@ -202,9 +204,9 @@ public void shouldSkipIpCheckForZeroThreshold() { } @Test - public void shouldSkipIpCheckForPlayerWithMultipleAccountsPermission() { + void shouldSkipIpCheckForPlayerWithMultipleAccountsPermission() { // given - Player player = mockPlayer("Frank"); + Player player = mock(Player.class); given(commonService.getProperty(RestrictionSettings.MAX_LOGIN_PER_IP)).willReturn(1); given(commonService.hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)).willReturn(true); @@ -218,9 +220,9 @@ public void shouldSkipIpCheckForPlayerWithMultipleAccountsPermission() { } @Test - public void shouldFailIpCheckForIpWithTooManyPlayersOnline() { + void shouldFailIpCheckForIpWithTooManyPlayersOnline() { // given - Player player = mockPlayer("Ian"); + Player player = mock(Player.class); given(commonService.getProperty(RestrictionSettings.MAX_LOGIN_PER_IP)).willReturn(2); given(commonService.hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)).willReturn(false); mockOnlinePlayersInBukkitService(); @@ -234,7 +236,7 @@ public void shouldFailIpCheckForIpWithTooManyPlayersOnline() { verify(bukkitService).getOnlinePlayers(); } - private static Player mockPlayer(String name) { + private Player mockPlayer(String name) { Player player = mock(Player.class); given(player.getName()).willReturn(name); return player; @@ -267,5 +269,4 @@ private void mockOnlinePlayersInBukkitService() { List onlinePlayers = Arrays.asList(playerA, playerB, playerC, playerD, playerE, playerF); given(bukkitService.getOnlinePlayers()).willReturn(onlinePlayers); } - } diff --git a/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java b/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java index 00e8be2407..e2e7656d63 100644 --- a/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java +++ b/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java @@ -15,11 +15,11 @@ import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.function.Function; @@ -33,8 +33,8 @@ /** * Test for {@link AsyncRegister}. */ -@RunWith(MockitoJUnitRunner.class) -public class AsyncRegisterTest { +@ExtendWith(MockitoExtension.class) +class AsyncRegisterTest { @InjectMocks private AsyncRegister asyncRegister; @@ -51,50 +51,44 @@ public class AsyncRegisterTest { private SingletonStore registrationExecutorStore; @Test - public void shouldDetectAlreadyLoggedInPlayer() { + void shouldDetectAlreadyLoggedInPlayer() { // given String name = "robert"; Player player = mockPlayerWithName(name); given(playerCache.isAuthenticated(name)).willReturn(true); - RegistrationExecutor executor = mock(RegistrationExecutor.class); - singletonStoreWillReturn(registrationExecutorStore, executor); // when asyncRegister.register(RegistrationMethod.PASSWORD_REGISTRATION, PasswordRegisterParams.of(player, "abc", null)); // then verify(commonService).send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); - verifyNoInteractions(dataSource, executor); + verifyNoInteractions(dataSource, registrationExecutorStore); } @Test - public void shouldStopForDisabledRegistration() { + void shouldStopForDisabledRegistration() { // given String name = "albert"; Player player = mockPlayerWithName(name); given(playerCache.isAuthenticated(name)).willReturn(false); given(commonService.getProperty(RegistrationSettings.IS_ENABLED)).willReturn(false); - RegistrationExecutor executor = mock(RegistrationExecutor.class); - singletonStoreWillReturn(registrationExecutorStore, executor); // when asyncRegister.register(RegistrationMethod.TWO_FACTOR_REGISTRATION, TwoFactorRegisterParams.of(player)); // then verify(commonService).send(player, MessageKey.REGISTRATION_DISABLED); - verifyNoInteractions(dataSource, executor); + verifyNoInteractions(dataSource, registrationExecutorStore); } @Test - public void shouldStopForAlreadyRegisteredName() { + void shouldStopForAlreadyRegisteredName() { // given String name = "dilbert"; Player player = mockPlayerWithName(name); given(playerCache.isAuthenticated(name)).willReturn(false); given(commonService.getProperty(RegistrationSettings.IS_ENABLED)).willReturn(true); given(dataSource.isAuthAvailable(name)).willReturn(true); - RegistrationExecutor executor = mock(RegistrationExecutor.class); - singletonStoreWillReturn(registrationExecutorStore, executor); // when asyncRegister.register(RegistrationMethod.TWO_FACTOR_REGISTRATION, TwoFactorRegisterParams.of(player)); @@ -102,22 +96,19 @@ public void shouldStopForAlreadyRegisteredName() { // then verify(commonService).send(player, MessageKey.NAME_ALREADY_REGISTERED); verify(dataSource, only()).isAuthAvailable(name); - verifyNoInteractions(executor); + verifyNoInteractions(registrationExecutorStore); } @Test @SuppressWarnings("unchecked") - public void shouldStopForCanceledEvent() { + void shouldStopForCanceledEvent() { // given String name = "edbert"; Player player = mockPlayerWithName(name); - TestHelper.mockIpAddressToPlayer(player, "33.44.55.66"); given(playerCache.isAuthenticated(name)).willReturn(false); given(commonService.getProperty(RegistrationSettings.IS_ENABLED)).willReturn(true); given(dataSource.isAuthAvailable(name)).willReturn(false); - RegistrationExecutor executor = mock(RegistrationExecutor.class); TwoFactorRegisterParams params = TwoFactorRegisterParams.of(player); - singletonStoreWillReturn(registrationExecutorStore, executor); AuthMeAsyncPreRegisterEvent canceledEvent = new AuthMeAsyncPreRegisterEvent(player, true); canceledEvent.setCanRegister(false); @@ -128,11 +119,12 @@ public void shouldStopForCanceledEvent() { // then verify(dataSource, only()).isAuthAvailable(name); + verifyNoInteractions(registrationExecutorStore); } @Test @SuppressWarnings("unchecked") - public void shouldStopForFailedExecutorCheck() { + void shouldStopForFailedExecutorCheck() { // given String name = "edbert"; Player player = mockPlayerWithName(name); diff --git a/src/test/java/fr/xephi/authme/process/register/executors/EmailRegisterExecutorTest.java b/src/test/java/fr/xephi/authme/process/register/executors/EmailRegisterExecutorTest.java index a52b0075d4..eb3f06f55a 100644 --- a/src/test/java/fr/xephi/authme/process/register/executors/EmailRegisterExecutorTest.java +++ b/src/test/java/fr/xephi/authme/process/register/executors/EmailRegisterExecutorTest.java @@ -12,18 +12,18 @@ import fr.xephi.authme.service.CommonService; import fr.xephi.authme.settings.properties.EmailSettings; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.AuthMeMatchers.hasAuthBasicData; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -33,8 +33,8 @@ /** * Test for {@link EmailRegisterExecutor}. */ -@RunWith(MockitoJUnitRunner.class) -public class EmailRegisterExecutorTest { +@ExtendWith(MockitoExtension.class) +class EmailRegisterExecutorTest { @InjectMocks private EmailRegisterExecutor executor; @@ -51,7 +51,7 @@ public class EmailRegisterExecutorTest { private PasswordSecurity passwordSecurity; @Test - public void shouldNotPassEmailValidation() { + void shouldNotPassEmailValidation() { // given given(commonService.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); String email = "test@example.com"; @@ -70,7 +70,7 @@ public void shouldNotPassEmailValidation() { } @Test - public void shouldPassVerificationForPlayerWithPermission() { + void shouldPassVerificationForPlayerWithPermission() { // given given(commonService.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); Player player = mock(Player.class); @@ -86,7 +86,7 @@ public void shouldPassVerificationForPlayerWithPermission() { } @Test - public void shouldPassVerificationForPreviouslyUnregisteredIp() { + void shouldPassVerificationForPreviouslyUnregisteredIp() { // given given(commonService.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(1); String email = "test@example.com"; @@ -104,7 +104,7 @@ public void shouldPassVerificationForPreviouslyUnregisteredIp() { } @Test - public void shouldCreatePlayerAuth() { + void shouldCreatePlayerAuth() { // given given(commonService.getProperty(EmailSettings.RECOVERY_PASSWORD_LENGTH)).willReturn(12); given(passwordSecurity.computeHash(anyString(), anyString())).willAnswer( @@ -125,7 +125,7 @@ public void shouldCreatePlayerAuth() { } @Test - public void shouldPerformActionAfterDataSourceSave() { + void shouldPerformActionAfterDataSourceSave() { // given given(emailService.sendPasswordMail(anyString(), anyString(), anyString())).willReturn(true); Player player = mock(Player.class); @@ -143,7 +143,7 @@ public void shouldPerformActionAfterDataSourceSave() { } @Test - public void shouldHandleEmailSendingFailure() { + void shouldHandleEmailSendingFailure() { // given given(emailService.sendPasswordMail(anyString(), anyString(), anyString())).willReturn(false); Player player = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/process/register/executors/PasswordRegisterExecutorTest.java b/src/test/java/fr/xephi/authme/process/register/executors/PasswordRegisterExecutorTest.java index 7e2e5fd010..fabf1086d1 100644 --- a/src/test/java/fr/xephi/authme/process/register/executors/PasswordRegisterExecutorTest.java +++ b/src/test/java/fr/xephi/authme/process/register/executors/PasswordRegisterExecutorTest.java @@ -14,19 +14,19 @@ import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.AuthMeMatchers.equalToHash; import static fr.xephi.authme.AuthMeMatchers.hasAuthBasicData; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -36,8 +36,8 @@ /** * Test for {@link PasswordRegisterExecutor}. */ -@RunWith(MockitoJUnitRunner.class) -public class PasswordRegisterExecutorTest { +@ExtendWith(MockitoExtension.class) +class PasswordRegisterExecutorTest { @InjectMocks private PasswordRegisterExecutor executor; @@ -56,7 +56,7 @@ public class PasswordRegisterExecutorTest { private AsynchronousLogin asynchronousLogin; @Test - public void shouldCheckPasswordValidity() { + void shouldCheckPasswordValidity() { // given String password = "myPass"; String name = "player040"; @@ -73,7 +73,7 @@ public void shouldCheckPasswordValidity() { } @Test - public void shouldDetectInvalidPasswordAndInformPlayer() { + void shouldDetectInvalidPasswordAndInformPlayer() { // given String password = "myPass"; String name = "player040"; @@ -92,7 +92,7 @@ public void shouldDetectInvalidPasswordAndInformPlayer() { } @Test - public void shouldCreatePlayerAuth() { + void shouldCreatePlayerAuth() { // given given(passwordSecurity.computeHash(anyString(), anyString())).willAnswer( invocation -> new HashedPassword(invocation.getArgument(0))); @@ -111,7 +111,7 @@ public void shouldCreatePlayerAuth() { } @Test - public void shouldLogPlayerIn() { + void shouldLogPlayerIn() { // given given(commonService.getProperty(RegistrationSettings.FORCE_LOGIN_AFTER_REGISTER)).willReturn(false); given(commonService.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(false); @@ -128,7 +128,7 @@ public void shouldLogPlayerIn() { } @Test - public void shouldNotLogPlayerIn() { + void shouldNotLogPlayerIn() { // given given(commonService.getProperty(RegistrationSettings.FORCE_LOGIN_AFTER_REGISTER)).willReturn(true); Player player = mock(Player.class); diff --git a/src/test/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelperTest.java b/src/test/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelperTest.java index cbe460dfb9..6ec0fed1b4 100644 --- a/src/test/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelperTest.java +++ b/src/test/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelperTest.java @@ -4,23 +4,23 @@ import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.security.crypts.HashedPassword; import org.bukkit.entity.Player; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static fr.xephi.authme.AuthMeMatchers.equalToHash; import static fr.xephi.authme.AuthMeMatchers.hasAuthBasicData; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link PlayerAuthBuilderHelper}. */ -public class PlayerAuthBuilderHelperTest { +class PlayerAuthBuilderHelperTest { @Test - public void shouldConstructPlayerAuth() { + void shouldConstructPlayerAuth() { // given Player player = mock(Player.class); given(player.getName()).willReturn("Noah"); diff --git a/src/test/java/fr/xephi/authme/process/unregister/AsynchronousUnregisterTest.java b/src/test/java/fr/xephi/authme/process/unregister/AsynchronousUnregisterTest.java index 99d736ddab..2eda4a4e38 100644 --- a/src/test/java/fr/xephi/authme/process/unregister/AsynchronousUnregisterTest.java +++ b/src/test/java/fr/xephi/authme/process/unregister/AsynchronousUnregisterTest.java @@ -20,19 +20,19 @@ import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.function.Function; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -44,8 +44,8 @@ /** * Test for {@link AsynchronousUnregister}. */ -@RunWith(MockitoJUnitRunner.class) -public class AsynchronousUnregisterTest { +@ExtendWith(MockitoExtension.class) +class AsynchronousUnregisterTest { @InjectMocks private AsynchronousUnregister asynchronousUnregister; @@ -69,13 +69,13 @@ public class AsynchronousUnregisterTest { @Mock private BungeeSender bungeeSender; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldRejectWrongPassword() { + void shouldRejectWrongPassword() { // given Player player = mock(Player.class); String name = "Bobby"; @@ -98,7 +98,7 @@ public void shouldRejectWrongPassword() { } @Test - public void shouldPerformUnregister() { + void shouldPerformUnregister() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -131,7 +131,7 @@ public void shouldPerformUnregister() { } @Test - public void shouldPerformUnregisterAndNotApplyBlindEffect() { + void shouldPerformUnregisterAndNotApplyBlindEffect() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -163,7 +163,7 @@ public void shouldPerformUnregisterAndNotApplyBlindEffect() { } @Test - public void shouldNotApplyUnregisteredEffectsForNotForcedRegistration() { + void shouldNotApplyUnregisteredEffectsForNotForcedRegistration() { // given Player player = mock(Player.class); String name = "__FranK"; @@ -192,7 +192,7 @@ public void shouldNotApplyUnregisteredEffectsForNotForcedRegistration() { } @Test - public void shouldHandleDatabaseError() { + void shouldHandleDatabaseError() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -216,7 +216,7 @@ public void shouldHandleDatabaseError() { } @Test - public void shouldNotTeleportOfflinePlayer() { + void shouldNotTeleportOfflinePlayer() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -243,7 +243,7 @@ public void shouldNotTeleportOfflinePlayer() { // Initiator known and Player object available @Test - public void shouldPerformAdminUnregister() { + void shouldPerformAdminUnregister() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -268,7 +268,7 @@ public void shouldPerformAdminUnregister() { } @Test - public void shouldPerformAdminUnregisterWithoutInitiatorOrPlayer() { + void shouldPerformAdminUnregisterWithoutInitiatorOrPlayer() { // given String name = "billy"; given(dataSource.removeAuth(name)).willReturn(true); @@ -284,7 +284,7 @@ public void shouldPerformAdminUnregisterWithoutInitiatorOrPlayer() { } @Test - public void shouldHandleDatabaseErrorForAdminUnregister() { + void shouldHandleDatabaseErrorForAdminUnregister() { // given String name = "TtOoLl"; CommandSender initiator = mock(CommandSender.class); diff --git a/src/test/java/fr/xephi/authme/security/HashAlgorithmIntegrationTest.java b/src/test/java/fr/xephi/authme/security/HashAlgorithmIntegrationTest.java index 8ebcbda1e5..523d5b195c 100644 --- a/src/test/java/fr/xephi/authme/security/HashAlgorithmIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/security/HashAlgorithmIntegrationTest.java @@ -12,29 +12,29 @@ import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.StringUtils; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Integration test for {@link HashAlgorithm}. */ -public class HashAlgorithmIntegrationTest { +class HashAlgorithmIntegrationTest { private static Injector injector; - @BeforeClass - public static void setUpConfigAndInjector() { + @BeforeAll + static void setUpConfigAndInjector() { Settings settings = mock(Settings.class); given(settings.getProperty(HooksSettings.BCRYPT_LOG2_ROUND)).willReturn(8); given(settings.getProperty(SecuritySettings.DOUBLE_MD5_SALT_LENGTH)).willReturn(16); @@ -45,7 +45,7 @@ public static void setUpConfigAndInjector() { } @Test - public void shouldHaveUniqueClassForEntries() { + void shouldHaveUniqueClassForEntries() { // given Set> classes = new HashSet<>(); @@ -60,7 +60,7 @@ public void shouldHaveUniqueClassForEntries() { } @Test - public void shouldBeAbleToInstantiateEncryptionAlgorithms() { + void shouldBeAbleToInstantiateEncryptionAlgorithms() { // given / when / then for (HashAlgorithm algorithm : HashAlgorithm.values()) { if (!HashAlgorithm.CUSTOM.equals(algorithm) && !HashAlgorithm.PLAINTEXT.equals(algorithm)) { @@ -82,7 +82,7 @@ public void shouldBeAbleToInstantiateEncryptionAlgorithms() { } @Test - public void shouldBeDeprecatedIfEncryptionClassIsDeprecated() throws NoSuchFieldException { + void shouldBeDeprecatedIfEncryptionClassIsDeprecated() throws NoSuchFieldException { // given List failedEntries = new LinkedList<>(); diff --git a/src/test/java/fr/xephi/authme/security/HashUtilsTest.java b/src/test/java/fr/xephi/authme/security/HashUtilsTest.java index 16cba7043f..6f86aebe0f 100644 --- a/src/test/java/fr/xephi/authme/security/HashUtilsTest.java +++ b/src/test/java/fr/xephi/authme/security/HashUtilsTest.java @@ -1,19 +1,19 @@ package fr.xephi.authme.security; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.security.MessageDigest; import java.util.ArrayList; 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.junit.Assert.assertThat; /** * Test for {@link HashUtils}. */ -public class HashUtilsTest { +class HashUtilsTest { /** * List of passwords whose hash is provided to the class to test against. @@ -21,7 +21,7 @@ public class HashUtilsTest { private static final String[] GIVEN_PASSWORDS = {"", "password", "PassWord1", "&^%te$t?Pw@_"}; @Test - public void shouldHashMd5() { + void shouldHashMd5() { // given String[] correctHashes = { "d41d8cd98f00b204e9800998ecf8427e", // empty string @@ -41,7 +41,7 @@ public void shouldHashMd5() { } @Test - public void shouldHashSha1() { + void shouldHashSha1() { // given String[] correctHashes = { "da39a3ee5e6b4b0d3255bfef95601890afd80709", // empty string @@ -61,7 +61,7 @@ public void shouldHashSha1() { } @Test - public void shouldHashSha256() { + void shouldHashSha256() { // given String[] correctHashes = { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", // empty string @@ -82,7 +82,7 @@ public void shouldHashSha256() { @Test - public void shouldHashSha512() { + void shouldHashSha512() { // given String[] correctHashes = { "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", // empty string @@ -102,7 +102,7 @@ public void shouldHashSha512() { } @Test - public void shouldRetrieveMd5Instance() { + void shouldRetrieveMd5Instance() { // given MessageDigestAlgorithm algorithm = MessageDigestAlgorithm.MD5; @@ -114,7 +114,7 @@ public void shouldRetrieveMd5Instance() { } @Test - public void shouldCheckForValidBcryptHashStart() { + void shouldCheckForValidBcryptHashStart() { // given / when / then assertThat(HashUtils.isValidBcryptHash(""), equalTo(false)); assertThat(HashUtils.isValidBcryptHash("$2"), equalTo(false)); @@ -125,7 +125,7 @@ public void shouldCheckForValidBcryptHashStart() { } @Test - public void shouldCompareStrings() { + void shouldCompareStrings() { // given / when / then assertThat(HashUtils.isEqual("test", "test"), equalTo(true)); assertThat(HashUtils.isEqual("test", "Test"), equalTo(false)); diff --git a/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java b/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java index aa3165e767..0f8400724c 100644 --- a/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java +++ b/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java @@ -3,9 +3,6 @@ import ch.jalu.injector.Injector; import ch.jalu.injector.InjectorBuilder; import ch.jalu.injector.factory.Factory; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; @@ -19,11 +16,14 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.event.Event; import org.bukkit.plugin.PluginManager; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import java.util.Collections; @@ -31,10 +31,10 @@ import java.util.Set; import static com.google.common.collect.Sets.newHashSet; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -48,10 +48,10 @@ /** * Test for {@link PasswordSecurity}. */ -@RunWith(DelayedInjectionRunner.class) -public class PasswordSecurityTest { +@ExtendWith(MockitoExtension.class) +class PasswordSecurityTest { - @InjectDelayed + @InjectMocks private PasswordSecurity passwordSecurity; @Mock @@ -71,13 +71,13 @@ public class PasswordSecurityTest { private Class caughtClassInEvent; - @BeforeClass - public static void setUpTest() { + @BeforeAll + static void setUpTest() { TestHelper.setupLogger(); } - @BeforeInjecting - public void setUpMocks() { + @BeforeEach + void setUpMocks() { caughtClassInEvent = null; // When the password encryption event is emitted, replace the encryption method with our mock. @@ -111,10 +111,12 @@ public Void answer(InvocationOnMock invocation) throws Throwable { } return o; }); + + ReflectionTestUtils.invokePostConstructMethods(passwordSecurity); } @Test - public void shouldReturnPasswordMatch() { + void shouldReturnPasswordMatch() { // given HashedPassword password = new HashedPassword("$TEST$10$SOME_HASH", null); String playerName = "Tester"; @@ -136,7 +138,7 @@ public void shouldReturnPasswordMatch() { } @Test - public void shouldReturnPasswordMismatch() { + void shouldReturnPasswordMismatch() { // given HashedPassword password = new HashedPassword("$TEST$10$SOME_HASH", null); String playerName = "My_PLayer"; @@ -157,7 +159,7 @@ public void shouldReturnPasswordMismatch() { } @Test - public void shouldReturnFalseIfPlayerDoesNotExist() { + void shouldReturnFalseIfPlayerDoesNotExist() { // given String playerName = "bobby"; String clearTextPass = "tables"; @@ -173,7 +175,7 @@ public void shouldReturnFalseIfPlayerDoesNotExist() { } @Test - public void shouldTryOtherMethodsForFailedPassword() { + void shouldTryOtherMethodsForFailedPassword() { // given // BCRYPT hash for "Test" HashedPassword password = @@ -206,7 +208,7 @@ public void shouldTryOtherMethodsForFailedPassword() { } @Test - public void shouldTryLegacyMethodsAndFail() { + void shouldTryLegacyMethodsAndFail() { // given HashedPassword password = new HashedPassword("hashNotMatchingAnyMethod", "someBogusSalt"); String playerName = "asfd"; @@ -227,7 +229,7 @@ public void shouldTryLegacyMethodsAndFail() { } @Test - public void shouldHashPassword() { + void shouldHashPassword() { // given String password = "MyP@ssword"; String username = "theUserInTest"; @@ -248,7 +250,7 @@ public void shouldHashPassword() { } @Test - public void shouldSkipCheckIfMandatorySaltIsUnavailable() { + void shouldSkipCheckIfMandatorySaltIsUnavailable() { // given String password = "?topSecretPass\\"; String username = "someone12"; @@ -269,7 +271,7 @@ public void shouldSkipCheckIfMandatorySaltIsUnavailable() { } @Test - public void shouldReloadSettings() { + void shouldReloadSettings() { // given given(settings.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.MD5); given(settings.getProperty(SecuritySettings.LEGACY_HASHES)) diff --git a/src/test/java/fr/xephi/authme/security/crypts/AbstractEncryptionMethodTest.java b/src/test/java/fr/xephi/authme/security/crypts/AbstractEncryptionMethodTest.java index 6a96425fc8..91bb549550 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/AbstractEncryptionMethodTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/AbstractEncryptionMethodTest.java @@ -4,18 +4,16 @@ import com.google.common.collect.ImmutableMap; import fr.xephi.authme.TestHelper; import fr.xephi.authme.security.crypts.description.AsciiRestricted; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Locale; import java.util.Map; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; /** * Test for implementations of {@link EncryptionMethod}. @@ -97,12 +95,12 @@ public AbstractEncryptionMethodTest(EncryptionMethod method, HashedPassword resu GIVEN_PASSWORDS[3], result3); } - @BeforeClass - public static void setupLogger() { + @BeforeAll + static void setupLogger() { TestHelper.setupLogger(); } - protected void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean isConstructorWithSalt) { + void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean isConstructorWithSalt) { if (isConstructorWithSalt && !method.hasSeparateSalt()) { throw new UnsupportedOperationException("Salt is not stored separately, so test should be initialized" + " with the password hashes only. Use the other constructor"); @@ -113,14 +111,14 @@ protected void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean i } @Test - public void testGivenPasswords() { + void testGivenPasswords() { // Start with the 2nd to last password if we skip long tests int start = SKIP_LONG_TESTS ? GIVEN_PASSWORDS.length - 2 : 0; // Test entries in GIVEN_PASSWORDS except the last one for (int i = start; i < GIVEN_PASSWORDS.length - 1; ++i) { String password = GIVEN_PASSWORDS[i]; - assertTrue("Hash for password '" + password + "' should match", - doesGivenHashMatch(password, method)); + assertThat("Hash for password '" + password + "' should match", + doesGivenHashMatch(password, method), equalTo(true)); } // Note #375: Windows console seems to use its own character encoding (Windows-1252?) and it seems impossible to @@ -135,7 +133,7 @@ public void testGivenPasswords() { } @Test - public void testPasswordEquality() { + void testPasswordEquality() { List internalPasswords = method.getClass().isAnnotationPresent(AsciiRestricted.class) ? INTERNAL_PASSWORDS.subList(0, INTERNAL_PASSWORDS.size() - 1) : INTERNAL_PASSWORDS; @@ -151,30 +149,30 @@ public void testPasswordEquality() { hash, equalTo(method.computeHash(password, salt, USERNAME))); } - assertTrue("Generated hash for '" + password + "' should match password (hash = '" + hash + "')", - method.comparePassword(password, hashedPassword, USERNAME)); - assumeThat(SKIP_LONG_TESTS, equalTo(false)); + assertThat("Generated hash for '" + password + "' should match password (hash = '" + hash + "')", + method.comparePassword(password, hashedPassword, USERNAME), equalTo(true)); + assumeFalse(SKIP_LONG_TESTS); if (!password.equals(password.toLowerCase(Locale.ROOT))) { - assertFalse("Lower-case of '" + password + "' should not match generated hash '" + hash + "'", - method.comparePassword(password.toLowerCase(Locale.ROOT), hashedPassword, USERNAME)); + assertThat("Lower-case of '" + password + "' should not match generated hash '" + hash + "'", + method.comparePassword(password.toLowerCase(), hashedPassword, USERNAME), equalTo(false)); } if (!password.equals(password.toUpperCase(Locale.ROOT))) { - assertFalse("Upper-case of '" + password + "' should not match generated hash '" + hash + "'", - method.comparePassword(password.toUpperCase(Locale.ROOT), hashedPassword, USERNAME)); + assertThat("Upper-case of '" + password + "' should not match generated hash '" + hash + "'", + method.comparePassword(password.toUpperCase(), hashedPassword, USERNAME), equalTo(false)); } } } /** Tests various strings to ensure that encryption methods don't rely on the hash's format too much. */ @Test - public void testMalformedHashes() { - assumeThat(SKIP_LONG_TESTS, equalTo(false)); + void testMalformedHashes() { + assumeFalse(SKIP_LONG_TESTS); String salt = method.hasSeparateSalt() ? "testSalt" : null; for (String bogusHash : BOGUS_HASHES) { HashedPassword hashedPwd = new HashedPassword(bogusHash, salt); - assertFalse("Passing bogus hash '" + bogusHash + "' does not result in an error", - method.comparePassword("Password", hashedPwd, "player")); + assertThat("Passing bogus hash '" + bogusHash + "' does not result in an error", + method.comparePassword("Password", hashedPwd, "player"), equalTo(false)); } } diff --git a/src/test/java/fr/xephi/authme/security/crypts/Argon2Test.java b/src/test/java/fr/xephi/authme/security/crypts/Argon2Test.java index 46b315d567..c6d8182b88 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Argon2Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Argon2Test.java @@ -1,24 +1,22 @@ package fr.xephi.authme.security.crypts; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Test for {@link Argon2}. */ -public class Argon2Test extends AbstractEncryptionMethodTest { +class Argon2Test extends AbstractEncryptionMethodTest { private static final boolean IS_LIBRARY_LOADED = Argon2.isLibraryLoaded(); - public Argon2Test() { + Argon2Test() { super(new Argon2(), "$argon2i$v=19$m=65536,t=2,p=1$dOP8NiXsPTcMgzI4Z8Rbew$ShdowtoTEWTL5UTFz1UgQOigb9JOlm4ZxWPA6WbIeUw", // password "$argon2i$v=19$m=65536,t=2,p=1$amZHbPfgc5peKd/4w1AI1g$Q2PUiOVw47TACijP57U0xf7QfiZ00HV4eFzMDA6yKRE", // PassWord1 "$argon2i$v=19$m=65536,t=2,p=1$58v7dWNn9/bpD00QLzSebw$7cMC7p0qceE3Mgf2yQp4X7c+UkO9oyJwQ7S6XTBubNs", // &^%te$t?Pw@_ "$argon2i$v=19$m=65536,t=2,p=1$93OSU71DgBOzpmhti7+6rQ$sSSI6QQQdoG9DlGwLjYz576kTek89nwr9CyNpy6bsL0"); // âË_3(íù* - assumeThat("Argon2 library is not loaded - skipping test", - IS_LIBRARY_LOADED, equalTo(true)); + assumeTrue(IS_LIBRARY_LOADED, "Argon2 library is not loaded - skipping test"); } @Override diff --git a/src/test/java/fr/xephi/authme/security/crypts/BCrypt2yTest.java b/src/test/java/fr/xephi/authme/security/crypts/BCrypt2yTest.java index f34bac6224..291d6baf7c 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/BCrypt2yTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/BCrypt2yTest.java @@ -1,17 +1,17 @@ package fr.xephi.authme.security.crypts; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; /** * Test for {@link BCrypt2y}. */ -public class BCrypt2yTest extends AbstractEncryptionMethodTest { +class BCrypt2yTest extends AbstractEncryptionMethodTest { - public BCrypt2yTest() { + BCrypt2yTest() { super(new BCrypt2y(), "$2y$10$da641e404b982edf1c7c0uTU9BcKzfA2vWKV05q6r.dCvm/93wqVK", // password "$2y$10$e52c48a76f5b86f5da899uiK/HYocyPsfQXESNbP278rIz08LKEP2", // PassWord1 @@ -20,7 +20,7 @@ public BCrypt2yTest() { } @Test - public void shouldGenerateWith2yPrefixAndCostFactor10() { + void shouldGenerateWith2yPrefixAndCostFactor10() { // given BCrypt2y bCrypt2y = new BCrypt2y(); diff --git a/src/test/java/fr/xephi/authme/security/crypts/BCryptTest.java b/src/test/java/fr/xephi/authme/security/crypts/BCryptTest.java index 9c3946f1c5..8a62070469 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/BCryptTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/BCryptTest.java @@ -2,19 +2,19 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.HooksSettings; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link BCrypt}. */ -public class BCryptTest extends AbstractEncryptionMethodTest { +class BCryptTest extends AbstractEncryptionMethodTest { - public BCryptTest() { + BCryptTest() { super(new BCrypt(mockSettings()), "$2a$10$6iATmYgwJVc3YONhVcZFve3Cfb5GnwvKhJ20r.hMjmcNkIT9.Uh9K", // password "$2a$10$LOhUxhEcS0vgDPv/jkXvCurNb7LjP9xUlEolJGk.Uhgikqc6FtIOi", // PassWord1 @@ -24,7 +24,7 @@ public BCryptTest() { } @Test - public void shouldGenerateWith2aPrefix() { + void shouldGenerateWith2aPrefix() { // given BCrypt bCrypt = new BCrypt(mockSettings()); diff --git a/src/test/java/fr/xephi/authme/security/crypts/CmwCryptTest.java b/src/test/java/fr/xephi/authme/security/crypts/CmwCryptTest.java index 7c6652db1f..8ac0300c4e 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/CmwCryptTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/CmwCryptTest.java @@ -3,9 +3,9 @@ /** * Test for {@link CmwCrypt}. */ -public class CmwCryptTest extends AbstractEncryptionMethodTest { +class CmwCryptTest extends AbstractEncryptionMethodTest { - public CmwCryptTest() { + CmwCryptTest() { super(new CmwCrypt(), "1619d7adc23f4f633f11014d2f22b7d8", // password "c651798d2d9da38f86654107ae60c86a", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/CrazyCrypt1Test.java b/src/test/java/fr/xephi/authme/security/crypts/CrazyCrypt1Test.java index f98ece5ab4..ed195201d6 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/CrazyCrypt1Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/CrazyCrypt1Test.java @@ -3,9 +3,9 @@ /** * Test for {@link CrazyCrypt1}. */ -public class CrazyCrypt1Test extends AbstractEncryptionMethodTest { +class CrazyCrypt1Test extends AbstractEncryptionMethodTest { - public CrazyCrypt1Test() { + CrazyCrypt1Test() { super(new CrazyCrypt1(), "d5c76eb36417d4e97ec62609619e40a9e549a2598d0dab5a7194fd997a9305af78de2b93f958e150d19dd1e7f821043379ddf5f9c7f352bf27df91ae4913f3e8", // password "49c63f827c88196871e344e589bd46cc4fa6db3c27801bbad5374c0d216381977627c1d76f2114667d5dd117e046f7493eb06e4f461f4f848aa08f6f40a3e934", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/DoubleMd5Test.java b/src/test/java/fr/xephi/authme/security/crypts/DoubleMd5Test.java index cc12df9e5a..415e537c7a 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/DoubleMd5Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/DoubleMd5Test.java @@ -3,9 +3,9 @@ /** * Test for {@link DoubleMd5}. */ -public class DoubleMd5Test extends AbstractEncryptionMethodTest { +class DoubleMd5Test extends AbstractEncryptionMethodTest { - public DoubleMd5Test() { + DoubleMd5Test() { super(new DoubleMd5(), "696d29e0940a4957748fe3fc9efd22a3", // password "c77aa2024d9fb7233a2872452d601aba", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Ipb3Test.java b/src/test/java/fr/xephi/authme/security/crypts/Ipb3Test.java index 984f3d2179..c0d53319a3 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Ipb3Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Ipb3Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Ipb3}. */ -public class Ipb3Test extends AbstractEncryptionMethodTest { +class Ipb3Test extends AbstractEncryptionMethodTest { - public Ipb3Test() { + Ipb3Test() { super(new Ipb3(), new HashedPassword("f8ecea1ce42b5babef369ff7692dbe3f", "1715b"), //password new HashedPassword("40a93731a931352e0619cdf09b975040", "ba91c"), //PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Ipb4Test.java b/src/test/java/fr/xephi/authme/security/crypts/Ipb4Test.java index d019f3d791..d8e775b4c7 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Ipb4Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Ipb4Test.java @@ -1,19 +1,19 @@ package fr.xephi.authme.security.crypts; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link Ipb4}. */ -public class Ipb4Test extends AbstractEncryptionMethodTest { +class Ipb4Test extends AbstractEncryptionMethodTest { - public Ipb4Test() { + Ipb4Test() { super(new Ipb4(), new HashedPassword("$2a$13$leEvXu77OIwPwNvtZIJvaeAx8EItGHuR3nIlq8416g0gXeJaQdrr2", "leEvXu77OIwPwNvtZIJval"), //password new HashedPassword("$2a$13$xyTTP9zhQQtRRKIJPv5AuuOGJ6Ni9FLbDhcuIAcPjt3XzCxIWe3Uu", "xyTTP9zhQQtRRKIJPv5Au3"), //PassWord1 @@ -22,7 +22,7 @@ public Ipb4Test() { } @Test - public void shouldCreateHashesWith2aAndCostFactor13() { + void shouldCreateHashesWith2aAndCostFactor13() { // given Ipb4 hashMethod = new Ipb4(); @@ -35,7 +35,7 @@ public void shouldCreateHashesWith2aAndCostFactor13() { } @Test - public void shouldThrowForInvalidSalt() { + void shouldThrowForInvalidSalt() { // given Ipb4 hashMethod = new Ipb4(); diff --git a/src/test/java/fr/xephi/authme/security/crypts/JoomlaTest.java b/src/test/java/fr/xephi/authme/security/crypts/JoomlaTest.java index d2673b34c9..089dda93f5 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/JoomlaTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/JoomlaTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Joomla}. */ -public class JoomlaTest extends AbstractEncryptionMethodTest { +class JoomlaTest extends AbstractEncryptionMethodTest { - public JoomlaTest() { + JoomlaTest() { super(new Joomla(), "b18c99813cd96df3a706652f47177490:377c4aaf92c5ed57711306909e6065ca", // password "c5af71da91a8841d95937ba24a5b7fdb:07068e5850930b794526a614438cafc7", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Md5Test.java b/src/test/java/fr/xephi/authme/security/crypts/Md5Test.java index c079183715..86fbe895b4 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Md5Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Md5Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Md5}. */ -public class Md5Test extends AbstractEncryptionMethodTest { +class Md5Test extends AbstractEncryptionMethodTest { - public Md5Test() { + Md5Test() { super(new Md5(), "5f4dcc3b5aa765d61d8327deb882cf99", // password "f2126d405f46ed603ff5b2950f062c96", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Md5vBTest.java b/src/test/java/fr/xephi/authme/security/crypts/Md5vBTest.java index eac20fcd13..5a9d268c87 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Md5vBTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Md5vBTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Md5vB}. */ -public class Md5vBTest extends AbstractEncryptionMethodTest { +class Md5vBTest extends AbstractEncryptionMethodTest { - public Md5vBTest() { + Md5vBTest() { super(new Md5vB(), "$MD5vb$bd9832fffa287321$5006d371fcb813f2347987f902a024ad", // password "$MD5vb$5e492c1166b5a828$c954fa5ee561700a097826971653b57f", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/MyBBTest.java b/src/test/java/fr/xephi/authme/security/crypts/MyBBTest.java index fabd9f35df..f13fa72201 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/MyBBTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/MyBBTest.java @@ -3,9 +3,9 @@ /** * Test for {@link MyBB}. */ -public class MyBBTest extends AbstractEncryptionMethodTest { +class MyBBTest extends AbstractEncryptionMethodTest { - public MyBBTest() { + MyBBTest() { super(new MyBB(), new HashedPassword("57c7a16d860833db5030738f5a465d2b", "acdc14e6"), //password new HashedPassword("08fbdf721f2c42d9780b7d66df0ba830", "792fd7fb"), //PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2DjangoTest.java b/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2DjangoTest.java index a5a1af6160..040697a0f5 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2DjangoTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2DjangoTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Pbkdf2Django}. */ -public class Pbkdf2DjangoTest extends AbstractEncryptionMethodTest { +class Pbkdf2DjangoTest extends AbstractEncryptionMethodTest { - public Pbkdf2DjangoTest() { + Pbkdf2DjangoTest() { super(new Pbkdf2Django(), "pbkdf2_sha256$15000$50a7ff2d7e00$t7Qx2CfzMhGEbyCa3Wk5nJvNjj3N+FdxhpwJDerl4Fs=", // password "pbkdf2_sha256$15000$f9d8a58f3fe2$oMqmMGuJetdubW0cpubmT8CltQLjHT+L2GuwKsaWLx8=", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Test.java b/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Test.java index 8296e56ea0..aa4f7f5c6e 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Test.java @@ -2,19 +2,19 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.SecuritySettings; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link Pbkdf2}. */ -public class Pbkdf2Test extends AbstractEncryptionMethodTest { +class Pbkdf2Test extends AbstractEncryptionMethodTest { - public Pbkdf2Test() { + Pbkdf2Test() { super(new Pbkdf2(mockSettings()), "pbkdf2_sha256$10000$b25801311edf$093E38B16DFF13FCE5CD64D5D888EE6E0376A3E572FE5DA6749515EA0F384413223A21C464B0BE899E64084D1FFEFD44F2AC768453C87F41B42CC6954C416900", // password "pbkdf2_sha256$10000$fe705da06c57$A41527BD58FED9C9E6F452FC1BA8B0C4C4224ECC63E37F71EB1A0865D2AB81BBFEBCA9B7B6A6E8AEF4717B43F8EB6FB4EDEFFBB399D9D991EF7E23013595BAF0", // PassWord1 @@ -23,7 +23,7 @@ public Pbkdf2Test() { } @Test - public void shouldDetectMatchForHashWithOtherRoundNumber() { + void shouldDetectMatchForHashWithOtherRoundNumber() { // given Pbkdf2 pbkdf2 = new Pbkdf2(mockSettings()); String hash = "pbkdf2_sha256$4128$3469b0d48b702046$DC8A54351008C6054E12FB19E0BF8A4EA6D4165E0EDC97A1ECD15231037C382DE5BF85D07D5BC9D1ADF9BBFE4CE257C6059FB1B9FF65DB69D8B205F064BE0DA9"; diff --git a/src/test/java/fr/xephi/authme/security/crypts/PhpBBTest.java b/src/test/java/fr/xephi/authme/security/crypts/PhpBBTest.java index 743a7b46af..271073ecb0 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/PhpBBTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/PhpBBTest.java @@ -1,18 +1,18 @@ package fr.xephi.authme.security.crypts; import com.google.common.collect.ImmutableMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Map; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link PhpBB}. */ -public class PhpBBTest extends AbstractEncryptionMethodTest { +class PhpBBTest extends AbstractEncryptionMethodTest { - public PhpBBTest() { + PhpBBTest() { super(new PhpBB(), "$2a$10$1rnuna3GBduBy1NQuOpnWODqBfl8CZHeULuBThNfAvkOYDRRQR1Zi", // password "$2a$10$F6LVgXa8.t95H0Fikr6nG.aEMgIQRXlFpzMvAjbO7ag3fny9GGS3i", // PassWord1 @@ -21,7 +21,7 @@ public PhpBBTest() { } @Test - public void shouldMatchPhpassSaltedMd5Hashes() { + void shouldMatchPhpassSaltedMd5Hashes() { // given Map givenHashes = ImmutableMap.of( "password", "$H$7MaSGQb0xe3Fp/a.Q.Ewpw.UKfCv.t0", @@ -39,7 +39,7 @@ public void shouldMatchPhpassSaltedMd5Hashes() { } @Test - public void shouldMatchUnsaltedMd5Hashes() { + void shouldMatchUnsaltedMd5Hashes() { // given Map givenHashes = ImmutableMap.of( "password", "5f4dcc3b5aa765d61d8327deb882cf99", diff --git a/src/test/java/fr/xephi/authme/security/crypts/PhpFusionTest.java b/src/test/java/fr/xephi/authme/security/crypts/PhpFusionTest.java index a08a6ad8c4..ff520fdd3e 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/PhpFusionTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/PhpFusionTest.java @@ -3,9 +3,9 @@ /** * Test for {@link PhpFusion}. */ -public class PhpFusionTest extends AbstractEncryptionMethodTest { +class PhpFusionTest extends AbstractEncryptionMethodTest { - public PhpFusionTest() { + PhpFusionTest() { super(new PhpFusion(), new HashedPassword("f7a606c4eb3fcfbc382906476e05b06f21234a77d1a4eacc0f93f503deb69e70", "6cd1c97c55cb"), // password new HashedPassword("8a9b7bb706a3347e5f684a7cb905bfb26b9a0d099358064139ab3ed1a66aeb2b", "d6012370b73f"), // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/RoyalAuthTest.java b/src/test/java/fr/xephi/authme/security/crypts/RoyalAuthTest.java index 7734dc03ad..06bc087c1c 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/RoyalAuthTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/RoyalAuthTest.java @@ -3,9 +3,9 @@ /** * Test for {@link RoyalAuth}. */ -public class RoyalAuthTest extends AbstractEncryptionMethodTest { +class RoyalAuthTest extends AbstractEncryptionMethodTest { - public RoyalAuthTest() { + RoyalAuthTest() { super(new RoyalAuth(), "5d21ef9236896bc4ac508e524e2da8a0def555dac1cdfc7259d62900d1d3f553826210c369870673ae2cf1c41abcf4f92670d76af1db044d33559324f5c2a339", // password "ecc685f4328bc54093c086ced66c5c11855e117ea22940632d5c0f55fff84d94bfdcc74e05f5d95bbdd052823a7057910748bc1c7a07af96b3e86731a4f11794", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Salted2Md5Test.java b/src/test/java/fr/xephi/authme/security/crypts/Salted2Md5Test.java index fc34a13fca..7463d332db 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Salted2Md5Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Salted2Md5Test.java @@ -9,9 +9,9 @@ /** * Test for {@link Salted2Md5}. */ -public class Salted2Md5Test extends AbstractEncryptionMethodTest { +class Salted2Md5Test extends AbstractEncryptionMethodTest { - public Salted2Md5Test() { + Salted2Md5Test() { super(new Salted2Md5(mockSettings()), new HashedPassword("9f3d13dc01a6fe61fd669954174399f3", "9b5f5749"), // password new HashedPassword("b28c32f624a4eb161d6adc9acb5bfc5b", "f750ba32"), // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/SaltedSha512Test.java b/src/test/java/fr/xephi/authme/security/crypts/SaltedSha512Test.java index 98ab061532..44614fedad 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/SaltedSha512Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/SaltedSha512Test.java @@ -3,9 +3,9 @@ /** * Test for {@link SaltedSha512}. */ -public class SaltedSha512Test extends AbstractEncryptionMethodTest { +class SaltedSha512Test extends AbstractEncryptionMethodTest { - public SaltedSha512Test() { + SaltedSha512Test() { super(new SaltedSha512(), new HashedPassword("dea7a37cecf5384ae8e347fd1411efb51364b6ba1b328695de3b354612c1d7010807e8b7051c40f740e498490e1f133e2c2408327d13fbdd68e1b1f6d548e624", "29f8a3c52147f987fee7ba3e0fb311bd"), // password new HashedPassword("7c06225aac574d2dc7c81a2ed306637adf025715f52083e05bdab014faaa234e24a97d0e69ea0108dfa77cc9228e58be319ee677e679b5d1ad168d40e50a42f6", "8ea37b85d020b98f60c0fe9b8ec9296c"), // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Sha1Test.java b/src/test/java/fr/xephi/authme/security/crypts/Sha1Test.java index 2bd5543f38..f3240a6b7a 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Sha1Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Sha1Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Sha1}. */ -public class Sha1Test extends AbstractEncryptionMethodTest { +class Sha1Test extends AbstractEncryptionMethodTest { - public Sha1Test() { + Sha1Test() { super(new Sha1(), "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", // password "285d0c707f9644b75e1a87a62f25d0efb56800f0", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Sha256Test.java b/src/test/java/fr/xephi/authme/security/crypts/Sha256Test.java index b9f751654b..9d55b38919 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Sha256Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Sha256Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Sha256}. */ -public class Sha256Test extends AbstractEncryptionMethodTest { +class Sha256Test extends AbstractEncryptionMethodTest { - public Sha256Test() { + Sha256Test() { super(new Sha256(), "$SHA$11aa0706173d7272$dbba96681c2ae4e0bfdf226d70fbbc5e4ee3d8071faa613bc533fe8a64817d10", // password "$SHA$3c72a18a29b08d40$8e50a7a4f69a80f4893dc921eac84bd74b3f9ebfa22908302c9965eac3aa45e5", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Sha512Test.java b/src/test/java/fr/xephi/authme/security/crypts/Sha512Test.java index 2871cd3a2e..ec98a48289 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Sha512Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Sha512Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Sha512}. */ -public class Sha512Test extends AbstractEncryptionMethodTest { +class Sha512Test extends AbstractEncryptionMethodTest { - public Sha512Test() { + Sha512Test() { super(new Sha512(), "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86", // password "ae9942149995a8171391625b36da134d5e288c721650d7c8d2d464fb49a49f3f551e4916ab1e097d9dd1201b01d69b1dccdefa3d2524a66092fb61b3df6e7e71", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/SmfTest.java b/src/test/java/fr/xephi/authme/security/crypts/SmfTest.java index 442d5194cd..8092f46c01 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/SmfTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/SmfTest.java @@ -1,17 +1,17 @@ package fr.xephi.authme.security.crypts; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link Smf}. */ -public class SmfTest extends AbstractEncryptionMethodTest { +class SmfTest extends AbstractEncryptionMethodTest { - public SmfTest() { + SmfTest() { super(new Smf(), "9b361c66977bb059d460a20d3c21fb3394772df5", // password "31a560bdd095a837945d46add1605108ba87b268", // PassWord1 @@ -20,14 +20,14 @@ public SmfTest() { } @Override - protected void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean isSaltConstructor) { + void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean isSaltConstructor) { // Smf declares to use a separate salt, but it's not used in the actual hashing mechanism, see Smf class Javadoc assertThat(method.hasSeparateSalt(), equalTo(true)); assertThat(isSaltConstructor, equalTo(false)); } @Test - public void shouldGenerateFourCharSalt() { + void shouldGenerateFourCharSalt() { // given EncryptionMethod method = new Smf(); diff --git a/src/test/java/fr/xephi/authme/security/crypts/TwoFactorTest.java b/src/test/java/fr/xephi/authme/security/crypts/TwoFactorTest.java index cdc2526704..85785df9cb 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/TwoFactorTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/TwoFactorTest.java @@ -1,24 +1,24 @@ package fr.xephi.authme.security.crypts; import fr.xephi.authme.TestHelper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link TwoFactor}. */ -public class TwoFactorTest { +class TwoFactorTest { - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldGenerateBarcodeUrl() { + void shouldGenerateBarcodeUrl() { // given String user = "tester"; String host = "192.168.0.4"; @@ -34,7 +34,7 @@ public void shouldGenerateBarcodeUrl() { } @Test - public void shouldHandleInvalidHash() { + void shouldHandleInvalidHash() { // given HashedPassword password = new HashedPassword("!@&#@!(*&@"); String inputPassword = "12345"; @@ -48,7 +48,7 @@ public void shouldHandleInvalidHash() { } @Test - public void shouldHandleInvalidInput() { + void shouldHandleInvalidInput() { // given HashedPassword password = new HashedPassword("3AK6Y4KWGRLJMEQW"); String inputPassword = "notA_number!"; diff --git a/src/test/java/fr/xephi/authme/security/crypts/Wbb3Test.java b/src/test/java/fr/xephi/authme/security/crypts/Wbb3Test.java index 7443253fe3..21b37c3608 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Wbb3Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Wbb3Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Wbb3}. */ -public class Wbb3Test extends AbstractEncryptionMethodTest { +class Wbb3Test extends AbstractEncryptionMethodTest { - public Wbb3Test() { + Wbb3Test() { super(new Wbb3(), new HashedPassword("8df818ef7d56075ab2744f74b98ad68a375ccac4", "b7415b355492ea60314f259a35733a3092c03e3f"), // password new HashedPassword("106da5cf5df92cb845e12cf62cbdb5235b6dc693", "6110f19b2b52910dccf592a19c59126873f42e69"), // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/Wbb4Test.java b/src/test/java/fr/xephi/authme/security/crypts/Wbb4Test.java index 6c5459f609..e588e95f8d 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/Wbb4Test.java +++ b/src/test/java/fr/xephi/authme/security/crypts/Wbb4Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Wbb4}. */ -public class Wbb4Test extends AbstractEncryptionMethodTest { +class Wbb4Test extends AbstractEncryptionMethodTest { - public Wbb4Test() { + Wbb4Test() { super(new Wbb4(), "$2a$08$7DGr.wROqEPe0Z3XJS7n5.k.QWehovLHbpI.UkdfRb4ns268WsR6C", // password "$2a$08$yWWVUA4PB4mqW.0wyIvV3OdoH492HuLk5L3iaqUrpRK2.2zn08d/K", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/WhirlpoolTest.java b/src/test/java/fr/xephi/authme/security/crypts/WhirlpoolTest.java index 76cef4b05e..3d3cafef29 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/WhirlpoolTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/WhirlpoolTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Whirlpool}. */ -public class WhirlpoolTest extends AbstractEncryptionMethodTest { +class WhirlpoolTest extends AbstractEncryptionMethodTest { - public WhirlpoolTest() { + WhirlpoolTest() { super(new Whirlpool(), "74DFC2B27ACFA364DA55F93A5CAEE29CCAD3557247EDA238831B3E9BD931B01D77FE994E4F12B9D4CFA92A124461D2065197D8CF7F33FC88566DA2DB2A4D6EAE", // password "819B4CBD26508E39EA76BFE102DCF2ACC87A446747CAB0BD88522B0822A724583E81B6A4BD2CE255DB694E530B659F47D434EEB50344A02F50B64414C9671583", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/WordpressTest.java b/src/test/java/fr/xephi/authme/security/crypts/WordpressTest.java index 0c444c2f8a..1a7c379cfa 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/WordpressTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/WordpressTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Wordpress}. */ -public class WordpressTest extends AbstractEncryptionMethodTest { +class WordpressTest extends AbstractEncryptionMethodTest { - public WordpressTest() { + WordpressTest() { super(new Wordpress(), "$P$B9wyjxuU4yrfjnnHNGSzH9ti9CC0Os1", // password "$P$BjzPjjzPjjkRzvGGRTyYu0sNqcz6Ci0", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/XAuthTest.java b/src/test/java/fr/xephi/authme/security/crypts/XAuthTest.java index 877a81ee16..90b357980c 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/XAuthTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/XAuthTest.java @@ -3,9 +3,9 @@ /** * Test for {@link XAuth}. */ -public class XAuthTest extends AbstractEncryptionMethodTest { +class XAuthTest extends AbstractEncryptionMethodTest { - public XAuthTest() { + XAuthTest() { super(new XAuth(), "e54d4916577410d26d2f6e9362445463dab9ffdff9a67ed3b74d3f2312bc8fab84f653fcb88ad8338793ef8a6d0a1162105e46ec24f0dcb52355c634e3e6439f45444b09c715", // password "d54489a4fd4732ee03d56810ab92944096e3d49335266adeecfbc12567abb3ff744761b33a1fcc4d04739e377775c788e4baace3caf35c7b9176b82b1fe3472e4cbdc5a43214", // PassWord1 diff --git a/src/test/java/fr/xephi/authme/security/crypts/XfBCryptTest.java b/src/test/java/fr/xephi/authme/security/crypts/XfBCryptTest.java index 982f5d488d..4c05cc3775 100644 --- a/src/test/java/fr/xephi/authme/security/crypts/XfBCryptTest.java +++ b/src/test/java/fr/xephi/authme/security/crypts/XfBCryptTest.java @@ -1,17 +1,17 @@ package fr.xephi.authme.security.crypts; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; /** * Test for {@link XfBCrypt}. */ -public class XfBCryptTest extends AbstractEncryptionMethodTest { +class XfBCryptTest extends AbstractEncryptionMethodTest { - public XfBCryptTest() { + XfBCryptTest() { super(new XfBCrypt(), "$2a$10$UtuON/ZG.x8EWG/zQbryB.BHfQVrfxk3H7qykzP.UJQ8YiLjZyfqq", // password "$2a$10$Q.ocUo.YtHTdI4nu3pcpKun6BILcmWHm541ANULucmuU/ps1QKY4K", // PassWord1 @@ -20,7 +20,7 @@ public XfBCryptTest() { } @Test - public void shouldGenerateWith2aPrefixAndCostFactor10() { + void shouldGenerateWith2aPrefixAndCostFactor10() { // given XfBCrypt xfBCrypt = new XfBCrypt(); diff --git a/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java b/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java index 3778cc1009..add9f4dfe7 100644 --- a/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java +++ b/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java @@ -4,26 +4,25 @@ import fr.xephi.authme.security.totp.TotpAuthenticator.TotpGenerationResult; import fr.xephi.authme.util.expiring.ExpiringMap; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; /** * Test for {@link GenerateTotpService}. */ -@RunWith(MockitoJUnitRunner.class) -public class GenerateTotpServiceTest { +@ExtendWith(MockitoExtension.class) +class GenerateTotpServiceTest { @InjectMocks private GenerateTotpService generateTotpService; @@ -32,7 +31,7 @@ public class GenerateTotpServiceTest { private TotpAuthenticator totpAuthenticator; @Test - public void shouldGenerateTotpKey() { + void shouldGenerateTotpKey() { // given TotpGenerationResult givenGenerationResult = new TotpGenerationResult("1234", "http://example.com/link/to/chart"); Player player = mockPlayerWithName("Spencer"); @@ -47,7 +46,7 @@ public void shouldGenerateTotpKey() { } @Test - public void shouldRemoveGeneratedTotpKey() { + void shouldRemoveGeneratedTotpKey() { // given TotpGenerationResult givenGenerationResult = new TotpGenerationResult("1234", "http://example.com/link/to/chart"); Player player = mockPlayerWithName("Hanna"); @@ -62,7 +61,7 @@ public void shouldRemoveGeneratedTotpKey() { } @Test - public void shouldCheckGeneratedTotpKey() { + void shouldCheckGeneratedTotpKey() { // given String generatedKey = "ASLO43KDF2J"; TotpGenerationResult givenGenerationResult = new TotpGenerationResult(generatedKey, "url"); @@ -71,6 +70,7 @@ public void shouldCheckGeneratedTotpKey() { generateTotpService.generateTotpKey(player); String validCode = "928374"; given(totpAuthenticator.checkCode("Aria", generatedKey, validCode)).willReturn(true); + given(totpAuthenticator.checkCode("Aria", generatedKey, "000000")).willReturn(false); // when boolean invalidCodeResult = generateTotpService.isTotpCodeCorrectForGeneratedTotpKey(player, "000000"); @@ -81,12 +81,10 @@ public void shouldCheckGeneratedTotpKey() { assertThat(invalidCodeResult, equalTo(false)); assertThat(validCodeResult, equalTo(true)); assertThat(unknownPlayerResult, equalTo(false)); - verify(totpAuthenticator).checkCode("Aria", generatedKey, "000000"); - verify(totpAuthenticator).checkCode("Aria", generatedKey, validCode); } @Test - public void shouldRemoveExpiredEntries() throws InterruptedException { + void shouldRemoveExpiredEntries() throws InterruptedException { // given TotpGenerationResult generationResult = new TotpGenerationResult("key", "url"); ExpiringMap generatedKeys = diff --git a/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java b/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java index 8df9940849..88963b45c2 100644 --- a/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java +++ b/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java @@ -9,18 +9,18 @@ import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.util.Utils; import org.bukkit.entity.Player; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -29,8 +29,8 @@ /** * Test for {@link TotpAuthenticator}. */ -@RunWith(MockitoJUnitRunner.class) -public class TotpAuthenticatorTest { +@ExtendWith(MockitoExtension.class) +class TotpAuthenticatorTest { private TotpAuthenticator totpAuthenticator; @@ -40,13 +40,13 @@ public class TotpAuthenticatorTest { @Mock private IGoogleAuthenticator googleAuthenticator; - @Before - public void initializeTotpAuthenticator() { + @BeforeEach + void initializeTotpAuthenticator() { totpAuthenticator = new TotpAuthenticatorTestImpl(settings); } @Test - public void shouldGenerateTotpKey() { + void shouldGenerateTotpKey() { // given // Use the GoogleAuthenticator instance the TotpAuthenticator normally creates to test its parameters totpAuthenticator = new TotpAuthenticator(settings); @@ -69,7 +69,7 @@ public void shouldGenerateTotpKey() { } @Test - public void shouldCheckCodeAndDeclareItValidOnlyOnce() { + void shouldCheckCodeAndDeclareItValidOnlyOnce() { // given String secret = "the_secret"; int code = 21398; @@ -86,7 +86,7 @@ public void shouldCheckCodeAndDeclareItValidOnlyOnce() { } @Test - public void shouldHandleInvalidNumberInput() { + void shouldHandleInvalidNumberInput() { // given / when boolean result = totpAuthenticator.checkCode("foo", "Some_Secret", "123ZZ"); @@ -96,7 +96,7 @@ public void shouldHandleInvalidNumberInput() { } @Test - public void shouldVerifyCode() { + void shouldVerifyCode() { // given String totpKey = "ASLO43KDF2J"; PlayerAuth auth = PlayerAuth.builder() @@ -115,7 +115,7 @@ public void shouldVerifyCode() { } @Test - public void shouldRemoveOldEntries() { + void shouldRemoveOldEntries() { // given Table usedCodes = ReflectionTestUtils.getFieldValue( TotpAuthenticator.class, totpAuthenticator, "usedCodes"); diff --git a/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java b/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java index 6437925476..a2616b5d23 100644 --- a/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.AdminPermission; @@ -11,18 +8,20 @@ import fr.xephi.authme.settings.properties.ProtectionSettings; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.List; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.BDDMockito.given; @@ -35,10 +34,9 @@ /** * Test for {@link AntiBotService}. */ -@RunWith(DelayedInjectionRunner.class) -public class AntiBotServiceTest { +@ExtendWith(MockitoExtension.class) +class AntiBotServiceTest { - @InjectDelayed private AntiBotService antiBotService; @Mock @@ -50,24 +48,25 @@ public class AntiBotServiceTest { @Mock private BukkitService bukkitService; - @BeforeInjecting - public void initSettings() { + @BeforeEach + void initSettingsAndService() { given(settings.getProperty(ProtectionSettings.ANTIBOT_DURATION)).willReturn(10); given(settings.getProperty(ProtectionSettings.ANTIBOT_INTERVAL)).willReturn(5); given(settings.getProperty(ProtectionSettings.ANTIBOT_SENSIBILITY)).willReturn(5); given(settings.getProperty(ProtectionSettings.ENABLE_ANTIBOT)).willReturn(true); given(settings.getProperty(ProtectionSettings.ANTIBOT_DELAY)).willReturn(8); setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + antiBotService = new AntiBotService(settings, messages, permissionsManager, bukkitService); } @Test - public void shouldStartListenerOnStartup() { + void shouldStartListenerOnStartup() { // given / when / then assertThat(antiBotService.getAntiBotStatus(), equalTo(AntiBotService.AntiBotStatus.LISTENING)); } @Test - public void shouldNotListenForDisabledSetting() { + void shouldNotListenForDisabledSetting() { // given reset(bukkitService); given(settings.getProperty(ProtectionSettings.ENABLE_ANTIBOT)).willReturn(false); @@ -81,7 +80,7 @@ public void shouldNotListenForDisabledSetting() { } @Test - public void shouldActivateAntibot() { + void shouldActivateAntibot() { // given - listening antibot BukkitTask task = mock(BukkitTask.class); given(bukkitService.runTaskLater(any(Runnable.class), anyLong())).willReturn(task); @@ -99,7 +98,7 @@ public void shouldActivateAntibot() { } @Test - public void shouldNotActivateAntibotForDisabledSetting() { + void shouldNotActivateAntibotForDisabledSetting() { // given - disabled antibot given(settings.getProperty(ProtectionSettings.ENABLE_ANTIBOT)).willReturn(false); AntiBotService antiBotService = new AntiBotService(settings, messages, permissionsManager, bukkitService); @@ -112,7 +111,7 @@ public void shouldNotActivateAntibotForDisabledSetting() { } @Test - public void shouldKeepTrackOfKickedPlayers() { + void shouldKeepTrackOfKickedPlayers() { // given String name = "eratic"; antiBotService.addPlayerKick(name); @@ -127,7 +126,7 @@ public void shouldKeepTrackOfKickedPlayers() { } @Test - public void shouldAcceptPlayerToJoin() { + void shouldAcceptPlayerToJoin() { // given / when boolean result = antiBotService.shouldKick(); @@ -136,7 +135,7 @@ public void shouldAcceptPlayerToJoin() { } @Test - public void shouldActivateAntibotAfterThreshold() { + void shouldActivateAntibotAfterThreshold() { // given int sensitivity = 10; given(settings.getProperty(ProtectionSettings.ANTIBOT_SENSIBILITY)).willReturn(sensitivity); @@ -155,7 +154,7 @@ public void shouldActivateAntibotAfterThreshold() { } @Test - public void shouldInformPlayersOnActivation() { + void shouldInformPlayersOnActivation() { // given - listening antibot List players = Arrays.asList(mock(Player.class), mock(Player.class)); given(bukkitService.getOnlinePlayers()).willReturn(players); @@ -173,7 +172,7 @@ public void shouldInformPlayersOnActivation() { } @Test - public void shouldImmediatelyStartAfterFirstStartup() { + void shouldImmediatelyStartAfterFirstStartup() { // given - listening antibot given(bukkitService.runTaskLater(any(Runnable.class), anyLong())).willReturn(mock(BukkitTask.class)); antiBotService.overrideAntiBotStatus(true); diff --git a/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java b/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java index 2e6ee72c74..d6e2c08e56 100644 --- a/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java @@ -14,15 +14,16 @@ import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doReturn; @@ -34,8 +35,8 @@ /** * Test for {@link BukkitService}. */ -@RunWith(MockitoJUnitRunner.class) -public class BukkitServiceTest { +@ExtendWith(MockitoExtension.class) +class BukkitServiceTest { private BukkitService bukkitService; @@ -47,20 +48,121 @@ public class BukkitServiceTest { private Server server; @Mock private BukkitScheduler scheduler; - @Mock - private PluginManager pluginManager; - @Before - public void constructBukkitService() { + @BeforeEach + void constructBukkitService() { ReflectionTestUtils.setField(Bukkit.class, null, "server", server); - given(server.getScheduler()).willReturn(scheduler); - given(server.getPluginManager()).willReturn(pluginManager); given(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(true); bukkitService = new BukkitService(authMe, settings); } + + @Nested + class SchedulerFunctionalityTests { + + @BeforeEach + void setUpScheduler() { + given(server.getScheduler()).willReturn(scheduler); + } + + @Test + void shouldScheduleSyncDelayedTask() { + // given + Runnable task = () -> {/* noop */}; + given(scheduler.scheduleSyncDelayedTask(authMe, task)).willReturn(123); + + // when + int taskId = bukkitService.scheduleSyncDelayedTask(task); + + // then + verify(scheduler, only()).scheduleSyncDelayedTask(authMe, task); + assertThat(taskId, equalTo(123)); + } + + @Test + void shouldScheduleSyncDelayedTaskWithDelay() { + // given + Runnable task = () -> {/* noop */}; + int delay = 3; + given(scheduler.scheduleSyncDelayedTask(authMe, task, delay)).willReturn(44); + + // when + int taskId = bukkitService.scheduleSyncDelayedTask(task, delay); + + // then + verify(scheduler, only()).scheduleSyncDelayedTask(authMe, task, delay); + assertThat(taskId, equalTo(44)); + } + + + @Test + void shouldRunTask() { + // given + Runnable task = () -> {/* noop */}; + BukkitTask bukkitTask = mock(BukkitTask.class); + given(scheduler.runTask(authMe, task)).willReturn(bukkitTask); + + // when + BukkitTask resultingTask = bukkitService.runTask(task); + + // then + assertThat(resultingTask, equalTo(bukkitTask)); + verify(scheduler, only()).runTask(authMe, task); + } + + @Test + void shouldRunTaskLater() { + // given + Runnable task = () -> {/* noop */}; + BukkitTask bukkitTask = mock(BukkitTask.class); + long delay = 400; + given(scheduler.runTaskLater(authMe, task, delay)).willReturn(bukkitTask); + + // when + BukkitTask resultingTask = bukkitService.runTaskLater(task, delay); + + // then + assertThat(resultingTask, equalTo(bukkitTask)); + verify(scheduler, only()).runTaskLater(authMe, task, delay); + } + + @Test + void shouldRunTaskAsynchronously() { + // given + Runnable task = () -> {/* noop */}; + BukkitTask bukkitTask = mock(BukkitTask.class); + given(scheduler.runTaskAsynchronously(authMe, task)).willReturn(bukkitTask); + + // when + BukkitTask resultingTask = bukkitService.runTaskAsynchronously(task); + + // then + assertThat(resultingTask, equalTo(bukkitTask)); + verify(scheduler, only()).runTaskAsynchronously(authMe, task); + } + + @Test + void shouldRunTaskTimerAsynchronously() { + // given + BukkitRunnable task = new BukkitRunnable() { + @Override + public void run() { + } + }; + long delay = 20L; + long period = 4000L; + BukkitTask bukkitTask = mock(BukkitTask.class); + given(task.runTaskTimerAsynchronously(authMe, delay, period)).willReturn(bukkitTask); + + // when + BukkitTask resultingTask = bukkitService.runTaskTimerAsynchronously(task, delay, period); + + // then + assertThat(resultingTask, equalTo(bukkitTask)); + } + } @Test - public void shouldDispatchCommand() { + void shouldDispatchCommand() { // given CommandSender sender = mock(CommandSender.class); String command = "help test abc"; @@ -73,7 +175,7 @@ public void shouldDispatchCommand() { } @Test - public void shouldDispatchConsoleCommand() { + void shouldDispatchConsoleCommand() { // given ConsoleCommandSender consoleSender = mock(ConsoleCommandSender.class); given(server.getConsoleSender()).willReturn(consoleSender); @@ -87,36 +189,7 @@ public void shouldDispatchConsoleCommand() { } @Test - public void shouldScheduleSyncDelayedTask() { - // given - Runnable task = () -> {/* noop */}; - given(scheduler.scheduleSyncDelayedTask(authMe, task)).willReturn(123); - - // when - int taskId = bukkitService.scheduleSyncDelayedTask(task); - - // then - verify(scheduler, only()).scheduleSyncDelayedTask(authMe, task); - assertThat(taskId, equalTo(123)); - } - - @Test - public void shouldScheduleSyncDelayedTaskWithDelay() { - // given - Runnable task = () -> {/* noop */}; - int delay = 3; - given(scheduler.scheduleSyncDelayedTask(authMe, task, delay)).willReturn(44); - - // when - int taskId = bukkitService.scheduleSyncDelayedTask(task, delay); - - // then - verify(scheduler, only()).scheduleSyncDelayedTask(authMe, task, delay); - assertThat(taskId, equalTo(44)); - } - - @Test - public void shouldScheduleSyncTask() { + void shouldScheduleSyncTask() { // given BukkitService spy = Mockito.spy(bukkitService); doReturn(1).when(spy).scheduleSyncDelayedTask(any(Runnable.class)); @@ -131,7 +204,7 @@ public void shouldScheduleSyncTask() { } @Test - public void shouldRunTaskDirectly() { + void shouldRunTaskDirectly() { // given given(server.isPrimaryThread()).willReturn(true); bukkitService.reload(settings); @@ -147,38 +220,7 @@ public void shouldRunTaskDirectly() { } @Test - public void shouldRunTask() { - // given - Runnable task = () -> {/* noop */}; - BukkitTask bukkitTask = mock(BukkitTask.class); - given(scheduler.runTask(authMe, task)).willReturn(bukkitTask); - - // when - BukkitTask resultingTask = bukkitService.runTask(task); - - // then - assertThat(resultingTask, equalTo(bukkitTask)); - verify(scheduler, only()).runTask(authMe, task); - } - - @Test - public void shouldRunTaskLater() { - // given - Runnable task = () -> {/* noop */}; - BukkitTask bukkitTask = mock(BukkitTask.class); - long delay = 400; - given(scheduler.runTaskLater(authMe, task, delay)).willReturn(bukkitTask); - - // when - BukkitTask resultingTask = bukkitService.runTaskLater(task, delay); - - // then - assertThat(resultingTask, equalTo(bukkitTask)); - verify(scheduler, only()).runTaskLater(authMe, task, delay); - } - - @Test - public void shouldRunTaskInAsync() { + void shouldRunTaskInAsync() { // given Runnable task = mock(Runnable.class); BukkitService spy = Mockito.spy(bukkitService); @@ -193,7 +235,7 @@ public void shouldRunTaskInAsync() { } @Test - public void shouldRunTaskDirectlyIfConfigured() { + void shouldRunTaskDirectlyIfConfigured() { // given given(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(false); bukkitService.reload(settings); @@ -208,43 +250,12 @@ public void shouldRunTaskDirectlyIfConfigured() { verify(spy, only()).runTaskOptionallyAsync(task); } - @Test - public void shouldRunTaskAsynchronously() { - // given - Runnable task = () -> {/* noop */}; - BukkitTask bukkitTask = mock(BukkitTask.class); - given(scheduler.runTaskAsynchronously(authMe, task)).willReturn(bukkitTask); - - // when - BukkitTask resultingTask = bukkitService.runTaskAsynchronously(task); - // then - assertThat(resultingTask, equalTo(bukkitTask)); - verify(scheduler, only()).runTaskAsynchronously(authMe, task); - } - @Test - public void shouldRunTaskTimerAsynchronously() { - // given - BukkitRunnable task = new BukkitRunnable() { - @Override - public void run() { - } - }; - long delay = 20L; - long period = 4000L; - BukkitTask bukkitTask = mock(BukkitTask.class); - given(task.runTaskTimerAsynchronously(authMe, delay, period)).willReturn(bukkitTask); - // when - BukkitTask resultingTask = bukkitService.runTaskTimerAsynchronously(task, delay, period); - - // then - assertThat(resultingTask, equalTo(bukkitTask)); - } @Test - public void shouldRunTaskTimer() { + void shouldRunTaskTimer() { // given BukkitRunnable bukkitRunnable = mock(BukkitRunnable.class); long delay = 20; @@ -261,7 +272,7 @@ public void shouldRunTaskTimer() { } @Test - public void shouldBroadcastMessage() { + void shouldBroadcastMessage() { // given String message = "Important message to all"; given(server.broadcastMessage(message)).willReturn(24); @@ -275,11 +286,13 @@ public void shouldBroadcastMessage() { } @Test - public void shouldCreateAndEmitSyncEvent() { + void shouldCreateAndEmitSyncEvent() { // given given(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(false); bukkitService.reload(settings); Player player = mock(Player.class); + PluginManager pluginManager = mock(PluginManager.class); + given(server.getPluginManager()).willReturn(pluginManager); // when FailedLoginEvent event = bukkitService.createAndCallEvent(isAsync -> new FailedLoginEvent(player, isAsync)); @@ -291,9 +304,11 @@ public void shouldCreateAndEmitSyncEvent() { } @Test - public void shouldCreateAndEmitAsyncEvent() { + void shouldCreateAndEmitAsyncEvent() { // given Player player = mock(Player.class); + PluginManager pluginManager = mock(PluginManager.class); + given(server.getPluginManager()).willReturn(pluginManager); // when FailedLoginEvent event = bukkitService.createAndCallEvent(isAsync -> new FailedLoginEvent(player, isAsync)); @@ -305,7 +320,7 @@ public void shouldCreateAndEmitAsyncEvent() { } @Test - public void shouldReturnServerIp() { + void shouldReturnServerIp() { // given String ip = "99.99.99.99"; given(server.getIp()).willReturn(ip); diff --git a/src/test/java/fr/xephi/authme/service/CommonServiceTest.java b/src/test/java/fr/xephi/authme/service/CommonServiceTest.java index b74762dc26..33af3a7c6c 100644 --- a/src/test/java/fr/xephi/authme/service/CommonServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/CommonServiceTest.java @@ -9,14 +9,14 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -24,8 +24,8 @@ /** * Test for {@link CommonService}. */ -@RunWith(MockitoJUnitRunner.class) -public class CommonServiceTest { +@ExtendWith(MockitoExtension.class) +class CommonServiceTest { @InjectMocks private CommonService commonService; @@ -40,7 +40,7 @@ public class CommonServiceTest { private PermissionsManager permissionsManager; @Test - public void shouldGetProperty() { + void shouldGetProperty() { // given given(settings.getProperty(SecuritySettings.CAPTCHA_LENGTH)).willReturn(8); @@ -53,7 +53,7 @@ public void shouldGetProperty() { } @Test - public void shouldSendMessageToPlayer() { + void shouldSendMessageToPlayer() { // given CommandSender sender = mock(CommandSender.class); MessageKey key = MessageKey.ACCOUNT_NOT_ACTIVATED; @@ -66,7 +66,7 @@ public void shouldSendMessageToPlayer() { } @Test - public void shouldSendMessageWithReplacements() { + void shouldSendMessageWithReplacements() { // given CommandSender sender = mock(CommandSender.class); MessageKey key = MessageKey.ACCOUNT_NOT_ACTIVATED; @@ -80,7 +80,7 @@ public void shouldSendMessageWithReplacements() { } @Test - public void shouldRetrieveSingleMessage() { + void shouldRetrieveSingleMessage() { // given MessageKey key = MessageKey.ACCOUNT_NOT_ACTIVATED; Player player = mock(Player.class); @@ -96,7 +96,7 @@ public void shouldRetrieveSingleMessage() { } @Test - public void shouldCheckPermission() { + void shouldCheckPermission() { // given Player player = mock(Player.class); PermissionNode permission = PlayerPermission.CHANGE_PASSWORD; diff --git a/src/test/java/fr/xephi/authme/service/GeoIpServiceTest.java b/src/test/java/fr/xephi/authme/service/GeoIpServiceTest.java index 351049a806..eee47a3bed 100644 --- a/src/test/java/fr/xephi/authme/service/GeoIpServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/GeoIpServiceTest.java @@ -5,20 +5,18 @@ import com.maxmind.db.model.CountryResponse; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ProtectionSettings; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; -import java.io.IOException; import java.net.InetAddress; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -29,11 +27,13 @@ /** * Test for {@link GeoIpService}. */ -@RunWith(MockitoJUnitRunner.class) -public class GeoIpServiceTest { +@ExtendWith(MockitoExtension.class) +class GeoIpServiceTest { private GeoIpService geoIpService; - private File dataFolder; + + @TempDir + File dataFolder; @Mock private GeoIp2Provider lookupService; @@ -44,17 +44,13 @@ public class GeoIpServiceTest { @Mock private Settings settings; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Before - public void initializeGeoLiteApi() throws IOException { - dataFolder = temporaryFolder.newFolder(); + @BeforeEach + void initializeGeoLiteApi() { geoIpService = new GeoIpService(dataFolder, bukkitService, settings, lookupService); } @Test - public void shouldGetCountry() throws Exception { + void shouldGetCountry() throws Exception { // given InetAddress ip = InetAddress.getByName("123.45.67.89"); String countryCode = "XX"; @@ -76,7 +72,7 @@ public void shouldGetCountry() throws Exception { } @Test - public void shouldNotLookUpCountryForLocalhostIp() throws Exception { + void shouldNotLookUpCountryForLocalhostIp() throws Exception { // given String ip = "127.0.0.1"; @@ -89,7 +85,7 @@ public void shouldNotLookUpCountryForLocalhostIp() throws Exception { } @Test - public void shouldLookUpCountryName() throws Exception { + void shouldLookUpCountryName() throws Exception { // given InetAddress ip = InetAddress.getByName("24.45.167.89"); String countryName = "Ecuador"; @@ -111,7 +107,7 @@ public void shouldLookUpCountryName() throws Exception { } @Test - public void shouldNotLookUpCountryNameForLocalhostIp() throws Exception { + void shouldNotLookUpCountryNameForLocalhostIp() throws Exception { // given InetAddress ip = InetAddress.getByName("127.0.0.1"); @@ -124,7 +120,7 @@ public void shouldNotLookUpCountryNameForLocalhostIp() throws Exception { } @Test - public void shouldNotLookUpCountryNameIfDisabled() throws Exception { + void shouldNotLookUpCountryNameIfDisabled() throws Exception { // given InetAddress ip = InetAddress.getByName("24.45.167.89"); given(settings.getProperty(ProtectionSettings.ENABLE_GEOIP)).willReturn(false); diff --git a/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java b/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java index 3e094cc2bd..81d01402f4 100644 --- a/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java @@ -1,80 +1,73 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandInitializer; import fr.xephi.authme.command.help.HelpMessage; import fr.xephi.authme.command.help.HelpMessagesService; import fr.xephi.authme.command.help.HelpSection; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.message.HelpMessagesFileHandler; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +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.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; +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.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; /** * Integration test for {@link HelpTranslationGenerator}. */ -@RunWith(DelayedInjectionRunner.class) -public class HelpTranslationGeneratorIntegrationTest { +@ExtendWith(MockitoExtension.class) +class HelpTranslationGeneratorIntegrationTest { - @InjectDelayed private HelpTranslationGenerator helpTranslationGenerator; - @InjectDelayed - private HelpMessagesService helpMessagesService; - @InjectDelayed - private HelpMessagesFileHandler helpMessagesFileHandler; - @InjectDelayed - private CommandInitializer commandInitializer; - - @DataFolder - private File dataFolder; + + @TempDir + File dataFolder; private File helpMessagesFile; @Mock private Settings settings; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void setUpClasses() throws IOException { - dataFolder = temporaryFolder.newFolder(); + @BeforeEach + void setUpClasses() throws IOException { File messagesFolder = new File(dataFolder, "messages"); messagesFolder.mkdir(); helpMessagesFile = new File(messagesFolder, "help_test.yml"); Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/help_test.yml"), helpMessagesFile); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); + + CommandInitializer commandInitializer = new CommandInitializer(); + HelpMessagesFileHandler helpMessagesFileHandler = new HelpMessagesFileHandler(dataFolder, settings); + HelpMessagesService helpMessagesService = new HelpMessagesService(helpMessagesFileHandler); + helpTranslationGenerator = new HelpTranslationGenerator(commandInitializer, helpMessagesService, settings, dataFolder); + ReflectionTestUtils.invokePostConstructMethods(helpMessagesFileHandler); } @Test - public void shouldUpdateCurrentHelpFile() throws IOException { + void shouldUpdateCurrentHelpFile() throws IOException { // given / when helpTranslationGenerator.updateHelpFile(); diff --git a/src/test/java/fr/xephi/authme/service/MigrationServiceTest.java b/src/test/java/fr/xephi/authme/service/MigrationServiceTest.java index ec989a0429..5f00f06557 100644 --- a/src/test/java/fr/xephi/authme/service/MigrationServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/MigrationServiceTest.java @@ -8,18 +8,18 @@ import fr.xephi.authme.security.crypts.Sha256; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.SecuritySettings; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Locale; import static fr.xephi.authme.AuthMeMatchers.equalToHash; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalToIgnoringCase; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -31,8 +31,8 @@ /** * Test for {@link MigrationService}. */ -@RunWith(MockitoJUnitRunner.class) -public class MigrationServiceTest { +@ExtendWith(MockitoExtension.class) +class MigrationServiceTest { @Mock private Settings settings; @@ -43,13 +43,13 @@ public class MigrationServiceTest { @Mock private Sha256 sha256; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldMigratePlaintextHashes() { + void shouldMigratePlaintextHashes() { // given PlayerAuth auth1 = authWithNickAndHash("bobby", "test"); PlayerAuth auth2 = authWithNickAndHash("user", "myPassword"); @@ -75,7 +75,7 @@ public void shouldMigratePlaintextHashes() { } @Test - public void shouldNotMigrateShaHashes() { + void shouldNotMigrateShaHashes() { // given PlayerAuth auth1 = authWithNickAndHash("testUser", "abc1234"); PlayerAuth auth2 = authWithNickAndHash("minecraft", "$SHA$f28930ae09823eba4cd98a3"); @@ -97,7 +97,7 @@ public void shouldNotMigrateShaHashes() { } @Test - public void shouldNotMigrateForHashOtherThanPlaintext() { + void shouldNotMigrateForHashOtherThanPlaintext() { // given given(settings.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.BCRYPT); diff --git a/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java b/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java index bf3dd083f4..5c0aad6214 100644 --- a/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java @@ -1,8 +1,6 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.mail.EmailService; @@ -11,12 +9,15 @@ import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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 static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -24,10 +25,10 @@ /** * Tests for {@link PasswordRecoveryService}. */ -@RunWith(DelayedInjectionRunner.class) -public class PasswordRecoveryServiceTest { +@ExtendWith(MockitoExtension.class) +class PasswordRecoveryServiceTest { - @InjectDelayed + @InjectMocks private PasswordRecoveryService recoveryService; @Mock @@ -48,14 +49,15 @@ public class PasswordRecoveryServiceTest { @Mock private Messages messages; - @BeforeInjecting - public void initSettings() { + @BeforeEach + void runPostConstructMethod() { given(commonService.getProperty(SecuritySettings.EMAIL_RECOVERY_COOLDOWN_SECONDS)).willReturn(40); given(commonService.getProperty(SecuritySettings.PASSWORD_CHANGE_TIMEOUT)).willReturn(2); + ReflectionTestUtils.invokePostConstructMethods(recoveryService); } @Test - public void shouldSendRecoveryCode() { + void shouldSendRecoveryCode() { // given Player player = mock(Player.class); String name = "Carl"; @@ -75,7 +77,7 @@ public void shouldSendRecoveryCode() { } @Test - public void shouldKeepTrackOfSuccessfulRecoversByIp() { + void shouldKeepTrackOfSuccessfulRecoversByIp() { // given Player bobby = mock(Player.class); TestHelper.mockIpAddressToPlayer(bobby, "192.168.8.8"); @@ -99,7 +101,7 @@ public void shouldKeepTrackOfSuccessfulRecoversByIp() { } @Test - public void shouldRemovePlayerFromSuccessfulRecovers() { + void shouldRemovePlayerFromSuccessfulRecovers() { // given Player bobby = mock(Player.class); TestHelper.mockIpAddressToPlayer(bobby, "192.168.8.8"); diff --git a/src/test/java/fr/xephi/authme/service/PluginHookServiceTest.java b/src/test/java/fr/xephi/authme/service/PluginHookServiceTest.java index d949db7dd2..43219d0afe 100644 --- a/src/test/java/fr/xephi/authme/service/PluginHookServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/PluginHookServiceTest.java @@ -13,14 +13,14 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; @@ -31,7 +31,7 @@ /** * Test for {@link PluginHookService}. */ -public class PluginHookServiceTest { +class PluginHookServiceTest { /** The plugin name of Essentials. */ private static final String ESSENTIALS = "Essentials"; @@ -40,13 +40,13 @@ public class PluginHookServiceTest { /** The plugin name of Multiverse-Core. */ private static final String MULTIVERSE = "Multiverse-Core"; - @BeforeClass - public static void setLogger() { + @BeforeAll + static void setLogger() { TestHelper.setupLogger(); } @Test - public void shouldHookIntoEssentials() { + void shouldHookIntoEssentials() { // given PluginManager pluginManager = mock(PluginManager.class); PluginHookService pluginHookService = new PluginHookService(pluginManager); @@ -61,7 +61,7 @@ public void shouldHookIntoEssentials() { } @Test - public void shouldHookIntoEssentialsAtInitialization() { + void shouldHookIntoEssentialsAtInitialization() { // given PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, ESSENTIALS, Essentials.class); @@ -74,7 +74,7 @@ public void shouldHookIntoEssentialsAtInitialization() { } @Test - public void shouldHookIntoCmiAtInitialization() { + void shouldHookIntoCmiAtInitialization() { // given PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, CMI, Plugin.class); @@ -87,7 +87,7 @@ public void shouldHookIntoCmiAtInitialization() { } @Test - public void shouldHookIntoMultiverseAtInitialization() { + void shouldHookIntoMultiverseAtInitialization() { // given PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, MULTIVERSE, MultiverseCore.class); @@ -100,7 +100,7 @@ public void shouldHookIntoMultiverseAtInitialization() { } @Test - public void shouldReturnEssentialsDataFolder() { + void shouldReturnEssentialsDataFolder() { // given Essentials ess = mock(Essentials.class); File essDataFolder = new File("test/data-folder"); @@ -119,7 +119,7 @@ public void shouldReturnEssentialsDataFolder() { } @Test - public void shouldReturnNullForUnhookedEssentials() { + void shouldReturnNullForUnhookedEssentials() { // given PluginManager pluginManager = mock(PluginManager.class); PluginHookService pluginHookService = new PluginHookService(pluginManager); @@ -132,7 +132,7 @@ public void shouldReturnNullForUnhookedEssentials() { } @Test - public void shouldSetSocialSpyStatus() { + void shouldSetSocialSpyStatus() { // given Player player = mock(Player.class); @@ -153,7 +153,7 @@ public void shouldSetSocialSpyStatus() { } @Test - public void shouldNotDoAnythingForUnhookedEssentials() { + void shouldNotDoAnythingForUnhookedEssentials() { // given PluginHookService pluginHookService = new PluginHookService(mock(PluginManager.class)); @@ -162,7 +162,7 @@ public void shouldNotDoAnythingForUnhookedEssentials() { } @Test - public void shouldUnhookEssentialsAndMultiverse() { + void shouldUnhookEssentialsAndMultiverse() { // given PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, ESSENTIALS, Essentials.class); @@ -179,7 +179,7 @@ public void shouldUnhookEssentialsAndMultiverse() { } @Test - public void shouldHandlePluginRetrievalError() { + void shouldHandlePluginRetrievalError() { // given PluginManager pluginManager = mock(PluginManager.class); given(pluginManager.isPluginEnabled(anyString())).willReturn(true); @@ -195,7 +195,7 @@ public void shouldHandlePluginRetrievalError() { } @Test - public void shouldReturnNullForUnavailableMultiverse() { + void shouldReturnNullForUnavailableMultiverse() { // given PluginManager pluginManager = mock(PluginManager.class); PluginHookService pluginHookService = new PluginHookService(pluginManager); @@ -209,7 +209,7 @@ public void shouldReturnNullForUnavailableMultiverse() { } @Test - public void shouldGetMultiverseSpawn() { + void shouldGetMultiverseSpawn() { // given Location location = mock(Location.class); MultiverseWorld multiverseWorld = mock(MultiverseWorld.class); @@ -237,7 +237,7 @@ public void shouldGetMultiverseSpawn() { } @Test - public void shouldReturnNullForNonMvWorld() { + void shouldReturnNullForNonMvWorld() { // given World world = mock(World.class); MVWorldManager mvWorldManager = mock(MVWorldManager.class); diff --git a/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java b/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java index 9641db9a03..678a08aa2a 100644 --- a/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java @@ -1,43 +1,43 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.expiring.ExpiringMap; -import org.junit.Test; -import org.junit.runner.RunWith; +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 fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; /** * Test for {@link RecoveryCodeService}. */ -@RunWith(DelayedInjectionRunner.class) -public class RecoveryCodeServiceTest { +@ExtendWith(MockitoExtension.class) +class RecoveryCodeServiceTest { - @InjectDelayed private RecoveryCodeService recoveryCodeService; @Mock private Settings settings; - @BeforeInjecting - public void initSettings() { + @BeforeEach + void initService() { given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(4); given(settings.getProperty(SecuritySettings.RECOVERY_CODE_LENGTH)).willReturn(5); given(settings.getProperty(SecuritySettings.RECOVERY_CODE_MAX_TRIES)).willReturn(3); + + recoveryCodeService = new RecoveryCodeService(settings); } @Test - public void shouldBeDisabledForNonPositiveLength() { + void shouldBeDisabledForNonPositiveLength() { assertThat(recoveryCodeService.isRecoveryCodeNeeded(), equalTo(true)); // given @@ -51,7 +51,7 @@ public void shouldBeDisabledForNonPositiveLength() { } @Test - public void shouldGenerateAndStoreCode() { + void shouldGenerateAndStoreCode() { // given String name = "Bobbers"; @@ -64,7 +64,7 @@ public void shouldGenerateAndStoreCode() { } @Test - public void playerHasTriesLeft() { + void playerHasTriesLeft() { // given String player = "Dusty"; recoveryCodeService.generateCode(player); @@ -77,7 +77,7 @@ public void playerHasTriesLeft() { } @Test - public void playerHasNoTriesLeft() { + void playerHasNoTriesLeft() { // given String player = "Dusty"; recoveryCodeService.generateCode(player); @@ -93,7 +93,7 @@ public void playerHasNoTriesLeft() { } @Test - public void shouldRecognizeCorrectCode() { + void shouldRecognizeCorrectCode() { // given String player = "dragon"; String code = recoveryCodeService.generateCode(player); @@ -106,7 +106,7 @@ public void shouldRecognizeCorrectCode() { } @Test - public void shouldRemoveCode() { + void shouldRemoveCode() { // given String player = "Tester"; String code = recoveryCodeService.generateCode(player); diff --git a/src/test/java/fr/xephi/authme/service/SessionServiceTest.java b/src/test/java/fr/xephi/authme/service/SessionServiceTest.java index 7153f14986..f9182d29b4 100644 --- a/src/test/java/fr/xephi/authme/service/SessionServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/SessionServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; @@ -10,18 +7,21 @@ import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.settings.properties.PluginSettings; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.function.Function; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.only; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -31,10 +31,9 @@ /** * Test for {@link SessionService}. */ -@RunWith(DelayedInjectionRunner.class) -public class SessionServiceTest { +@ExtendWith(MockitoExtension.class) +class SessionServiceTest { - @InjectDelayed private SessionService sessionService; @Mock @@ -44,18 +43,19 @@ public class SessionServiceTest { @Mock private BukkitService bukkitService; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void setUpEnabledProperty() { + @BeforeEach + void createSessionService() { given(commonService.getProperty(PluginSettings.SESSIONS_ENABLED)).willReturn(true); + sessionService = new SessionService(commonService, bukkitService, dataSource); } @Test - public void shouldCheckSessionsEnabledSetting() { + void shouldCheckSessionsEnabledSetting() { // given Player player = mock(Player.class); given(commonService.getProperty(PluginSettings.SESSIONS_ENABLED)).willReturn(false); @@ -70,7 +70,7 @@ public void shouldCheckSessionsEnabledSetting() { } @Test - public void shouldCheckIfUserHasSession() { + void shouldCheckIfUserHasSession() { // given String name = "Bobby"; Player player = mock(Player.class); @@ -83,21 +83,20 @@ public void shouldCheckIfUserHasSession() { // then assertThat(result, equalTo(false)); verify(commonService, only()).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource, only()).hasSession(name); } @Test - public void shouldCheckLastLoginDate() { + void shouldCheckLastLoginDate() { // given String name = "Bobby"; - String ip = "127.3.12.15"; - Player player = mockPlayerWithNameAndIp(name, ip); + Player player = mock(Player.class); + given(player.getName()).willReturn(name); given(commonService.getProperty(PluginSettings.SESSIONS_TIMEOUT)).willReturn(8); given(dataSource.hasSession(name)).willReturn(true); PlayerAuth auth = PlayerAuth.builder() .name(name) .lastLogin(System.currentTimeMillis() - 10 * 60 * 1000) - .lastIp(ip).build(); + .lastIp("127.3.12.15").build(); given(dataSource.getAuth(name)).willReturn(auth); // when @@ -105,24 +104,22 @@ public void shouldCheckLastLoginDate() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); + verify(player, only()).getName(); } @Test - public void shouldRefuseSessionForAuthWithNullLastLoginTimestamp() { + void shouldRefuseSessionForAuthWithNullLastLoginTimestamp() { // given String name = "Bobby"; - String ip = "127.3.12.15"; - Player player = mockPlayerWithNameAndIp(name, ip); - given(commonService.getProperty(PluginSettings.SESSIONS_TIMEOUT)).willReturn(8); + Player player = mock(Player.class); + given(player.getName()).willReturn(name); given(dataSource.hasSession(name)).willReturn(true); PlayerAuth auth = PlayerAuth.builder() .name(name) .lastLogin(null) - .lastIp(ip).build(); + .lastIp("127.3.12.15").build(); given(dataSource.getAuth(name)).willReturn(auth); // when @@ -130,14 +127,13 @@ public void shouldRefuseSessionForAuthWithNullLastLoginTimestamp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); + verify(player, only()).getName(); } @Test - public void shouldCheckLastLoginIp() { + void shouldCheckLastLoginIp() { // given String name = "Bobby"; String ip = "127.3.12.15"; @@ -155,15 +151,13 @@ public void shouldCheckLastLoginIp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); verify(commonService).send(player, MessageKey.SESSION_EXPIRED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); } @Test - public void shouldEmitEventForValidSession() { + void shouldEmitEventForValidSession() { // given String name = "Bobby"; String ip = "127.3.12.15"; @@ -186,17 +180,17 @@ public void shouldEmitEventForValidSession() { verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); verify(commonService).getProperty(PluginSettings.SESSIONS_TIMEOUT); verifyNoMoreInteractions(commonService); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); verify(event).isCancelled(); } @Test - public void shouldHandleNullPlayerAuth() { + void shouldHandleNullPlayerAuth() { // given String name = "Bobby"; - Player player = mockPlayerWithNameAndIp(name, "127.3.12.15"); + Player player = mock(Player.class); + given(player.getName()).willReturn(name); given(dataSource.hasSession(name)).willReturn(true); given(dataSource.getAuth(name)).willReturn(null); @@ -205,15 +199,13 @@ public void shouldHandleNullPlayerAuth() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); - verify(dataSource).getAuth(name); + verify(player, never()).getAddress(); } @Test - public void shouldHandlePlayerAuthWithNullLastIp() { + void shouldHandlePlayerAuthWithNullLastIp() { // given String name = "Charles"; Player player = mockPlayerWithNameAndIp(name, "144.117.118.145"); @@ -222,7 +214,8 @@ public void shouldHandlePlayerAuthWithNullLastIp() { PlayerAuth auth = PlayerAuth.builder() .name(name) .lastIp(null) - .lastLogin(System.currentTimeMillis()).build(); + .lastLogin(System.currentTimeMillis() - 2) + .build(); given(dataSource.getAuth(name)).willReturn(auth); // when @@ -230,11 +223,8 @@ public void shouldHandlePlayerAuthWithNullLastIp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); - verify(dataSource).getAuth(name); } private static Player mockPlayerWithNameAndIp(String name, String ip) { diff --git a/src/test/java/fr/xephi/authme/service/TeleportationServiceTest.java b/src/test/java/fr/xephi/authme/service/TeleportationServiceTest.java index 46db5e05ca..313df6448f 100644 --- a/src/test/java/fr/xephi/authme/service/TeleportationServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/TeleportationServiceTest.java @@ -11,19 +11,19 @@ import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -37,8 +37,8 @@ /** * Test for {@link TeleportationService}. */ -@RunWith(MockitoJUnitRunner.class) -public class TeleportationServiceTest { +@ExtendWith(MockitoExtension.class) +class TeleportationServiceTest { @InjectMocks private TeleportationService teleportationService; @@ -55,8 +55,8 @@ public class TeleportationServiceTest { @Mock private PlayerCache playerCache; - @Before - public void setUpForcedWorlds() { + @BeforeEach + void setUpForcedWorlds() { given(settings.getProperty(RestrictionSettings.FORCE_SPAWN_ON_WORLDS)) .willReturn(Arrays.asList("forced1", "OtherForced")); teleportationService.reload(); @@ -68,7 +68,7 @@ public void setUpForcedWorlds() { // JOINING // ----------- @Test - public void shouldNotTeleportPlayerOnJoin() { + void shouldNotTeleportPlayerOnJoin() { // given given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(true); Player player = mock(Player.class); @@ -82,7 +82,7 @@ public void shouldNotTeleportPlayerOnJoin() { } @Test - public void shouldTeleportPlayerToFirstSpawn() { + void shouldTeleportPlayerToFirstSpawn() { // given Player player = mock(Player.class); given(player.hasPlayedBefore()).willReturn(false); @@ -102,7 +102,7 @@ public void shouldTeleportPlayerToFirstSpawn() { } @Test - public void shouldTeleportPlayerToSpawn() { + void shouldTeleportPlayerToSpawn() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); Player player = mock(Player.class); @@ -122,7 +122,7 @@ public void shouldTeleportPlayerToSpawn() { @Test // No first spawn defined, no teleport settings enabled - public void shouldNotTeleportNewPlayer() { + void shouldNotTeleportNewPlayer() { // given Player player = mock(Player.class); given(spawnLoader.getFirstSpawn()).willReturn(null); @@ -138,7 +138,7 @@ public void shouldNotTeleportNewPlayer() { } @Test - public void shouldNotTeleportPlayerToFirstSpawnIfNoTeleportEnabled() { + void shouldNotTeleportPlayerToFirstSpawnIfNoTeleportEnabled() { // given Player player = mock(Player.class); given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(true); @@ -152,7 +152,7 @@ public void shouldNotTeleportPlayerToFirstSpawnIfNoTeleportEnabled() { } @Test - public void shouldNotTeleportNotNewPlayerToFirstSpawn() { + void shouldNotTeleportNotNewPlayerToFirstSpawn() { // given Player player = mock(Player.class); given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(false); @@ -166,10 +166,10 @@ public void shouldNotTeleportNotNewPlayerToFirstSpawn() { } @Test - public void shouldNotTeleportPlayerForRemovedLocationInEvent() { + void shouldNotTeleportPlayerForRemovedLocationInEvent() { // given final Player player = mock(Player.class); - Location spawn = mockLocation(); + Location spawn = mock(Location.class); given(spawnLoader.getSpawnLocation(player)).willReturn(spawn); given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); doAnswer(invocation -> { @@ -189,10 +189,10 @@ public void shouldNotTeleportPlayerForRemovedLocationInEvent() { } @Test - public void shouldNotTeleportPlayerForCanceledEvent() { + void shouldNotTeleportPlayerForCanceledEvent() { // given final Player player = mock(Player.class); - Location spawn = mockLocation(); + Location spawn = mock(Location.class); given(spawnLoader.getSpawnLocation(player)).willReturn(spawn); given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); doAnswer(invocation -> { @@ -215,7 +215,7 @@ public void shouldNotTeleportPlayerForCanceledEvent() { // LOGIN // --------- @Test - public void shouldNotTeleportUponLogin() { + void shouldNotTeleportUponLogin() { // given given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(true); Player player = mock(Player.class); @@ -230,7 +230,7 @@ public void shouldNotTeleportUponLogin() { } @Test - public void shouldTeleportPlayerToSpawnAfterLogin() { + void shouldTeleportPlayerToSpawnAfterLogin() { // given given(settings.getProperty(RestrictionSettings.FORCE_SPAWN_LOCATION_AFTER_LOGIN)).willReturn(true); Player player = mock(Player.class); @@ -251,14 +251,14 @@ public void shouldTeleportPlayerToSpawnAfterLogin() { verify(player).teleport(spawn); } - @Test // Check that the worlds for "force spawn loc after login" are case-sensitive - public void shouldNotTeleportToSpawnForOtherCaseInWorld() { + @Test + void shouldNotTeleportToSpawnForOtherCaseInWorld() { // given given(settings.getProperty(RestrictionSettings.FORCE_SPAWN_LOCATION_AFTER_LOGIN)).willReturn(true); given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(false); Player player = mock(Player.class); - Location spawn = mockLocation(); + Location spawn = mock(Location.class); PlayerAuth auth = mock(PlayerAuth.class); LimboPlayer limbo = mock(LimboPlayer.class); Location limboLocation = mockLocation(); @@ -274,7 +274,7 @@ public void shouldNotTeleportToSpawnForOtherCaseInWorld() { } @Test - public void shouldTeleportBackToPlayerAuthLocation() { + void shouldTeleportBackToPlayerAuthLocation() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(true); @@ -301,7 +301,7 @@ public void shouldTeleportBackToPlayerAuthLocation() { } @Test - public void shouldTeleportAccordingToPlayerAuthAndPlayerWorldAsFallback() { + void shouldTeleportAccordingToPlayerAuthAndPlayerWorldAsFallback() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(true); @@ -329,7 +329,7 @@ public void shouldTeleportAccordingToPlayerAuthAndPlayerWorldAsFallback() { } @Test - public void shouldTeleportWithLimboPlayerIfAuthYCoordIsNotSet() { + void shouldTeleportWithLimboPlayerIfAuthYCoordIsNotSet() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(true); @@ -353,7 +353,7 @@ public void shouldTeleportWithLimboPlayerIfAuthYCoordIsNotSet() { } @Test - public void shouldTeleportWithLimboPlayerIfSaveQuitLocIsDisabled() { + void shouldTeleportWithLimboPlayerIfSaveQuitLocIsDisabled() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(false); @@ -374,7 +374,7 @@ public void shouldTeleportWithLimboPlayerIfSaveQuitLocIsDisabled() { } @Test - public void shouldNotTeleportForNullLocationInLimboPlayer() { + void shouldNotTeleportForNullLocationInLimboPlayer() { // given given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(false); given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); @@ -411,5 +411,4 @@ private static PlayerAuth createAuthWithLocation() { .locX(123.45).locY(23.4).locZ(-4.567) .build(); } - } diff --git a/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java b/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java index da8f16326e..c18a0a24f0 100644 --- a/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.base.Strings; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; @@ -17,11 +14,14 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.Test; -import org.junit.runner.RunWith; +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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetSocketAddress; import java.util.Collections; @@ -29,23 +29,24 @@ import static com.google.common.collect.Sets.newHashSet; import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Test for {@link ValidationService}. */ -@RunWith(DelayedInjectionRunner.class) -public class ValidationServiceTest { +@ExtendWith(MockitoExtension.class) +class ValidationServiceTest { - @InjectDelayed + @InjectMocks private ValidationService validationService; @Mock private Settings settings; @@ -56,20 +57,16 @@ public class ValidationServiceTest { @Mock private GeoIpService geoIpService; - @BeforeInjecting - public void createService() { + @BeforeEach + void callReload() { given(settings.getProperty(RestrictionSettings.ALLOWED_PASSWORD_REGEX)).willReturn("[a-zA-Z]+"); - given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); - given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); - given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); - given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); - given(settings.getProperty(RestrictionSettings.UNRESTRICTED_NAMES)).willReturn(newHashSet("name01", "npc")); given(settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)).willReturn(false); + validationService.reload(); } @Test - public void shouldRejectPasswordSameAsUsername() { - // given/when + void shouldRejectPasswordSameAsUsername() { + // given / when ValidationResult error = validationService.validatePassword("bobby", "Bobby"); // then @@ -77,8 +74,8 @@ public void shouldRejectPasswordSameAsUsername() { } @Test - public void shouldRejectPasswordNotMatchingPattern() { - // given/when + void shouldRejectPasswordNotMatchingPattern() { + // given / when // service mock returns pattern a-zA-Z -> numbers should not be accepted ValidationResult error = validationService.validatePassword("invalid1234", "myPlayer"); @@ -87,8 +84,11 @@ public void shouldRejectPasswordNotMatchingPattern() { } @Test - public void shouldRejectTooShortPassword() { - // given/when + void shouldRejectTooShortPassword() { + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + + // when ValidationResult error = validationService.validatePassword("ab", "tester"); // then @@ -96,17 +96,26 @@ public void shouldRejectTooShortPassword() { } @Test - public void shouldRejectTooLongPassword() { - // given/when - ValidationResult error = validationService.validatePassword(Strings.repeat("a", 30), "player"); + void shouldRejectTooLongPassword() { + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + + // when + ValidationResult error = validationService.validatePassword(Strings.repeat("a", 21), "player"); // then assertErrorEquals(error, MessageKey.INVALID_PASSWORD_LENGTH); } @Test - public void shouldRejectUnsafePassword() { - // given/when + void shouldRejectUnsafePassword() { + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); + + // when ValidationResult error = validationService.validatePassword("unsafe", "playertest"); // then @@ -114,8 +123,13 @@ public void shouldRejectUnsafePassword() { } @Test - public void shouldAcceptValidPassword() { - // given/when + void shouldAcceptValidPassword() { + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); + + // when ValidationResult error = validationService.validatePassword("safePass", "some_user"); // then @@ -123,7 +137,7 @@ public void shouldAcceptValidPassword() { } @Test - public void shouldAcceptEmailWithEmptyLists() { + void shouldAcceptEmailWithEmptyLists() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)).willReturn(Collections.emptyList()); @@ -136,11 +150,10 @@ public void shouldAcceptEmailWithEmptyLists() { } @Test - public void shouldAcceptEmailWithWhitelist() { + void shouldAcceptEmailWithWhitelist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)) .willReturn(asList("domain.tld", "example.com")); - given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)).willReturn(Collections.emptyList()); // when boolean result = validationService.validateEmail("TesT@Example.com"); @@ -150,11 +163,10 @@ public void shouldAcceptEmailWithWhitelist() { } @Test - public void shouldRejectEmailNotInWhitelist() { + void shouldRejectEmailNotInWhitelist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)) .willReturn(asList("domain.tld", "example.com")); - given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)).willReturn(Collections.emptyList()); // when boolean result = validationService.validateEmail("email@other-domain.abc"); @@ -164,7 +176,7 @@ public void shouldRejectEmailNotInWhitelist() { } @Test - public void shouldAcceptEmailNotInBlacklist() { + void shouldAcceptEmailNotInBlacklist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)) @@ -178,7 +190,7 @@ public void shouldAcceptEmailNotInBlacklist() { } @Test - public void shouldRejectEmailInBlacklist() { + void shouldRejectEmailInBlacklist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)) @@ -192,31 +204,32 @@ public void shouldRejectEmailInBlacklist() { } @Test - public void shouldRejectInvalidEmail() { - // given/when/then + void shouldRejectInvalidEmail() { + // given / when / then assertThat(validationService.validateEmail("invalidinput"), equalTo(false)); } @Test - public void shouldRejectInvalidEmailWithoutDomain() { - // given/when/then + void shouldRejectInvalidEmailWithoutDomain() { + // given / when / then assertThat(validationService.validateEmail("invalidinput@"), equalTo(false)); } @Test - public void shouldRejectDefaultEmail() { - // given/when/then + void shouldRejectDefaultEmail() { + // given / when / then assertThat(validationService.validateEmail("your@email.com"), equalTo(false)); } @Test - public void shouldAllowRegistration() { + void shouldAllowRegistration() { // given CommandSender sender = mock(CommandSender.class); String email = "my.address@example.org"; given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(false); given(dataSource.countAuthsByEmail(email)).willReturn(2); + given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); @@ -226,13 +239,14 @@ public void shouldAllowRegistration() { } @Test - public void shouldRejectEmailWithTooManyAccounts() { + void shouldRejectEmailWithTooManyAccounts() { // given CommandSender sender = mock(CommandSender.class); String email = "mail@example.org"; given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(false); given(dataSource.countAuthsByEmail(email)).willReturn(5); + given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); @@ -242,23 +256,27 @@ public void shouldRejectEmailWithTooManyAccounts() { } @Test - public void shouldAllowBypassForPresentPermission() { + void shouldAllowBypassForPresentPermission() { // given CommandSender sender = mock(CommandSender.class); String email = "mail-address@example.com"; given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(true); - given(dataSource.countAuthsByEmail(email)).willReturn(7); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); // then + verifyNoInteractions(dataSource); assertThat(result, equalTo(true)); } @Test - public void shouldRecognizeUnrestrictedNames() { + void shouldRecognizeUnrestrictedNames() { + // given + given(settings.getProperty(RestrictionSettings.UNRESTRICTED_NAMES)).willReturn(newHashSet("name01", "npc")); + + // when / then assertThat(validationService.isUnrestricted("npc"), equalTo(true)); assertThat(validationService.isUnrestricted("someplayer"), equalTo(false)); assertThat(validationService.isUnrestricted("NAME01"), equalTo(true)); @@ -271,7 +289,7 @@ public void shouldRecognizeUnrestrictedNames() { } @Test - public void shouldNotInvokeGeoLiteApiIfCountryListsAreEmpty() { + void shouldNotInvokeGeoLiteApiIfCountryListsAreEmpty() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(Collections.emptyList()); @@ -285,10 +303,9 @@ public void shouldNotInvokeGeoLiteApiIfCountryListsAreEmpty() { } @Test - public void shouldAcceptCountryInWhitelist() { + void shouldAcceptCountryInWhitelist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(asList("ch", "it")); - given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(Collections.emptyList()); String ip = "127.0.0.1"; given(geoIpService.getCountryCode(ip)).willReturn("CH"); @@ -297,14 +314,12 @@ public void shouldAcceptCountryInWhitelist() { // then assertThat(result, equalTo(true)); - verify(geoIpService).getCountryCode(ip); } @Test - public void shouldRejectCountryMissingFromWhitelist() { + void shouldRejectCountryMissingFromWhitelist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(asList("ch", "it")); - given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(Collections.emptyList()); String ip = "123.45.67.89"; given(geoIpService.getCountryCode(ip)).willReturn("BR"); @@ -313,11 +328,10 @@ public void shouldRejectCountryMissingFromWhitelist() { // then assertThat(result, equalTo(false)); - verify(geoIpService).getCountryCode(ip); } @Test - public void shouldAcceptCountryAbsentFromBlacklist() { + void shouldAcceptCountryAbsentFromBlacklist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(asList("ch", "it")); @@ -333,7 +347,7 @@ public void shouldAcceptCountryAbsentFromBlacklist() { } @Test - public void shouldRejectCountryInBlacklist() { + void shouldRejectCountryInBlacklist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(asList("ch", "it")); @@ -345,11 +359,10 @@ public void shouldRejectCountryInBlacklist() { // then assertThat(result, equalTo(false)); - verify(geoIpService).getCountryCode(ip); } @Test - public void shouldCheckNameRestrictions() { + void shouldCheckNameRestrictions() { // given given(settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)).willReturn(true); given(settings.getProperty(RestrictionSettings.RESTRICTED_USERS)) @@ -363,7 +376,8 @@ public void shouldCheckNameRestrictions() { Player emanuel = mockPlayer("emanuel", "94.65.24.10"); Player emanuel2 = mockPlayer("emanuel", "94.65.60.10"); Player imYourIsp = mockPlayer("imyourisp", "65.65.65.65"); - Player notRestricted = mockPlayer("notRestricted", "0.0.0.0"); + Player notRestricted = mock(Player.class); + given(notRestricted.getName()).willReturn("notRestricted"); ValidationService validationServiceSpy = Mockito.spy(validationService); willReturn("bogus.tld").given(validationServiceSpy).getHostName(any(InetSocketAddress.class)); @@ -389,10 +403,11 @@ public void shouldCheckNameRestrictions() { assertThat(isEmanuel2Admitted, equalTo(false)); assertThat(isImYourIspAdmitted, equalTo(true)); assertThat(isNotRestrictedAdmitted, equalTo(true)); + verify(notRestricted, only()).getName(); } @Test - public void shouldLogWarningForInvalidRestrictionRule() { + void shouldLogWarningForInvalidRestrictionRule() { // given Logger logger = TestHelper.setupLogger(); given(settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)).willReturn(true); diff --git a/src/test/java/fr/xephi/authme/service/yaml/YamlFileResourceProviderTest.java b/src/test/java/fr/xephi/authme/service/yaml/YamlFileResourceProviderTest.java index 3b6bbddbbf..78ad541c6b 100644 --- a/src/test/java/fr/xephi/authme/service/yaml/YamlFileResourceProviderTest.java +++ b/src/test/java/fr/xephi/authme/service/yaml/YamlFileResourceProviderTest.java @@ -2,23 +2,23 @@ import ch.jalu.configme.resource.YamlFileResource; import fr.xephi.authme.TestHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.parser.ParserException; import java.io.File; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link YamlFileResourceProvider}. */ -public class YamlFileResourceProviderTest { +class YamlFileResourceProviderTest { @Test - public void shouldLoadValidFile() { + void shouldLoadValidFile() { // given File yamlFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "service/yaml/validYaml.yml"); @@ -30,7 +30,7 @@ public void shouldLoadValidFile() { } @Test - public void shouldThrowForInvalidFile() { + void shouldThrowForInvalidFile() { // given File yamlFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "service/yaml/invalidYaml.yml"); diff --git a/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java b/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java index f589e6c33a..528d5b048c 100644 --- a/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java @@ -6,8 +6,8 @@ import com.google.common.collect.ImmutableSet; import fr.xephi.authme.settings.properties.AuthMeSettingsRetriever; import fr.xephi.authme.settings.properties.SecuritySettings; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -18,12 +18,12 @@ import java.util.stream.Collectors; import static fr.xephi.authme.ReflectionTestUtils.getFieldValue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests the consistency of the settings configuration. */ -public class SettingsConsistencyTest { +class SettingsConsistencyTest { /** * Maximum characters one comment line may have (prevents horizontal scrolling). @@ -38,13 +38,13 @@ public class SettingsConsistencyTest { private static ConfigurationData configurationData; - @BeforeClass - public static void buildConfigurationData() { + @BeforeAll + static void buildConfigurationData() { configurationData = AuthMeSettingsRetriever.buildConfigurationData(); } @Test - public void shouldHaveCommentOnEachProperty() { + void shouldHaveCommentOnEachProperty() { // given List> properties = configurationData.getProperties(); @@ -57,7 +57,7 @@ public void shouldHaveCommentOnEachProperty() { } @Test - public void shouldNotHaveVeryLongCommentLines() { + void shouldNotHaveVeryLongCommentLines() { // given Map> commentEntries = configurationData.getAllComments(); List badPaths = new ArrayList<>(0); @@ -86,7 +86,7 @@ public void shouldNotHaveVeryLongCommentLines() { * so the user knows which values are available. */ @Test - public void shouldMentionAllEnumValues() { + void shouldMentionAllEnumValues() { // given Map, Enum> invalidEnumProperties = new HashMap<>(); diff --git a/src/test/java/fr/xephi/authme/settings/SettingsIntegrationTest.java b/src/test/java/fr/xephi/authme/settings/SettingsIntegrationTest.java index e9a58c6771..be401584ca 100644 --- a/src/test/java/fr/xephi/authme/settings/SettingsIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/settings/SettingsIntegrationTest.java @@ -11,11 +11,9 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.properties.TestConfiguration; import fr.xephi.authme.settings.properties.TestEnum; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -24,13 +22,13 @@ import java.util.Map; import static fr.xephi.authme.TestHelper.getJarFile; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Integration test for {@link Settings} (ConfigMe integration). */ -public class SettingsIntegrationTest { +class SettingsIntegrationTest { /** File name of the sample config including all {@link TestConfiguration} values. */ private static final String COMPLETE_FILE = TestHelper.PROJECT_ROOT + "settings/config-sample-values.yml"; @@ -40,27 +38,20 @@ public class SettingsIntegrationTest { private static ConfigurationData CONFIG_DATA = ConfigurationDataBuilder.createConfiguration(TestConfiguration.class); - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File testPluginFolder; - private File testPluginFolder; - - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } - @Before - public void setUpTestPluginFolder() throws IOException { - testPluginFolder = temporaryFolder.newFolder(); - } - @Test - public void shouldLoadAndReadAllProperties() throws IOException { + void shouldLoadAndReadAllProperties() throws IOException { // given PropertyResource resource = new YamlFileResource(copyFileFromResources(COMPLETE_FILE)); // Pass another, non-existent file to check if the settings had to be rewritten - File newFile = temporaryFolder.newFile(); + File newFile = TestHelper.createFile(testPluginFolder, "newfile"); // when / then Settings settings = new Settings(testPluginFolder, resource, @@ -85,7 +76,7 @@ public void shouldLoadAndReadAllProperties() throws IOException { } @Test - public void shouldWriteMissingProperties() { + void shouldWriteMissingProperties() { // given/when File file = copyFileFromResources(INCOMPLETE_FILE); PropertyResource resource = new YamlFileResource(file); @@ -117,9 +108,9 @@ public void shouldWriteMissingProperties() { } @Test - public void shouldReloadSettings() throws IOException { + void shouldReloadSettings() throws IOException { // given - File configFile = temporaryFolder.newFile(); + File configFile = TestHelper.createFile(testPluginFolder, "settings"); PropertyResource resource = new YamlFileResource(configFile); Settings settings = new Settings(testPluginFolder, resource, null, CONFIG_DATA); @@ -135,7 +126,7 @@ public void shouldReloadSettings() throws IOException { private File copyFileFromResources(String path) { try { File source = getJarFile(path); - File destination = temporaryFolder.newFile(); + File destination = TestHelper.createFile(testPluginFolder, "fileFromJar"); Files.copy(source, destination); return destination; } catch (IOException e) { diff --git a/src/test/java/fr/xephi/authme/settings/SettingsMigrationServiceTest.java b/src/test/java/fr/xephi/authme/settings/SettingsMigrationServiceTest.java index 021bfb93b6..a2e2a6840c 100644 --- a/src/test/java/fr/xephi/authme/settings/SettingsMigrationServiceTest.java +++ b/src/test/java/fr/xephi/authme/settings/SettingsMigrationServiceTest.java @@ -12,10 +12,9 @@ import fr.xephi.authme.process.register.RegistrationType; import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.settings.properties.AuthMeSettingsRetriever; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -37,30 +36,29 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.FORCE_SPAWN_ON_WORLDS; import static fr.xephi.authme.settings.properties.SecuritySettings.LEGACY_HASHES; import static fr.xephi.authme.settings.properties.SecuritySettings.PASSWORD_HASH; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link SettingsMigrationService}. */ -public class SettingsMigrationServiceTest { +class SettingsMigrationServiceTest { private static final String OLD_CONFIG_FILE = TestHelper.PROJECT_ROOT + "settings/config-old.yml"; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File dataFolder; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } /* When settings are loaded, test that migrations are applied and immediately available in memory. */ @Test - public void shouldPerformMigrationsInMemory() throws IOException { + void shouldPerformMigrationsInMemory() throws IOException { // given - File dataFolder = temporaryFolder.newFolder(); File configFile = new File(dataFolder, "config.yml"); Files.copy(getJarFile(OLD_CONFIG_FILE), configFile); PropertyResource resource = new YamlFileResource(configFile); @@ -79,9 +77,8 @@ public void shouldPerformMigrationsInMemory() throws IOException { * i.e. when the settings are loaded again from the file, no migrations should be necessary. */ @Test - public void shouldPerformMigrationsAndPersistToDisk() throws IOException { + void shouldPerformMigrationsAndPersistToDisk() throws IOException { // given - File dataFolder = temporaryFolder.newFolder(); File configFile = new File(dataFolder, "config.yml"); Files.copy(getJarFile(OLD_CONFIG_FILE), configFile); PropertyResource resource = new YamlFileResource(configFile); @@ -99,9 +96,8 @@ public void shouldPerformMigrationsAndPersistToDisk() throws IOException { } @Test - public void shouldKeepOldOtherAccountsSettings() throws IOException { + void shouldKeepOldOtherAccountsSettings() throws IOException { // given - File dataFolder = temporaryFolder.newFolder(); File configFile = new File(dataFolder, "config.yml"); Files.copy(getJarFile(OLD_CONFIG_FILE), configFile); PropertyResource resource = new YamlFileResource(configFile); diff --git a/src/test/java/fr/xephi/authme/settings/SettingsTest.java b/src/test/java/fr/xephi/authme/settings/SettingsTest.java index 73d3cc8d6c..d47d421f00 100644 --- a/src/test/java/fr/xephi/authme/settings/SettingsTest.java +++ b/src/test/java/fr/xephi/authme/settings/SettingsTest.java @@ -6,19 +6,17 @@ import ch.jalu.configme.resource.PropertyResource; import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.properties.TestConfiguration; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Collections; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; @@ -27,27 +25,21 @@ /** * Unit tests for {@link Settings}. */ -public class SettingsTest { +class SettingsTest { private static final ConfigurationData CONFIG_DATA = ConfigurationDataBuilder.createConfiguration(TestConfiguration.class); - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private File testPluginFolder; + @TempDir + File testPluginFolder; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } - @Before - public void setUpTestPluginFolder() throws IOException { - testPluginFolder = temporaryFolder.newFolder(); - } - @Test - public void shouldLoadEmailMessage() throws IOException { + void shouldLoadEmailMessage() throws IOException { // given String emailMessage = "Sample email message\nThat's all!"; File emailFile = new File(testPluginFolder, "email.html"); @@ -65,7 +57,7 @@ public void shouldLoadEmailMessage() throws IOException { } @Test - public void shouldLoadRecoveryCodeMessage() throws IOException { + void shouldLoadRecoveryCodeMessage() throws IOException { // given String emailMessage = "Your recovery code is %code."; File emailFile = new File(testPluginFolder, "recovery_code_email.html"); @@ -83,7 +75,7 @@ public void shouldLoadRecoveryCodeMessage() throws IOException { } @Test - public void shouldLoadVerificationMessage() throws IOException { + void shouldLoadVerificationMessage() throws IOException { // given String emailMessage = "Please verify your identity with ."; File emailFile = new File(testPluginFolder, "verification_code_email.html"); diff --git a/src/test/java/fr/xephi/authme/settings/SettingsWarnerTest.java b/src/test/java/fr/xephi/authme/settings/SettingsWarnerTest.java index fbea9f9afd..0e1a68aa53 100644 --- a/src/test/java/fr/xephi/authme/settings/SettingsWarnerTest.java +++ b/src/test/java/fr/xephi/authme/settings/SettingsWarnerTest.java @@ -1,6 +1,5 @@ package fr.xephi.authme.settings; -import fr.xephi.authme.AuthMe; import fr.xephi.authme.TestHelper; import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.service.BukkitService; @@ -9,11 +8,11 @@ import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.SecuritySettings; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Optional; import java.util.logging.Logger; @@ -27,8 +26,8 @@ /** * Test for {@link SettingsWarner}. */ -@RunWith(MockitoJUnitRunner.class) -public class SettingsWarnerTest { +@ExtendWith(MockitoExtension.class) +class SettingsWarnerTest { @InjectMocks private SettingsWarner settingsWarner; @@ -40,7 +39,7 @@ public class SettingsWarnerTest { private BukkitService bukkitService; @Test - public void shouldLogWarnings() { + void shouldLogWarnings() { // given Logger logger = TestHelper.setupLogger(); given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(false); @@ -60,7 +59,8 @@ public void shouldLogWarnings() { } @Test - public void shouldWarnBungeeWithoutSpigot() { + void shouldWarnBungeeWithoutSpigot() { + // given Logger logger = TestHelper.setupLogger(); // this cannot be covered above, because it's conflicting with the other settings @@ -80,7 +80,8 @@ public void shouldWarnBungeeWithoutSpigot() { } @Test - public void shouldNotLogAnyWarning() { + void shouldNotLogAnyWarning() { + // given Logger logger = TestHelper.setupLogger(); given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(25); diff --git a/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java b/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java index edd561925e..8e947c0853 100644 --- a/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java +++ b/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java @@ -1,37 +1,33 @@ package fr.xephi.authme.settings; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; import fr.xephi.authme.TestHelper; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.PluginHookService; import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link SpawnLoader}. */ -@RunWith(DelayedInjectionRunner.class) -public class SpawnLoaderTest { +@ExtendWith(MockitoExtension.class) +class SpawnLoaderTest { - @InjectDelayed private SpawnLoader spawnLoader; @Mock @@ -40,16 +36,12 @@ public class SpawnLoaderTest { @Mock private PluginHookService pluginHookService; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File testFolder; - @DataFolder - private File testFolder; - - @BeforeInjecting - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { // Copy test config into a new temporary folder - testFolder = temporaryFolder.newFolder(); File source = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/spawn-firstspawn.yml"); File destination = new File(testFolder, "spawn.yml"); Files.copy(source, destination); @@ -57,10 +49,11 @@ public void setup() throws IOException { // Create a settings mock with default values given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)) .willReturn("authme, essentials, multiverse, default"); + spawnLoader = new SpawnLoader(testFolder, settings, pluginHookService); } @Test - public void shouldSetSpawn() { + void shouldSetSpawn() { // given World world = mock(World.class); given(world.getName()).willReturn("new_world"); @@ -77,5 +70,4 @@ public void shouldSetSpawn() { assertThat(configuration.getDouble("spawn.z"), equalTo(-67.89)); assertThat(configuration.getString("spawn.world"), equalTo("new_world")); } - } diff --git a/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java b/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java index 3415a95077..4e7496428c 100644 --- a/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java +++ b/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java @@ -1,11 +1,8 @@ package fr.xephi.authme.settings; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionRunner; -import ch.jalu.injector.testing.InjectDelayed; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.GeoIpService; @@ -14,11 +11,13 @@ import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Player; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -26,10 +25,10 @@ import java.util.Arrays; 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.hasSize; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -37,10 +36,10 @@ /** * Test for {@link WelcomeMessageConfiguration}. */ -@RunWith(DelayedInjectionRunner.class) -public class WelcomeMessageConfigurationTest { +@ExtendWith(MockitoExtension.class) +class WelcomeMessageConfigurationTest { - @InjectDelayed + @InjectMocks private WelcomeMessageConfiguration welcomeMessageConfiguration; @Mock private Server server; @@ -52,24 +51,21 @@ public class WelcomeMessageConfigurationTest { private PlayerCache playerCache; @Mock private CommonService service; - @DataFolder - private File testPluginFolder; + @TempDir + File testPluginFolder; private File welcomeFile; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @BeforeInjecting - public void createPluginFolder() throws IOException { - testPluginFolder = temporaryFolder.newFolder(); + @BeforeEach + void createWelcomeFileAndSetPluginFolder() throws IOException { welcomeFile = new File(testPluginFolder, "welcome.txt"); welcomeFile.createNewFile(); given(service.getProperty(RegistrationSettings.USE_WELCOME_MESSAGE)).willReturn(true); + ReflectionTestUtils.setField(welcomeMessageConfiguration, "pluginFolder", testPluginFolder); } @Test - public void shouldLoadWelcomeMessage() { + void shouldLoadWelcomeMessage() { // given String welcomeMessage = "This is my welcome message for testing\nBye!"; setWelcomeMessageAndReload(welcomeMessage); @@ -85,7 +81,7 @@ public void shouldLoadWelcomeMessage() { } @Test - public void shouldReplaceNameAndIpAndCountry() { + void shouldReplaceNameAndIpAndCountry() { // given String welcomeMessage = "Hello {PLAYER}, your IP is {IP}\nYour country is {COUNTRY}.\nWelcome to {SERVER}!"; setWelcomeMessageAndReload(welcomeMessage); @@ -108,7 +104,7 @@ public void shouldReplaceNameAndIpAndCountry() { } @Test - public void shouldApplyOtherReplacements() { + void shouldApplyOtherReplacements() { // given String welcomeMessage = "{ONLINE}/{MAXPLAYERS} online\n{LOGINS} logged in\nYour world is {WORLD}\nServer: {VERSION}"; setWelcomeMessageAndReload(welcomeMessage); diff --git a/src/test/java/fr/xephi/authme/settings/commandconfig/CommandManagerTest.java b/src/test/java/fr/xephi/authme/settings/commandconfig/CommandManagerTest.java index 2a586c5769..b6a009a01c 100644 --- a/src/test/java/fr/xephi/authme/settings/commandconfig/CommandManagerTest.java +++ b/src/test/java/fr/xephi/authme/settings/commandconfig/CommandManagerTest.java @@ -7,14 +7,14 @@ import fr.xephi.authme.service.GeoIpService; import fr.xephi.authme.settings.SettingsMigrationService; import org.bukkit.entity.Player; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -34,8 +34,8 @@ /** * Test for {@link CommandManager}. */ -@RunWith(MockitoJUnitRunner.class) -public class CommandManagerTest { +@ExtendWith(MockitoExtension.class) +class CommandManagerTest { private static final String TEST_FILES_FOLDER = "/fr/xephi/authme/settings/commandconfig/"; @@ -52,108 +52,152 @@ public class CommandManagerTest { @Mock private SettingsMigrationService settingsMigrationService; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File temporaryFolder; - private File testFolder; - - @Before - public void setup() throws IOException { - testFolder = temporaryFolder.newFolder(); - player = mockPlayer(); - BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + @BeforeEach + void setup() { + player = mock(Player.class); + given(player.getName()).willReturn("Bobby"); } - @Test - public void shouldExecuteCommandsOnLogin() { - // given - copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); - initManager(); + @Nested + class TestsWithPlayerIp { - // when - manager.runCommandsOnLogin(player, Collections.emptyList()); + @BeforeEach + void setup() { + TestHelper.mockIpAddressToPlayer(player, "127.0.0.3"); + } - // then - verify(bukkitService).dispatchConsoleCommand("msg Bobby Welcome back"); - verify(bukkitService).dispatchCommand(any(Player.class), eq("motd")); - verify(bukkitService).dispatchCommand(any(Player.class), eq("list")); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(60L)); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(120L)); - verifyNoMoreInteractions(bukkitService); - verifyNoInteractions(geoIpService); - } + @Test + void shouldExecuteCommandsOnLoginWithTwentyFiveAlts() { + // given + copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); + initManager(); + BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + + // when + manager.runCommandsOnLogin(player, Collections.nCopies(25, "yolo")); + + // then + verify(bukkitService).dispatchConsoleCommand("msg Bobby Welcome back"); + verify(bukkitService).dispatchCommand(player, "motd"); + verify(bukkitService).dispatchCommand(player, "list"); + verify(bukkitService).dispatchConsoleCommand("helpop Player Bobby has more than 1 account"); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(60L)); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(120L)); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(180L)); + verifyNoMoreInteractions(bukkitService); + verifyNoInteractions(geoIpService); + } - @Test - public void shouldExecuteCommandsOnLoginWithTwoAlts() { - // given - copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); - initManager(); + @Test + void shouldExecuteCommandsOnLogin() { + // given + copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); + initManager(); + BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + + // when + manager.runCommandsOnLogin(player, Collections.emptyList()); + + // then + verify(bukkitService).dispatchConsoleCommand("msg Bobby Welcome back"); + verify(bukkitService).dispatchCommand(any(Player.class), eq("motd")); + verify(bukkitService).dispatchCommand(any(Player.class), eq("list")); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(60L)); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(120L)); + verifyNoMoreInteractions(bukkitService); + verifyNoInteractions(geoIpService); + } - // when - manager.runCommandsOnLogin(player, Arrays.asList("willy", "nilly", "billy", "silly")); + @Test + void shouldExecuteCommandsOnRegister() { + // given + copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); + initManager(); + BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + given(geoIpService.getCountryName("127.0.0.3")).willReturn("Syldavia"); + + // when + manager.runCommandsOnRegister(player); + + // then + verify(bukkitService).dispatchCommand(any(Player.class), eq("me I just registered")); + verify(bukkitService).dispatchConsoleCommand("log Bobby (127.0.0.3, Syldavia) registered"); + verify(bukkitService, times(2)).scheduleSyncDelayedTask(any(Runnable.class), eq(100L)); + verifyNoMoreInteractions(bukkitService); + } - // then - verify(bukkitService).dispatchConsoleCommand("msg Bobby Welcome back"); - verify(bukkitService).dispatchCommand(player, "motd"); - verify(bukkitService).dispatchCommand(player, "list"); - verify(bukkitService).dispatchConsoleCommand("helpop Player Bobby has more than 1 account"); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(60L)); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(120L)); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(180L)); - verifyNoMoreInteractions(bukkitService); - verifyNoInteractions(geoIpService); - } + @Test + void shouldExecuteCommandsOnLoginWithTwoAlts() { + // given + copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); + initManager(); + BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + + // when + manager.runCommandsOnLogin(player, Arrays.asList("willy", "nilly", "billy", "silly")); + + // then + verify(bukkitService).dispatchConsoleCommand("msg Bobby Welcome back"); + verify(bukkitService).dispatchCommand(player, "motd"); + verify(bukkitService).dispatchCommand(player, "list"); + verify(bukkitService).dispatchConsoleCommand("helpop Player Bobby has more than 1 account"); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(60L)); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(120L)); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(180L)); + verifyNoMoreInteractions(bukkitService); + verifyNoInteractions(geoIpService); + } - @Test - public void shouldExecuteCommandsOnLoginWithFifteenAlts() { - // given - copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); - initManager(); + @Test + void shouldExecuteCommandsOnLoginWithFifteenAlts() { + // given + copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); + initManager(); + BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + + // when + manager.runCommandsOnLogin(player, Collections.nCopies(15, "swag")); + + // then + verify(bukkitService).dispatchConsoleCommand("msg Bobby Welcome back"); + verify(bukkitService).dispatchCommand(player, "motd"); + verify(bukkitService).dispatchCommand(player, "list"); + verify(bukkitService).dispatchConsoleCommand("helpop Player Bobby has more than 1 account"); + verify(bukkitService).dispatchConsoleCommand("log Bobby 127.0.0.3 many accounts"); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(60L)); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(120L)); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(180L)); + verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(240L)); + verifyNoMoreInteractions(bukkitService); + verifyNoInteractions(geoIpService); + } - // when - manager.runCommandsOnLogin(player, Collections.nCopies(15, "swag")); + @Test + void shouldExecuteCommandOnLogout() { + // given + copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); + initManager(); - // then - verify(bukkitService).dispatchConsoleCommand("msg Bobby Welcome back"); - verify(bukkitService).dispatchCommand(player, "motd"); - verify(bukkitService).dispatchCommand(player, "list"); - verify(bukkitService).dispatchConsoleCommand("helpop Player Bobby has more than 1 account"); - verify(bukkitService).dispatchConsoleCommand("log Bobby 127.0.0.3 many accounts"); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(60L)); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(120L)); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(180L)); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(240L)); - verifyNoMoreInteractions(bukkitService); - verifyNoInteractions(geoIpService); - } + // when + manager.runCommandsOnLogout(player); - @Test - public void shouldExecuteCommandsOnLoginWithTwentyFiveAlts() { - // given - copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); - initManager(); - - // when - manager.runCommandsOnLogin(player, Collections.nCopies(25, "yolo")); - - // then - verify(bukkitService).dispatchConsoleCommand("msg Bobby Welcome back"); - verify(bukkitService).dispatchCommand(player, "motd"); - verify(bukkitService).dispatchCommand(player, "list"); - verify(bukkitService).dispatchConsoleCommand("helpop Player Bobby has more than 1 account"); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(60L)); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(120L)); - verify(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), eq(180L)); - verifyNoMoreInteractions(bukkitService); - verifyNoInteractions(geoIpService); + // then + verify(bukkitService).dispatchConsoleCommand("broadcast Bobby (127.0.0.3) logged out"); + verifyNoMoreInteractions(bukkitService); + verifyNoInteractions(geoIpService); + } } @Test - public void shouldExecuteCommandsOnLoginWithIncompleteConfig() { + void shouldExecuteCommandsOnLoginWithIncompleteConfig() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.incomplete.yml"); initManager(); BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + given(player.getDisplayName()).willReturn("bob"); // when manager.runCommandsOnLogin(player, Collections.emptyList()); @@ -167,7 +211,7 @@ public void shouldExecuteCommandsOnLoginWithIncompleteConfig() { } @Test - public void shouldExecuteCommandsOnSessionLogin() { + void shouldExecuteCommandsOnSessionLogin() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); @@ -182,7 +226,7 @@ public void shouldExecuteCommandsOnSessionLogin() { } @Test - public void shouldExecuteCommandsOnFirstLogin() { + void shouldExecuteCommandsOnFirstLogin() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); @@ -197,7 +241,7 @@ public void shouldExecuteCommandsOnFirstLogin() { } @Test - public void shouldNotExecuteFirstLoginCommandWhoseThresholdIsNotMet() { + void shouldNotExecuteFirstLoginCommandWhoseThresholdIsNotMet() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); @@ -210,10 +254,12 @@ public void shouldNotExecuteFirstLoginCommandWhoseThresholdIsNotMet() { } @Test - public void shouldExecuteCommandsOnJoin() { + void shouldExecuteCommandsOnJoin() { // given + player.getName(); // Prevent UnnecessaryStubbingException as the name is not needed copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); + given(player.getDisplayName()).willReturn("bob"); // when manager.runCommandsOnJoin(player); @@ -224,7 +270,7 @@ public void shouldExecuteCommandsOnJoin() { } @Test - public void shouldExecuteCommandsOnJoinWithIncompleteConfig() { + void shouldExecuteCommandsOnJoinWithIncompleteConfig() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.incomplete.yml"); initManager(); @@ -238,39 +284,9 @@ public void shouldExecuteCommandsOnJoinWithIncompleteConfig() { } @Test - public void shouldExecuteCommandsOnRegister() { - // given - copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); - initManager(); - - // when - manager.runCommandsOnRegister(player); - - // then - verify(bukkitService).dispatchCommand(any(Player.class), eq("me I just registered")); - verify(bukkitService).dispatchConsoleCommand("log Bobby (127.0.0.3, Syldavia) registered"); - verify(bukkitService, times(2)).scheduleSyncDelayedTask(any(Runnable.class), eq(100L)); - verifyNoMoreInteractions(bukkitService); - } - - @Test - public void shouldExecuteCommandOnLogout() { - // given - copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); - initManager(); - - // when - manager.runCommandsOnLogout(player); - - // then - verify(bukkitService).dispatchConsoleCommand("broadcast Bobby (127.0.0.3) logged out"); - verifyNoMoreInteractions(bukkitService); - verifyNoInteractions(geoIpService); - } - - @Test - public void shouldExecuteCommandsOnRegisterWithIncompleteConfig() { + void shouldExecuteCommandsOnRegisterWithIncompleteConfig() { // given + player.getName(); // Prevent UnnecessaryStubbingException as the name is not needed copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.incomplete.yml"); initManager(); @@ -282,7 +298,7 @@ public void shouldExecuteCommandsOnRegisterWithIncompleteConfig() { } @Test - public void shouldExecuteCommandOnUnregister() { + void shouldExecuteCommandOnUnregister() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.incomplete.yml"); initManager(); @@ -295,26 +311,16 @@ public void shouldExecuteCommandOnUnregister() { } private void initManager() { - manager = new CommandManager(testFolder, bukkitService, geoIpService, commandMigrationService); + manager = new CommandManager(temporaryFolder, bukkitService, geoIpService, commandMigrationService); } private void copyJarFileAsCommandsYml(String path) { File source = TestHelper.getJarFile(path); - File destination = new File(testFolder, "commands.yml"); + File destination = new File(temporaryFolder, "commands.yml"); try { Files.copy(source, destination); } catch (IOException e) { throw new IllegalStateException(e); } } - - private Player mockPlayer() { - Player player = mock(Player.class); - given(player.getName()).willReturn("Bobby"); - given(player.getDisplayName()).willReturn("bob"); - String ip = "127.0.0.3"; - TestHelper.mockIpAddressToPlayer(player, ip); - given(geoIpService.getCountryName(ip)).willReturn("Syldavia"); - return player; - } } diff --git a/src/test/java/fr/xephi/authme/settings/commandconfig/CommandMigrationServiceTest.java b/src/test/java/fr/xephi/authme/settings/commandconfig/CommandMigrationServiceTest.java index 800bcc0524..094b04983a 100644 --- a/src/test/java/fr/xephi/authme/settings/commandconfig/CommandMigrationServiceTest.java +++ b/src/test/java/fr/xephi/authme/settings/commandconfig/CommandMigrationServiceTest.java @@ -8,12 +8,12 @@ import ch.jalu.configme.resource.YamlFileResource; import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.SettingsMigrationService; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.util.List; @@ -22,17 +22,17 @@ import java.util.stream.Collectors; import static com.google.common.collect.Sets.newHashSet; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.aMapWithSize; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; /** * Test for {@link CommandMigrationService}. */ -@RunWith(MockitoJUnitRunner.class) -public class CommandMigrationServiceTest { +@ExtendWith(MockitoExtension.class) +class CommandMigrationServiceTest { @InjectMocks private CommandMigrationService commandMigrationService; @@ -40,13 +40,13 @@ public class CommandMigrationServiceTest { @Mock private SettingsMigrationService settingsMigrationService; - @BeforeClass - public static void setUpLogger() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldRewriteForEmptyFile() { + void shouldRewriteForEmptyFile() { // given File commandFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/commandconfig/commands.empty.yml"); PropertyResource resource = new YamlFileResource(commandFile); @@ -60,7 +60,7 @@ public void shouldRewriteForEmptyFile() { } @Test - public void shouldRewriteIncompleteFile() { + void shouldRewriteIncompleteFile() { // given File commandFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/commandconfig/commands.incomplete.yml"); PropertyResource resource = new YamlFileResource(commandFile); @@ -74,7 +74,7 @@ public void shouldRewriteIncompleteFile() { } @Test - public void shouldNotChangeCompleteFile() { + void shouldNotChangeCompleteFile() { // given File commandFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/commandconfig/commands.complete.yml"); PropertyResource resource = new YamlFileResource(commandFile); @@ -92,7 +92,7 @@ public void shouldNotChangeCompleteFile() { * {@link CommandConfig} class. It is used to ensure that the commands.yml file is complete. */ @Test - public void shouldHaveAllPropertiesFromCommandConfig() { + void shouldHaveAllPropertiesFromCommandConfig() { // given String[] properties = new BeanDescriptionFactoryImpl() .getAllProperties(CommandConfig.class) @@ -105,7 +105,7 @@ public void shouldHaveAllPropertiesFromCommandConfig() { } @Test - public void shouldMigrateOldOtherAccountsCommand() { + void shouldMigrateOldOtherAccountsCommand() { // given given(settingsMigrationService.hasOldOtherAccountsCommand()).willReturn(true); given(settingsMigrationService.getOldOtherAccountsCommand()) diff --git a/src/test/java/fr/xephi/authme/settings/commandconfig/CommandYmlConsistencyTest.java b/src/test/java/fr/xephi/authme/settings/commandconfig/CommandYmlConsistencyTest.java index 99b4d615be..9df83051b2 100644 --- a/src/test/java/fr/xephi/authme/settings/commandconfig/CommandYmlConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/settings/commandconfig/CommandYmlConsistencyTest.java @@ -5,25 +5,23 @@ import ch.jalu.configme.resource.YamlFileResource; import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.SettingsMigrationService; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; /** * Tests that commands.yml is well-formed. */ -@RunWith(MockitoJUnitRunner.class) -public class CommandYmlConsistencyTest { +@ExtendWith(MockitoExtension.class) +class CommandYmlConsistencyTest { @InjectMocks private CommandMigrationService commandMigrationService; @@ -31,11 +29,8 @@ public class CommandYmlConsistencyTest { @Mock private SettingsMigrationService settingsMigrationService; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Test - public void shouldLoadWithNoMigrations() { + void shouldLoadWithNoMigrations() { // given File commandFile = TestHelper.getJarFile("/commands.yml"); PropertyResource resource = new YamlFileResource(commandFile); diff --git a/src/test/java/fr/xephi/authme/settings/properties/AuthMeSettingsRetrieverTest.java b/src/test/java/fr/xephi/authme/settings/properties/AuthMeSettingsRetrieverTest.java index 35ab9627a7..c3c88c8bd0 100644 --- a/src/test/java/fr/xephi/authme/settings/properties/AuthMeSettingsRetrieverTest.java +++ b/src/test/java/fr/xephi/authme/settings/properties/AuthMeSettingsRetrieverTest.java @@ -1,18 +1,18 @@ package fr.xephi.authme.settings.properties; import ch.jalu.configme.configurationdata.ConfigurationData; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.closeTo; -import static org.junit.Assert.assertThat; /** * Test for {@link AuthMeSettingsRetriever}. */ -public class AuthMeSettingsRetrieverTest { +class AuthMeSettingsRetrieverTest { @Test - public void shouldReturnAllProperties() { + void shouldReturnAllProperties() { // given / when ConfigurationData configurationData = AuthMeSettingsRetriever.buildConfigurationData(); diff --git a/src/test/java/fr/xephi/authme/settings/properties/SettingsClassConsistencyTest.java b/src/test/java/fr/xephi/authme/settings/properties/SettingsClassConsistencyTest.java index 178576bc17..2084b43dca 100644 --- a/src/test/java/fr/xephi/authme/settings/properties/SettingsClassConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/settings/properties/SettingsClassConsistencyTest.java @@ -6,8 +6,8 @@ import fr.xephi.authme.ClassCollector; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.lang.reflect.Modifier; @@ -16,21 +16,21 @@ 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.hasSize; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link SettingsHolder} implementations. */ -public class SettingsClassConsistencyTest { +class SettingsClassConsistencyTest { private static final String SETTINGS_FOLDER = TestHelper.PROJECT_ROOT + "settings/properties"; private static List> classes; - @BeforeClass - public static void scanForSettingsClasses() { + @BeforeAll + static void scanForSettingsClasses() { ClassCollector collector = new ClassCollector(TestHelper.SOURCES_FOLDER, SETTINGS_FOLDER); classes = collector.collectClasses(SettingsHolder.class); @@ -44,7 +44,7 @@ public static void scanForSettingsClasses() { * Make sure that all {@link Property} instances we define are in public, static, final fields. */ @Test - public void shouldHavePublicStaticFinalFields() { + void shouldHavePublicStaticFinalFields() { for (Class clazz : classes) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { @@ -61,7 +61,7 @@ public void shouldHavePublicStaticFinalFields() { * Make sure that no properties use the same path. */ @Test - public void shouldHaveUniquePaths() { + void shouldHaveUniquePaths() { Set paths = new HashSet<>(); for (Class clazz : classes) { Field[] fields = clazz.getDeclaredFields(); @@ -82,7 +82,7 @@ public void shouldHaveUniquePaths() { * available SettingsHolder classes. */ @Test - public void shouldHaveAllClassesInConfigurationData() { + void shouldHaveAllClassesInConfigurationData() { // given long totalProperties = classes.stream() .map(Class::getDeclaredFields) diff --git a/src/test/java/fr/xephi/authme/task/CleanupTaskTest.java b/src/test/java/fr/xephi/authme/task/CleanupTaskTest.java index 4269f9bd78..2ddb2e696f 100644 --- a/src/test/java/fr/xephi/authme/task/CleanupTaskTest.java +++ b/src/test/java/fr/xephi/authme/task/CleanupTaskTest.java @@ -2,11 +2,11 @@ import ch.jalu.injector.factory.SingletonStore; import fr.xephi.authme.initialization.HasCleanup; -import org.junit.Test; -import org.junit.runner.RunWith; +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.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; @@ -18,8 +18,8 @@ /** * Test for {@link CleanupTask}. */ -@RunWith(MockitoJUnitRunner.class) -public class CleanupTaskTest { +@ExtendWith(MockitoExtension.class) +class CleanupTaskTest { @InjectMocks private CleanupTask cleanupTask; @@ -28,7 +28,7 @@ public class CleanupTaskTest { private SingletonStore hasCleanupStore; @Test - public void shouldPerformCleanup() { + void shouldPerformCleanup() { // given List services = asList(mock(HasCleanup.class), mock(HasCleanup.class), mock(HasCleanup.class)); given(hasCleanupStore.retrieveAllOfType()).willReturn(services); diff --git a/src/test/java/fr/xephi/authme/task/purge/PurgeServiceTest.java b/src/test/java/fr/xephi/authme/task/purge/PurgeServiceTest.java index 8823f1aa17..ea00b48934 100644 --- a/src/test/java/fr/xephi/authme/task/purge/PurgeServiceTest.java +++ b/src/test/java/fr/xephi/authme/task/purge/PurgeServiceTest.java @@ -10,13 +10,13 @@ import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Calendar; @@ -26,12 +26,12 @@ import java.util.UUID; import static com.google.common.collect.Sets.newHashSet; +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.Matchers.greaterThan; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; @@ -45,8 +45,8 @@ /** * Test for {@link PurgeService}. */ -@RunWith(MockitoJUnitRunner.class) -public class PurgeServiceTest { +@ExtendWith(MockitoExtension.class) +class PurgeServiceTest { @InjectMocks private PurgeService purgeService; @@ -62,13 +62,13 @@ public class PurgeServiceTest { @Mock private PurgeExecutor executor; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldNotRunAutoPurge() { + void shouldNotRunAutoPurge() { // given given(settings.getProperty(PurgeSettings.USE_AUTO_PURGE)).willReturn(false); given(settings.getProperty(PurgeSettings.DAYS_BEFORE_REMOVE_PLAYER)).willReturn(60); @@ -81,7 +81,7 @@ public void shouldNotRunAutoPurge() { } @Test - public void shouldNotRunAutoPurgeForInvalidInterval() { + void shouldNotRunAutoPurgeForInvalidInterval() { // given given(settings.getProperty(PurgeSettings.USE_AUTO_PURGE)).willReturn(true); given(settings.getProperty(PurgeSettings.DAYS_BEFORE_REMOVE_PLAYER)).willReturn(0); @@ -94,7 +94,7 @@ public void shouldNotRunAutoPurgeForInvalidInterval() { } @Test - public void shouldRunAutoPurge() { + void shouldRunAutoPurge() { // given given(settings.getProperty(PurgeSettings.USE_AUTO_PURGE)).willReturn(true); given(settings.getProperty(PurgeSettings.DAYS_BEFORE_REMOVE_PLAYER)).willReturn(60); @@ -114,7 +114,7 @@ public void shouldRunAutoPurge() { } @Test - public void shouldRecognizeNoPlayersToPurge() { + void shouldRecognizeNoPlayersToPurge() { // given final long delay = 123012301L; given(dataSource.getRecordsToPurge(delay)).willReturn(Collections.emptySet()); @@ -131,7 +131,7 @@ public void shouldRecognizeNoPlayersToPurge() { } @Test - public void shouldRunPurge() { + void shouldRunPurge() { // given final long delay = 1809714L; Set playerNames = newHashSet("charlie", "delta", "echo", "foxtrot"); @@ -149,7 +149,7 @@ public void shouldRunPurge() { } @Test - public void shouldNotRunPurgeIfProcessIsAlreadyRunning() { + void shouldNotRunPurgeIfProcessIsAlreadyRunning() { // given purgeService.setPurging(true); CommandSender sender = mock(CommandSender.class); @@ -164,7 +164,7 @@ public void shouldNotRunPurgeIfProcessIsAlreadyRunning() { } @Test - public void shouldExecutePurgeActions() { + void shouldExecutePurgeActions() { // given List names = Arrays.asList("alpha", "bravo", "foxtrot"); List offlinePlayers = Arrays.asList( diff --git a/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java b/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java index 2ecf6a13a2..224dd99156 100644 --- a/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java +++ b/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java @@ -13,14 +13,13 @@ import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import java.util.ArrayList; @@ -32,10 +31,10 @@ import java.util.UUID; import static com.google.common.collect.Sets.newHashSet; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; -import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -50,8 +49,8 @@ /** * Test for {@link PurgeTask}. */ -@RunWith(MockitoJUnitRunner.class) -public class PurgeTaskTest { +@ExtendWith(MockitoExtension.class) +class PurgeTaskTest { private static final PermissionNode BYPASS_NODE = PlayerStatePermission.BYPASS_PURGE; @@ -69,13 +68,13 @@ public class PurgeTaskTest { @Captor private ArgumentCaptor> namesCaptor; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldRunTask() { + void shouldRunTask() { // given Set names = newHashSet("alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india"); @@ -113,6 +112,7 @@ public void shouldRunTask() { // given (3) // Third round: no more OfflinePlayer objects, but some names remain reset(purgeService, permissionsManager); + given(permissionsManager.hasPermissionOffline(anyString(), eq(BYPASS_NODE))).willReturn(false); given(permissionsManager.hasPermissionOffline("india", BYPASS_NODE)).willReturn(true); // when (3) @@ -129,7 +129,7 @@ public void shouldRunTask() { * #1008: OfflinePlayer#getName may return null. */ @Test - public void shouldHandleOfflinePlayerWithNullName() { + void shouldHandleOfflinePlayerWithNullName() { // given Set names = newHashSet("name1", "name2"); OfflinePlayer[] players = asArray( @@ -147,7 +147,7 @@ public void shouldHandleOfflinePlayerWithNullName() { } @Test - public void shouldStopTaskAndInformSenderUponCompletion() { + void shouldStopTaskAndInformSenderUponCompletion() { // given Set names = newHashSet("name1", "name2"); Player sender = mock(Player.class); @@ -176,7 +176,7 @@ public void shouldStopTaskAndInformSenderUponCompletion() { } @Test - public void shouldStopTaskAndInformConsoleUser() { + void shouldStopTaskAndInformConsoleUser() { // given Set names = newHashSet("name1", "name2"); PurgeTask task = new PurgeTask(purgeService, permissionsManager, null, names, new OfflinePlayer[0]); diff --git a/src/test/java/fr/xephi/authme/util/ExceptionUtilsTest.java b/src/test/java/fr/xephi/authme/util/ExceptionUtilsTest.java index b42fa97f7b..4cd54f1273 100644 --- a/src/test/java/fr/xephi/authme/util/ExceptionUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/ExceptionUtilsTest.java @@ -1,23 +1,23 @@ package fr.xephi.authme.util; import fr.xephi.authme.ReflectionTestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.MalformedURLException; import java.util.ConcurrentModificationException; +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.junit.Assert.assertThat; /** * Test for {@link ExceptionUtils}. */ -public class ExceptionUtilsTest { +class ExceptionUtilsTest { @Test - public void shouldFindWantedThrowable() { + void shouldFindWantedThrowable() { // given ConcurrentModificationException initialCme = new ConcurrentModificationException(); Throwable th = new Throwable(initialCme); @@ -38,7 +38,7 @@ public void shouldFindWantedThrowable() { } @Test - public void shouldHandleCircularCausesGracefully() { + void shouldHandleCircularCausesGracefully() { // given ExceptionWithSettableCause exceptionWithSettableCause = new ExceptionWithSettableCause(); UnsupportedOperationException uoe = new UnsupportedOperationException(exceptionWithSettableCause); @@ -55,7 +55,7 @@ public void shouldHandleCircularCausesGracefully() { } @Test - public void shouldFormatException() { + void shouldFormatException() { // given MalformedURLException ex = new MalformedURLException("Unrecognized URL format"); diff --git a/src/test/java/fr/xephi/authme/util/FileUtilsTest.java b/src/test/java/fr/xephi/authme/util/FileUtilsTest.java index 36af67242a..d8882b2e57 100644 --- a/src/test/java/fr/xephi/authme/util/FileUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/FileUtilsTest.java @@ -2,41 +2,39 @@ import com.google.common.io.Files; import fr.xephi.authme.TestHelper; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; /** * Test for {@link FileUtils}. */ -public class FileUtilsTest { +class FileUtilsTest { /** Regex that matches timestamps such as 20180211_1048. */ private static final String BACKUP_TIMESTAMP_PATTERN = "20\\d{6}_\\d{4}"; - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File temporaryFolder; @Test - public void shouldNotCopyFile() throws IOException { + void shouldNotCopyFile() throws IOException { // given - File folder = temporaryFolder.newFolder(); - File file = new File(folder, "config.yml"); + File file = new File(temporaryFolder, "config.yml"); // purposely don't copy config.yml to verify that config.yml isn't copied by the method File emailJarFile = TestHelper.getJarFile("/email.html"); Files.copy(emailJarFile, file); @@ -50,10 +48,9 @@ public void shouldNotCopyFile() throws IOException { } @Test - public void shouldCopyFileFromJar() throws IOException { + void shouldCopyFileFromJar() { // given - File folder = temporaryFolder.newFolder(); - File file = new File(folder, "some/folders/welcome.txt"); + File file = new File(temporaryFolder, "some/folders/welcome.txt"); // when boolean result = FileUtils.copyFileFromResource(file, "welcome.txt"); @@ -66,10 +63,9 @@ public void shouldCopyFileFromJar() throws IOException { } @Test - public void shouldReturnFalseForInvalidJarFile() throws IOException { + void shouldReturnFalseForInvalidJarFile() { // given - File folder = temporaryFolder.newFolder(); - File file = new File(folder, "bogus"); + File file = new File(temporaryFolder, "bogus"); // when boolean result = FileUtils.copyFileFromResource(file, "does-not-exist"); @@ -80,11 +76,10 @@ public void shouldReturnFalseForInvalidJarFile() throws IOException { } @Test - public void shouldReturnFalseForParentInvalidParentFolders() throws IOException { + void shouldReturnFalseForParentInvalidParentFolders() throws IOException { // given - File folder = temporaryFolder.newFolder(); - new File(folder, "hello").createNewFile(); - File fileToCreate = new File(folder, "hello/test"); + new File(temporaryFolder, "hello").createNewFile(); + File fileToCreate = new File(temporaryFolder, "hello/test"); // when boolean result = FileUtils.copyFileFromResource(fileToCreate, "welcome.txt"); @@ -94,30 +89,29 @@ public void shouldReturnFalseForParentInvalidParentFolders() throws IOException } @Test - public void shouldPurgeDirectory() throws IOException { + void shouldPurgeDirectory() throws IOException { // given - File root = temporaryFolder.newFolder(); - File file1 = new File(root, "a/b/c/test.html"); - File file2 = new File(root, "a/b/f/toast.txt"); - File file3 = new File(root, "a/g/rest.png"); - File file4 = new File(root, "j/l/roast.tiff"); + File file1 = new File(temporaryFolder, "a/b/c/test.html"); + File file2 = new File(temporaryFolder, "a/b/f/toast.txt"); + File file3 = new File(temporaryFolder, "a/g/rest.png"); + File file4 = new File(temporaryFolder, "j/l/roast.tiff"); createFiles(file1, file2, file3, file4); // when - FileUtils.purgeDirectory(new File(root, "a")); + FileUtils.purgeDirectory(new File(temporaryFolder, "a")); // then assertThat(file1.exists(), equalTo(false)); assertThat(file2.exists(), equalTo(false)); assertThat(file3.exists(), equalTo(false)); assertThat(file4.exists(), equalTo(true)); - assertThat(new File(root, "a").exists(), equalTo(true)); + assertThat(new File(temporaryFolder, "a").exists(), equalTo(true)); } @Test - public void shouldDeleteFile() throws IOException { + void shouldDeleteFile() throws IOException { // given - File file = temporaryFolder.newFile(); + File file = TestHelper.createFile(temporaryFolder, "tempFile"); assertThat(file.exists(), equalTo(true)); // when @@ -128,7 +122,7 @@ public void shouldDeleteFile() throws IOException { } @Test - public void shouldDoNothingForNullFile() { + void shouldDoNothingForNullFile() { // given File file = null; @@ -140,14 +134,14 @@ public void shouldDoNothingForNullFile() { } @Test - public void shouldGetResourceFromJar() { + void shouldGetResourceFromJar() { // given / when / then assertThat(FileUtils.getResourceFromJar("config.yml"), not(nullValue())); assertThat(FileUtils.getResourceFromJar("does-not-exist"), nullValue()); } @Test - public void shouldConstructPath() { + void shouldConstructPath() { // given/when String result = FileUtils.makePath("path", "to", "test-file.txt"); @@ -156,10 +150,9 @@ public void shouldConstructPath() { } @Test - public void shouldCreateDirectory() throws IOException { + void shouldCreateDirectory() { // given - File root = temporaryFolder.newFolder(); - File dir = new File(root, "folder/folder2/myFolder"); + File dir = new File(temporaryFolder, "folder/folder2/myFolder"); // when boolean result = FileUtils.createDirectory(dir); @@ -171,10 +164,9 @@ public void shouldCreateDirectory() throws IOException { } @Test - public void shouldReturnFalseOnDirectoryCreateFail() throws IOException { + void shouldReturnFalseOnDirectoryCreateFail() throws IOException { // given - File root = temporaryFolder.newFolder(); - File dirAsFile = new File(root, "file"); + File dirAsFile = new File(temporaryFolder, "file"); dirAsFile.createNewFile(); // when @@ -186,7 +178,7 @@ public void shouldReturnFalseOnDirectoryCreateFail() throws IOException { } @Test - public void shouldCreateCurrentTimestampString() { + void shouldCreateCurrentTimestampString() { // given / when String currentTimeString = FileUtils.createCurrentTimeString(); @@ -195,7 +187,7 @@ public void shouldCreateCurrentTimestampString() { } @Test - public void shouldCreateBackupFile() { + void shouldCreateBackupFile() { // given File file = new File("some/folders/config.yml"); @@ -215,5 +207,4 @@ private static void createFiles(File... files) throws IOException { } } } - } diff --git a/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java b/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java index 54bc7dcbaa..e290406868 100644 --- a/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java @@ -1,17 +1,17 @@ package fr.xephi.authme.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link InternetProtocolUtils} */ -public class InternetProtocolUtilsTest { +class InternetProtocolUtilsTest { @Test - public void shouldCheckLocalAddress() { + void shouldCheckLocalAddress() { // loopback assertThat(InternetProtocolUtils.isLocalAddress("localhost"), equalTo(true)); assertThat(InternetProtocolUtils.isLocalAddress("127.0.0.1"), equalTo(true)); @@ -43,7 +43,7 @@ public void shouldCheckLocalAddress() { } @Test - public void testIsLoopback() { + void shouldRecognizeLoopbackAddresses() { // loopback assertThat(InternetProtocolUtils.isLoopbackAddress("localhost"), equalTo(true)); assertThat(InternetProtocolUtils.isLoopbackAddress("127.0.0.1"), equalTo(true)); diff --git a/src/test/java/fr/xephi/authme/util/PlayerUtilsTest.java b/src/test/java/fr/xephi/authme/util/PlayerUtilsTest.java index 69d7b1f0de..a76b35b951 100644 --- a/src/test/java/fr/xephi/authme/util/PlayerUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/PlayerUtilsTest.java @@ -2,26 +2,26 @@ import fr.xephi.authme.TestHelper; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link PlayerUtils}. */ -public class PlayerUtilsTest { +class PlayerUtilsTest { - @BeforeClass - public static void setAuthmeInstance() { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldGetPlayerIp() { + void shouldGetPlayerIp() { // given Player player = mock(Player.class); String ip = "124.86.248.62"; @@ -35,7 +35,7 @@ public void shouldGetPlayerIp() { } @Test - public void shouldCheckIfIsNpc() { + void shouldCheckIfIsNpc() { // given Player player1 = mock(Player.class); given(player1.hasMetadata("NPC")).willReturn(false); diff --git a/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java b/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java index a89b4922da..20eacb697a 100644 --- a/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java @@ -1,19 +1,20 @@ package fr.xephi.authme.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.regex.Pattern; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Test for {@link RandomStringUtils}. */ -public class RandomStringUtilsTest { +class RandomStringUtilsTest { @Test - public void shouldGenerateRandomStrings() { + void shouldGenerateRandomStrings() { // given int[] lengths = {0, 1, 19, 142, 1872}; Pattern badChars = Pattern.compile(".*[^0-9a-z].*"); @@ -29,7 +30,7 @@ public void shouldGenerateRandomStrings() { } @Test - public void shouldGenerateRandomHexString() { + void shouldGenerateRandomHexString() { // given int[] lengths = {0, 1, 21, 160, 1784}; Pattern badChars = Pattern.compile(".*[^0-9a-f].*"); @@ -45,7 +46,7 @@ public void shouldGenerateRandomHexString() { } @Test - public void shouldGenerateRandomLowerUpperString() { + void shouldGenerateRandomLowerUpperString() { // given int[] lengths = {0, 1, 17, 143, 1808}; Pattern badChars = Pattern.compile(".*[^0-9a-zA-Z].*"); @@ -61,7 +62,7 @@ public void shouldGenerateRandomLowerUpperString() { } @Test - public void shouldGenerateRandomNumberString() { + void shouldGenerateRandomNumberString() { // given int[] lengths = {0, 1, 18, 147, 1833}; Pattern badChars = Pattern.compile(".*[^0-9].*"); @@ -76,11 +77,10 @@ public void shouldGenerateRandomNumberString() { } } - @Test(expected = IllegalArgumentException.class) - public void shouldThrowForInvalidLength() { - // given/when - RandomStringUtils.generate(-3); - - // then - throw exception + @Test + void shouldThrowForInvalidLength() { + // given / when / then + assertThrows(IllegalArgumentException.class, + () -> RandomStringUtils.generate(-3)); } } diff --git a/src/test/java/fr/xephi/authme/util/StringUtilsTest.java b/src/test/java/fr/xephi/authme/util/StringUtilsTest.java index fcd000d951..436bfc5454 100644 --- a/src/test/java/fr/xephi/authme/util/StringUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/StringUtilsTest.java @@ -1,21 +1,21 @@ package fr.xephi.authme.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for {@link StringUtils}. */ -public class StringUtilsTest { +class StringUtilsTest { @Test - public void shouldFindContainedItem() { + void shouldFindContainedItem() { // given String text = "This is a test of containsAny()"; String piece = "test"; @@ -28,7 +28,7 @@ public void shouldFindContainedItem() { } @Test - public void shouldReturnFalseIfNoneFound() { + void shouldReturnFalseIfNoneFound() { // given String text = "This is a test string"; @@ -40,7 +40,7 @@ public void shouldReturnFalseIfNoneFound() { } @Test - public void shouldReturnFalseForNullString() { + void shouldReturnFalseForNullString() { // given/when boolean result = StringUtils.containsAny(null, asList("some", "words", "to", "check")); @@ -49,7 +49,7 @@ public void shouldReturnFalseForNullString() { } @Test - public void shouldCheckIfIsBlankString() { + void shouldCheckIfIsBlankString() { // Should be true for null/empty/whitespace assertTrue(StringUtils.isBlank(null)); assertTrue(StringUtils.isBlank("")); @@ -61,7 +61,7 @@ public void shouldCheckIfIsBlankString() { } @Test - public void shouldGetDifferenceWithNullString() { + void shouldGetDifferenceWithNullString() { // given/when/then assertThat(StringUtils.getDifference(null, "test"), equalTo(1.0)); assertThat(StringUtils.getDifference("test", null), equalTo(1.0)); @@ -69,7 +69,7 @@ public void shouldGetDifferenceWithNullString() { } @Test - public void shouldGetDifferenceBetweenTwoString() { + void shouldGetDifferenceBetweenTwoString() { // given/when/then assertThat(StringUtils.getDifference("test", "taste"), equalTo(0.4)); assertThat(StringUtils.getDifference("test", "bear"), equalTo(0.75)); @@ -77,7 +77,7 @@ public void shouldGetDifferenceBetweenTwoString() { } @Test - public void shouldCheckIfHasNeedleInWord() { + void shouldCheckIfHasNeedleInWord() { // given/when/then assertThat(StringUtils.isInsideString('@', "@hello"), equalTo(false)); assertThat(StringUtils.isInsideString('?', "absent"), equalTo(false)); diff --git a/src/test/java/fr/xephi/authme/util/UtilsTest.java b/src/test/java/fr/xephi/authme/util/UtilsTest.java index 37d52163d9..83a6a95f78 100644 --- a/src/test/java/fr/xephi/authme/util/UtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/UtilsTest.java @@ -5,8 +5,8 @@ import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collection; @@ -15,8 +15,8 @@ import java.util.logging.Logger; import java.util.regex.Pattern; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -24,15 +24,15 @@ /** * Test for {@link Utils}. */ -public class UtilsTest { +class UtilsTest { - @BeforeClass - public static void initLogger() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldCompilePattern() { + void shouldCompilePattern() { // given String pattern = "gr(a|e)ys?"; @@ -44,7 +44,7 @@ public void shouldCompilePattern() { } @Test - public void shouldDefaultToAllAllowedPattern() { + void shouldDefaultToAllAllowedPattern() { // given String invalidPattern = "gr(a|eys?"; // missing closing ')' @@ -56,7 +56,7 @@ public void shouldDefaultToAllAllowedPattern() { } @Test - public void shouldLogAndSendMessage() { + void shouldLogAndSendMessage() { // given Logger logger = TestHelper.setupLogger(); Player player = mock(Player.class); @@ -71,7 +71,7 @@ public void shouldLogAndSendMessage() { } @Test - public void shouldHandleNullAsCommandSender() { + void shouldHandleNullAsCommandSender() { // given Logger logger = TestHelper.setupLogger(); String message = "Test test, test."; @@ -84,7 +84,7 @@ public void shouldHandleNullAsCommandSender() { } @Test - public void shouldNotSendToCommandSenderTwice() { + void shouldNotSendToCommandSenderTwice() { // given Logger logger = TestHelper.setupLogger(); CommandSender sender = mock(ConsoleCommandSender.class); @@ -99,7 +99,7 @@ public void shouldNotSendToCommandSenderTwice() { } @Test - public void shouldCheckIfCollectionIsEmpty() { + void shouldCheckIfCollectionIsEmpty() { // given List emptyList = Collections.emptyList(); Collection nonEmptyColl = Arrays.asList(3, 4, 5); @@ -111,7 +111,7 @@ public void shouldCheckIfCollectionIsEmpty() { } @Test - public void shouldLogAndSendWarning() { + void shouldLogAndSendWarning() { // given Logger logger = TestHelper.setupLogger(); String message = "Error while performing action"; @@ -126,7 +126,7 @@ public void shouldLogAndSendWarning() { } @Test - public void shouldLogWarningAndNotSendToConsoleSender() { + void shouldLogWarningAndNotSendToConsoleSender() { // given Logger logger = TestHelper.setupLogger(); String message = "Error while performing action"; @@ -141,7 +141,7 @@ public void shouldLogWarningAndNotSendToConsoleSender() { } @Test - public void shouldLogWarningAndHandleNullCommandSender() { + void shouldLogWarningAndHandleNullCommandSender() { // given Logger logger = TestHelper.setupLogger(); String message = "Error while performing action"; @@ -155,14 +155,14 @@ public void shouldLogWarningAndHandleNullCommandSender() { } @Test - public void shouldCheckIfClassIsLoaded() { + void shouldCheckIfClassIsLoaded() { // given / when / then assertThat(Utils.isClassLoaded("org.bukkit.event.player.PlayerFishEvent"), equalTo(true)); assertThat(Utils.isClassLoaded("com.someclass.doesnot.exist"), equalTo(false)); } @Test - public void shouldDetectIfEmailIsEmpty() { + void shouldDetectIfEmailIsEmpty() { // given / when / then assertThat(Utils.isEmailEmpty(""), equalTo(true)); assertThat(Utils.isEmailEmpty(null), equalTo(true)); diff --git a/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java b/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java index b98bdba994..1040358bcc 100644 --- a/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java @@ -1,20 +1,20 @@ package fr.xephi.authme.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.UUID; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; /** * Test for {@link UuidUtils}. */ -public class UuidUtilsTest { +class UuidUtilsTest { @Test - public void shouldParseUuidSafely() { + void shouldParseUuidSafely() { // given UUID correctUuid = UUID.fromString("8e0a9aaa-5eda-42ef-8daf-e6c6359f607e"); diff --git a/src/test/java/fr/xephi/authme/util/expiring/DurationTest.java b/src/test/java/fr/xephi/authme/util/expiring/DurationTest.java index 03a0f9d471..29c8970d0d 100644 --- a/src/test/java/fr/xephi/authme/util/expiring/DurationTest.java +++ b/src/test/java/fr/xephi/authme/util/expiring/DurationTest.java @@ -1,19 +1,19 @@ package fr.xephi.authme.util.expiring; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link Duration}. */ -public class DurationTest { +class DurationTest { @Test - public void shouldConvertToAppropriateTimeUnit() { + void shouldConvertToAppropriateTimeUnit() { check(Duration.createWithSuitableUnit(0, TimeUnit.HOURS), 0, TimeUnit.SECONDS); diff --git a/src/test/java/fr/xephi/authme/util/expiring/ExpiringMapTest.java b/src/test/java/fr/xephi/authme/util/expiring/ExpiringMapTest.java index ac9a5a7194..2e37c30b6c 100644 --- a/src/test/java/fr/xephi/authme/util/expiring/ExpiringMapTest.java +++ b/src/test/java/fr/xephi/authme/util/expiring/ExpiringMapTest.java @@ -1,22 +1,22 @@ package fr.xephi.authme.util.expiring; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Map; import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; /** * Test for {@link ExpiringMap}. */ -public class ExpiringMapTest { +class ExpiringMapTest { @Test - public void shouldAddAndRetrieveEntries() { + void shouldAddAndRetrieveEntries() { // given ExpiringMap map = new ExpiringMap<>(3, TimeUnit.MINUTES); @@ -29,7 +29,7 @@ public void shouldAddAndRetrieveEntries() { } @Test - public void shouldRemoveEntry() { + void shouldRemoveEntry() { // given ExpiringMap map = new ExpiringMap<>(1, TimeUnit.HOURS); map.put("hi", true); @@ -44,7 +44,7 @@ public void shouldRemoveEntry() { } @Test - public void shouldUpdateExpirationAndSupportNegativeValues() { + void shouldUpdateExpirationAndSupportNegativeValues() { // given ExpiringMap map = new ExpiringMap<>(2, TimeUnit.DAYS); map.put(2, 4); @@ -61,7 +61,7 @@ public void shouldUpdateExpirationAndSupportNegativeValues() { } @Test - public void shouldCleanUpExpiredEntries() throws InterruptedException { + void shouldCleanUpExpiredEntries() throws InterruptedException { // given ExpiringMap map = new ExpiringMap<>(200, TimeUnit.MILLISECONDS); map.put(144, 12); @@ -81,7 +81,7 @@ public void shouldCleanUpExpiredEntries() throws InterruptedException { } @Test - public void shouldReturnIfIsEmpty() { + void shouldReturnIfIsEmpty() { // given ExpiringMap map = new ExpiringMap<>(-8, TimeUnit.SECONDS); diff --git a/src/test/java/fr/xephi/authme/util/expiring/ExpiringSetTest.java b/src/test/java/fr/xephi/authme/util/expiring/ExpiringSetTest.java index 42180ab26d..7a877b6a7b 100644 --- a/src/test/java/fr/xephi/authme/util/expiring/ExpiringSetTest.java +++ b/src/test/java/fr/xephi/authme/util/expiring/ExpiringSetTest.java @@ -1,19 +1,19 @@ package fr.xephi.authme.util.expiring; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link ExpiringSet}. */ -public class ExpiringSetTest { +class ExpiringSetTest { @Test - public void shouldAddEntry() { + void shouldAddEntry() { // given ExpiringSet set = new ExpiringSet<>(10, TimeUnit.MINUTES); @@ -26,7 +26,7 @@ public void shouldAddEntry() { } @Test - public void shouldRemoveEntries() { + void shouldRemoveEntries() { // given ExpiringSet set = new ExpiringSet<>(20, TimeUnit.SECONDS); set.add(20); @@ -43,7 +43,7 @@ public void shouldRemoveEntries() { } @Test - public void shouldHandleNewExpirationAndSupportNegativeValues() { + void shouldHandleNewExpirationAndSupportNegativeValues() { // given ExpiringSet set = new ExpiringSet<>(800, TimeUnit.MILLISECONDS); set.add('A'); @@ -58,7 +58,7 @@ public void shouldHandleNewExpirationAndSupportNegativeValues() { } @Test - public void shouldClearAllValues() { + void shouldClearAllValues() { // given ExpiringSet set = new ExpiringSet<>(1, TimeUnit.MINUTES); set.add("test"); @@ -71,7 +71,7 @@ public void shouldClearAllValues() { } @Test - public void shouldClearExpiredValues() { + void shouldClearExpiredValues() { // given ExpiringSet set = new ExpiringSet<>(2, TimeUnit.HOURS); set.add(2); @@ -90,7 +90,7 @@ public void shouldClearExpiredValues() { } @Test - public void shouldReturnExpiration() { + void shouldReturnExpiration() { // given ExpiringSet set = new ExpiringSet<>(123, TimeUnit.MINUTES); set.add("my entry"); @@ -105,7 +105,7 @@ public void shouldReturnExpiration() { } @Test - public void shouldReturnExpirationInSuitableUnits() { + void shouldReturnExpirationInSuitableUnits() { // given ExpiringSet set = new ExpiringSet<>(601, TimeUnit.SECONDS); set.add(12); @@ -124,7 +124,7 @@ public void shouldReturnExpirationInSuitableUnits() { } @Test - public void shouldReturnMinusOneForExpiredEntry() { + void shouldReturnMinusOneForExpiredEntry() { // given ExpiringSet set = new ExpiringSet<>(-100, TimeUnit.SECONDS); set.add(23); diff --git a/src/test/java/fr/xephi/authme/util/expiring/TimedCounterTest.java b/src/test/java/fr/xephi/authme/util/expiring/TimedCounterTest.java index c2b65eed31..7119bbdfc7 100644 --- a/src/test/java/fr/xephi/authme/util/expiring/TimedCounterTest.java +++ b/src/test/java/fr/xephi/authme/util/expiring/TimedCounterTest.java @@ -1,19 +1,19 @@ package fr.xephi.authme.util.expiring; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link TimedCounter}. */ -public class TimedCounterTest { +class TimedCounterTest { @Test - public void shouldReturnZeroForAnyKey() { + void shouldReturnZeroForAnyKey() { // given TimedCounter counter = new TimedCounter<>(1, TimeUnit.DAYS); @@ -23,7 +23,7 @@ public void shouldReturnZeroForAnyKey() { } @Test - public void shouldIncrementCount() { + void shouldIncrementCount() { // given TimedCounter counter = new TimedCounter<>(10, TimeUnit.MINUTES); counter.put("moto", 12); @@ -38,7 +38,7 @@ public void shouldIncrementCount() { } @Test - public void shouldDecrementCount() { + void shouldDecrementCount() { // given TimedCounter counter = new TimedCounter<>(10, TimeUnit.MINUTES); counter.put("moto", 12); @@ -53,7 +53,7 @@ public void shouldDecrementCount() { } @Test - public void shouldSumUpEntries() { + void shouldSumUpEntries() { // given TimedCounter counter = new TimedCounter<>(90, TimeUnit.SECONDS); counter.getEntries().put("expired", new ExpiringMap.ExpiringEntry<>(800, 0)); diff --git a/src/test/java/fr/xephi/authme/util/lazytags/TagBuilderTest.java b/src/test/java/fr/xephi/authme/util/lazytags/TagBuilderTest.java index 53362b5ff6..afa33b183f 100644 --- a/src/test/java/fr/xephi/authme/util/lazytags/TagBuilderTest.java +++ b/src/test/java/fr/xephi/authme/util/lazytags/TagBuilderTest.java @@ -1,21 +1,21 @@ package fr.xephi.authme.util.lazytags; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.function.Function; import java.util.function.Supplier; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; /** * Test for {@link TagBuilder}. */ -public class TagBuilderTest { +class TagBuilderTest { @Test - public void shouldCreateNoArgsTag() { + void shouldCreateNoArgsTag() { // given Supplier supplier = () -> "hello"; @@ -28,7 +28,7 @@ public void shouldCreateNoArgsTag() { } @Test - public void shouldCreateDependentTag() { + void shouldCreateDependentTag() { // given Function function = d -> Double.toString(d + d/10); diff --git a/src/test/java/fr/xephi/authme/util/lazytags/TagReplacerTest.java b/src/test/java/fr/xephi/authme/util/lazytags/TagReplacerTest.java index 8c9a8187f0..1b325f12e4 100644 --- a/src/test/java/fr/xephi/authme/util/lazytags/TagReplacerTest.java +++ b/src/test/java/fr/xephi/authme/util/lazytags/TagReplacerTest.java @@ -1,22 +1,22 @@ package fr.xephi.authme.util.lazytags; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static fr.xephi.authme.util.lazytags.TagBuilder.createTag; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; /** * Test for {@link TagReplacer}. */ -public class TagReplacerTest { +class TagReplacerTest { @Test - public void shouldReplaceTags() { + void shouldReplaceTags() { // given TestTagService tagService = new TestTagService(); List> tags = tagService.getAvailableTags(); @@ -35,7 +35,7 @@ public void shouldReplaceTags() { } @Test - public void shouldNotCallUnusedTags() { + void shouldNotCallUnusedTags() { // given TestTagService tagService = new TestTagService(); List> tags = tagService.getAvailableTags(); diff --git a/src/test/java/fr/xephi/authme/util/lazytags/WrappedTagReplacerTest.java b/src/test/java/fr/xephi/authme/util/lazytags/WrappedTagReplacerTest.java index 1991505456..e7ef379057 100644 --- a/src/test/java/fr/xephi/authme/util/lazytags/WrappedTagReplacerTest.java +++ b/src/test/java/fr/xephi/authme/util/lazytags/WrappedTagReplacerTest.java @@ -4,22 +4,22 @@ import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; 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.junit.Assert.assertThat; /** * Test for {@link WrappedTagReplacer}. */ -public class WrappedTagReplacerTest { +class WrappedTagReplacerTest { @Test - public void shouldApplyTags() { + void shouldApplyTags() { // given TestTagService tagService = new TestTagService(); List> tags = tagService.getAvailableTags();