Merge branch 'master' into JAVA-3533

This commit is contained in:
Loredana Crusoveanu
2020-12-30 15:48:46 +02:00
committed by GitHub
169 changed files with 613 additions and 221 deletions
@@ -64,7 +64,7 @@ public class HttpClientUnitTest {
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
assertThat(response.body(), containsString("https://stackoverflow.com/"));
assertTrue(response.headers().map().get("location").stream().anyMatch("https://stackoverflow.com/"::equals));
}
@Test
@@ -18,6 +18,7 @@ import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
public class HttpRequestUnitTest {
@@ -48,7 +49,12 @@ public class HttpRequestUnitTest {
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
}
@Test
/*
* This test will fail as soon as the given URL returns a HTTP 2 response.
* Therefore, let's leave it commented out.
* */
@Test
@Disabled
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
+2
View File
@@ -44,6 +44,8 @@
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>
@@ -2,8 +2,7 @@ package com.baeldung.java9.modules;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.*;
@@ -74,7 +73,6 @@ public class ModuleAPIUnitTest {
ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer();
assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent());
assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78));
assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty());
}
@@ -108,8 +106,7 @@ public class ModuleAPIUnitTest {
.collect(Collectors.toSet());
assertThat(javaBaseRequires, empty());
assertThat(javaSqlRequires.size(), is(3));
assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging"));
assertThat(javaSqlRequiresNames, hasItems("java.base", "java.xml", "java.logging"));
}
@Test
@@ -127,16 +124,13 @@ public class ModuleAPIUnitTest {
@Test
public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() {
Set<Exports> javaBaseExports = javaBaseModule.getDescriptor().exports();
Set<Exports> javaSqlExports = javaSqlModule.getDescriptor().exports();
Set<String> javaSqlExportsSource = javaSqlExports.stream()
.map(Exports::source)
.collect(Collectors.toSet());
assertThat(javaBaseExports.size(), is(108));
assertThat(javaSqlExports.size(), is(3));
assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql"));
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
}
@Test
@@ -144,7 +138,6 @@ public class ModuleAPIUnitTest {
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
assertThat(javaBaseUses.size(), is(34));
assertThat(javaSqlUses, contains("java.sql.Driver"));
}
@@ -3,35 +3,36 @@ package com.baeldung.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
public class CharacterGeneralCategoryTypeUnitTest {
@Test
public void givenACharacter_whenUpperCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('U') == Character.UPPERCASE_LETTER);
assertEquals(Character.UPPERCASE_LETTER, Character.getType('U'));
}
@Test
public void givenACharacter_whenLowerCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('u') == Character.LOWERCASE_LETTER);
assertEquals(Character.LOWERCASE_LETTER, Character.getType('u'));
}
@Test
public void givenACharacter_whenTitleCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('\u01f2') == Character.TITLECASE_LETTER);
assertEquals(Character.TITLECASE_LETTER, Character.getType('\u01f2'));
}
@Test
public void givenACharacter_whenModifierLetter_thenAssertTrue() {
assertTrue(Character.getType('\u02b0') == Character.MODIFIER_LETTER);
assertEquals(Character.MODIFIER_LETTER, Character.getType('\u02b0'));
}
@Test
public void givenACharacter_whenOtherLetter_thenAssertTrue() {
assertTrue(Character.getType('\u05d0') == Character.OTHER_LETTER);
assertEquals(Character.OTHER_LETTER, Character.getType('\u05d0'));
}
@Test
public void givenACharacter_whenLetterNumber_thenAssertTrue() {
assertTrue(Character.getType('\u2164') == Character.LETTER_NUMBER);
assertEquals(Character.LETTER_NUMBER, Character.getType('\u2164'));
}
}
@@ -6,6 +6,27 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class IsLetterOrAlphabetUnitTest {
@Test
public void givenACharacter_whenUpperCaseLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('A'));
}
@Test
public void givenACharacter_whenTitleCaseLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('\u01f2'));
}
@Test
public void givenACharacter_whenLowerCaseLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isAlphabetic('a'));
}
@Test
public void givenACharacter_whenModifierLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isAlphabetic('\u02b0'));
}
@Test
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isLetter('a'));
@@ -6,6 +6,7 @@ import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;
import static org.assertj.core.api.Assertions.assertThat;
@@ -21,9 +22,12 @@ public class ConvertInstantToTimestampUnitTest {
instant = timestamp.toInstant();
assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime());
DateFormat df = DateFormat.getDateTimeInstance();
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter = formatter.withZone(TimeZone.getTimeZone("UTC").toZoneId());
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
assertThat(instant.toString()).isEqualTo(df.format(timestamp).toString());
assertThat(formatter.format(instant)).isEqualTo(df.format(timestamp));
}
}
@@ -58,7 +58,8 @@ public class StringToDateUnitTest {
LocalDateTime localDateTime = LocalDateTime.of(2015, 05, 05, 10, 15, 30);
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Paris"));
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05T10:15:30+01:00[Europe/Paris]");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05 10:15:30 Europe/Paris", formatter);
assertThat(zonedDateTime).isEqualTo(expectedZonedDateTime);
}
@@ -38,14 +38,16 @@ public class DateTimeFormatterUnitTest {
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
DateTimeFormatter frLocalizedFormatter =
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy z", Locale.US);
DateTimeFormatter frLocalizedFormatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy z", Locale.FRANCE);
String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
System.out.println(formattedDateTime);
System.out.println(frFormattedDateTime);
Assert.assertEquals("Monday, January 01, 2018 PST", formattedDateTime);
Assert.assertEquals("lundi, janvier 01, 2018 PST", frFormattedDateTime);
}
@Test
@@ -105,14 +107,15 @@ public class DateTimeFormatterUnitTest {
Assert.assertEquals("8/23/16", DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay));
}
@Test
public void shouldPrintStyledDateTime() {
LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45);
Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
}
// Note: The exact output format using the different FormatStyle constants differs by JVM/Java version
// @Test
// public void shouldPrintStyledDateTime() {
// LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45);
// Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
// Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
// Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
// Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
// }
@Test
public void shouldPrintFormattedDateTimeWithPredefined() {
@@ -126,11 +129,12 @@ public class DateTimeFormatterUnitTest {
Assert.assertEquals(LocalDate.of(2018, 3, 12), LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3));
}
@Test
public void shouldParseFormatStyleFull() {
ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET"));
Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9));
}
// Note: The exact output format using the different FormatStyle constants differs by JVM/Java version
// @Test
// public void shouldParseFormatStyleFull() {
// ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET"));
// Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9));
// }
@Test
public void shouldParseDateWithCustomFormatter() {
@@ -24,9 +24,20 @@ public class ListFiles {
.collect(Collectors.toSet());
}
public Set<String> listFilesUsingFilesList(String dir) throws IOException {
try (Stream<Path> stream = Files.list(Paths.get(dir))) {
return stream
.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
}
}
public Set<String> listFilesUsingFileWalk(String dir, int depth) throws IOException {
try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) {
return stream.filter(file -> !Files.isDirectory(file))
return stream
.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
@@ -25,10 +25,15 @@ public class ListFilesUnitTest {
};
@Test
public void givenDir_whenUsingJAVAIO_thenListAllFiles() throws IOException {
public void givenDir_whenUsingJAVAIO_thenListAllFiles() {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingJavaIO(DIRECTORY));
}
@Test
public void givenDir_whenUsingFilesList_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFilesList(DIRECTORY));
}
@Test
public void givenDir_whenWalkingTree_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalk(DIRECTORY,DEPTH));
@@ -25,7 +25,7 @@ public class ProcessAPIEnhancementsUnitTest {
ProcessHandle processHandle = ProcessHandle.current();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.pid());
assertEquals(false, processInfo.arguments()
assertEquals(true, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
@@ -52,7 +52,7 @@ public class ProcessAPIEnhancementsUnitTest {
ProcessHandle processHandle = process.toHandle();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.pid());
assertEquals(false, processInfo.arguments()
assertEquals(true, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
@@ -61,7 +61,7 @@ public class ProcessAPIEnhancementsUnitTest {
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(true, processInfo.totalCpuDuration()
assertEquals(false, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
@@ -73,15 +73,9 @@ public class ProcessAPIEnhancementsUnitTest {
liveProcesses.filter(ProcessHandle::isAlive)
.forEach(ph -> {
assertNotNull(ph.pid());
assertEquals(true, ph.info()
.command()
.isPresent());
assertEquals(true, ph.info()
.startInstant()
.isPresent());
assertEquals(true, ph.info()
.totalCpuDuration()
.isPresent());
assertEquals(true, ph.info()
.user()
.isPresent());
@@ -16,28 +16,6 @@ import org.junit.jupiter.api.Test;
class ProcessUnderstandingUnitTest {
@Test
public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
int value = Integer.parseInt(output.readLine());
assertEquals(3, value);
}
@Test
public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
int value = Integer.parseInt(output.readLine());
assertEquals(3, value);
}
@Test
public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
Process process = Runtime.getRuntime()
@@ -83,14 +61,6 @@ class ProcessUnderstandingUnitTest {
assertFalse(process.isAlive());
}
@Test
public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
ProcessHandle processHandle = optionalProcessHandle.get();
processHandle.destroy();
assertFalse(processHandle.isAlive());
}
//@Test - windows specific
public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
@@ -40,7 +40,7 @@ public class ProcessBuilderUnitTest {
List<String> results = readOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")));
assertThat("Results should contain java version: ", results, hasItem(containsString("version")));
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
@@ -101,7 +101,7 @@ public class ProcessBuilderUnitTest {
.collect(Collectors.toList());
assertThat("Results should not be empty", lines, is(not(empty())));
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
assertThat("Results should contain java version: ", lines, hasItem(containsString("version")));
}
@Test
@@ -124,7 +124,7 @@ public class ProcessBuilderUnitTest {
.collect(Collectors.toList());
assertThat("Results should not be empty", lines, is(not(empty())));
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
assertThat("Results should contain java version: ", lines, hasItem(containsString("version")));
}
@Test
@@ -1,3 +1,5 @@
package com.baeldung.screenshot;
import javax.imageio.ImageIO;
import java.awt.Component;
import java.awt.GraphicsDevice;
@@ -8,6 +10,7 @@ import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import static org.junit.Assert.assertTrue;
@@ -38,7 +41,9 @@ public class ScreenshotUnitTest {
assertTrue(imageFile.exists());
}
// This methods needs a component as a parameter and can only be run from an application with a GUI
@Test
@Disabled
public void givenComponent_whenTakeScreenshot_thenSaveToFile(Component component) throws Exception {
Rectangle componentRect = component.getBounds();
BufferedImage bufferedImage = new BufferedImage(componentRect.width, componentRect.height, BufferedImage.TYPE_INT_ARGB);
@@ -92,10 +92,11 @@
<!-- util -->
<commons-math3.version>3.6.1</commons-math3.version>
<joda.version>2.10</joda.version>
<lombok.version>1.18.12</lombok.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
<powermock.version>2.0.0</powermock.version>
<powermock.version>2.0.7</powermock.version>
<jmockit.version>1.44</jmockit.version>
<!-- plugins -->
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.Test;
public class ElapsedTimeUnitTest {
public class ElapsedTimeManualTest {
@Test
public void givenRunningTask_whenMeasuringTimeWithCurrentTimeMillis_thenGetElapsedTime() throws InterruptedException {
@@ -50,17 +50,25 @@ public class ElapsedTimeUnitTest {
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
}
/*
The below test depends on the elapsed time, which isn't ideal in a test.
Also, it slows down test execution artificially.
*/
@Test
public void givenRunningTask_whenMeasuringTimeWithInstantClass_thenGetElapsedTime() throws InterruptedException {
Instant start = Instant.now();
System.out.println("start: " + start);
simulateRunningTask();
Instant finish = Instant.now();
System.out.println("start: " + start);
System.out.println("finish: " + finish);
long timeElapsed = Duration.between(start, finish).toMillis();
System.out.println("elapsed: " + timeElapsed);
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
}
@@ -10,8 +10,8 @@ import java.time.Instant;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Instant.class })
@@ -21,12 +21,8 @@ public class LocalDateTimeUnitTest {
@Test
public void givenLocalDateTimeMock_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-22T10:15:30.00Z"), ZoneId.of("UTC"));
LocalDateTime dateTime = LocalDateTime.now(clock);
mockStatic(LocalDateTime.class);
when(LocalDateTime.now()).thenReturn(dateTime);
String dateTimeExpected = "2014-12-22T10:15:30";
LocalDateTime now = LocalDateTime.now();
LocalDateTime now = LocalDateTime.now(clock);
assertThat(now).isEqualTo(dateTimeExpected);
}
+2 -1
View File
@@ -21,7 +21,7 @@
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring-boot.version}</version>
<version>${spring-security-oauth2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
@@ -88,6 +88,7 @@
<bouncycastle.version>1.58</bouncycastle.version>
<jsch.version>0.1.55</jsch.version>
<apache-mina.version>2.5.1</apache-mina.version>
<spring-security-oauth2.version>2.4.0.RELEASE</spring-security-oauth2.version>
</properties>
</project>
+3 -1
View File
@@ -82,8 +82,10 @@
<rest-assured.version>3.3.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.22.RELEASE</thin.version>
<spring-boot.version>2.3.3.RELEASE</spring-boot.version>
<spring-boot.version>2.4.0</spring-boot.version>
<aspectjweaver.version>1.9.1</aspectjweaver.version>
<!-- this property can be removed once we update Mockito version in the main pom.xml -->
<mockito.version>3.4.0</mockito.version>
</properties>
</project>
@@ -10,15 +10,15 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.redis.configuration.entity.Book;
import com.baeldung.spring.redis.configuration.repository.BooksRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class BooksControllerUnitTest {
@Spy
@InjectMocks
private BooksController booksController;
@@ -11,16 +11,16 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.redis.configuration.entity.Book;
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class BooksRepositoryUnitTest {
@Spy
@InjectMocks
private BooksRepository booksRepository;
@@ -1,13 +1,13 @@
package com.baeldung.spring.data.jpa.query.datetime;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
package com.baeldung.spring.data.jpa.query;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QueryApplication {
public static void main(String[] args) {
SpringApplication.run(QueryApplication.class, args);
}
}
@@ -0,0 +1,8 @@
insert into Users(id, name, creation_date, last_login_date, active, age, email, status)
values(1, 'John', TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('01/01/2020', 'DD/MM/YYYY'), 1, 23, '[email protected]', 1);
insert into Users(id, name, creation_date, last_login_date, active, age, email, status)
values(2, 'Bob', TO_DATE('02/02/2019', 'DD/MM/YYYY'), TO_DATE('02/02/2020', 'DD/MM/YYYY'), 1, 56, '[email protected]', 1);
insert into Users(id, name, creation_date, last_login_date, active, age, email, status)
values(3, 'Cindy', TO_DATE('02/02/2019', 'DD/MM/YYYY'), TO_DATE('02/02/2020', 'DD/MM/YYYY'), 1, 18, '[email protected]', 0);
@@ -0,0 +1,162 @@
package com.baeldung.spring.data.jpa.query;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(SpringRunner.class)
@DataJpaTest(properties = "spring.datasource.data=classpath:insert_users.sql")
public class UserRepositoryIntegrationTest {
@Autowired
private UserRepository userRepository;
@Test
public void whenFindAllActiveUsersThenAllActiveFound() {
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers).hasSize(2);
}
@Test
public void whenFindAllActiveUsersNativeThenAllActiveFound() {
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers).hasSize(2);
}
@Test
public void whenFindAllSortedByNameThenAllSorted() {
List<User> allUsersSortedByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name"));
assertThat(allUsersSortedByName)
.extracting("name")
.containsSequence("Bob", "Cindy", "John");
}
@Test
public void whenFindAllSortedByNameLengthThenException() {
assertThatThrownBy(() -> userRepository.findAll(Sort.by("LENGTH(name)")))
.isInstanceOf(PropertyReferenceException.class);
}
@Test
public void whenFindAllUsersSortedByNameThenAllSorted() {
List<User> allUsersSortedByName = userRepository.findAllUsers(Sort.by(Sort.Direction.ASC, "name"));
assertThat(allUsersSortedByName)
.extracting("name")
.containsSequence("Bob", "Cindy", "John");
}
@Test
public void whenFindAllUsersSortedByNameLengthThenAllSorted() {
List<User> allUsersSortedByName = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(allUsersSortedByName)
.extracting("name")
.containsSequence("Bob", "John", "Cindy");
}
@Test
public void whenFindAllUsersWithPaginationThenPaginated() {
Page<User> page = userRepository.findAllUsersWithPagination(PageRequest.of(0, 1));
assertThat(page.stream().map(User::getId))
.hasSize(1)
.containsOnly(1);
}
@Test
public void whenFindAllUsersWithPaginationNativeThenPaginated() {
Page<User> page = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 1));
assertThat(page.stream().map(User::getId))
.hasSize(1)
.containsOnly(2);
}
@Test
public void whenFindUserByStatusThenFound() {
User user = userRepository.findUserByStatus(0);
assertThat(user.getStatus()).isZero();
}
@Test
public void whenFindUserByStatusAndNameThenFound() {
User user = userRepository.findUserByStatusAndName(1, "John");
assertThat(user.getStatus()).isOne();
assertThat(user.getName()).isEqualTo("John");
}
@Test
public void whenFindUserByStatusNativeThenFound() {
User user = userRepository.findUserByStatusNative(0);
assertThat(user.getStatus()).isZero();
}
@Test
public void whenFindUserByStatusAndNameNamedParamsThenFound() {
User user = userRepository.findUserByStatusAndNameNamedParams(1, "John");
assertThat(user.getStatus()).isOne();
assertThat(user.getName()).isEqualTo("John");
}
@Test
public void whenFindUserByUserStatusAndUserNameThenFound() {
User user = userRepository.findUserByUserStatusAndUserName(1, "John");
assertThat(user.getStatus()).isOne();
assertThat(user.getName()).isEqualTo("John");
}
@Test
public void whenFindUserByStatusAndNameNamedParamsNativeThenFound() {
User user = userRepository.findUserByStatusAndNameNamedParamsNative(1, "Bob");
assertThat(user.getStatus()).isOne();
assertThat(user.getName()).isEqualTo("Bob");
}
@Test
public void whenFindUserByNameListThenAllFound() {
List<User> users = userRepository.findUserByNameList(Arrays.asList("Bob", "Cindy"));
assertThat(users)
.extracting("name")
.containsOnly("Bob", "Cindy");
}
@Test
public void whenUpdateUserSetStatusForNameThenUpdated() {
int updated = userRepository.updateUserSetStatusForName(0, "John");
assertThat(updated).isOne();
User john = userRepository.findUserByStatusAndName(0, "John");
assertThat(john).isNotNull();
}
@Test
public void whenUpdateUserSetStatusForNameNativeThenUpdated() {
int updated = userRepository.updateUserSetStatusForNameNative(0, "John");
assertThat(updated).isOne();
User john = userRepository.findUserByStatusAndName(0, "John");
assertThat(john).isNotNull();
}
@Test
public void whenInsertUserThenInserted() {
User beforeInsert = userRepository.findUserByStatusAndName(0, "Mandy");
assertThat(beforeInsert).isNull();
userRepository.insertUser("Mandy", 20, "[email protected]", 0, true);
User afterInsert = userRepository.findUserByStatusAndName(0, "Mandy");
assertThat(afterInsert).isNotNull();
}
}
+23 -33
View File
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress PyInterpreter -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
@@ -663,8 +664,6 @@
<module>spring-mvc-java-2</module>
<module>spring-mvc-velocity</module>
<module>spring-mvc-views</module>
<module>spring-mvc-webflow</module>
<module>spring-mvc-xml</module>
<module>spring-protobuf</module>
@@ -672,12 +671,10 @@
<module>spring-reactor</module>
<module>spring-remoting</module>
<module>spring-rest-angular</module>
<module>spring-rest-query-language</module>
<module>spring-rest-shell</module>
<module>spring-rest-simple</module>
<module>spring-resttemplate</module>
<module>spring-resttemplate-2</module>
<module>spring-rest-testing</module>
<module>spring-roo</module>
@@ -1132,8 +1129,6 @@
<module>spring-mvc-java-2</module>
<module>spring-mvc-velocity</module>
<module>spring-mvc-views</module>
<module>spring-mvc-webflow</module>
<module>spring-mvc-xml</module>
<module>spring-protobuf</module>
@@ -1141,12 +1136,10 @@
<module>spring-reactor</module>
<module>spring-remoting</module>
<module>spring-rest-angular</module>
<module>spring-rest-query-language</module>
<module>spring-rest-shell</module>
<module>spring-rest-simple</module>
<module>spring-resttemplate</module>
<module>spring-resttemplate-2</module>
<module>spring-rest-testing</module>
<module>spring-roo</module>
@@ -1279,7 +1272,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
@@ -1304,23 +1296,22 @@
<modules>
<module>core-java-modules/core-java-9</module>
<module>core-java-modules/core-java-9-improvements</module>
<!-- <module>core-java-modules/core-java-9-jigsaw</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-9-new-features</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>core-java-modules/core-java-9-jigsaw</module>
<!-- <module>core-java-modules/core-java-9-new-features</module> --> <!-- uses preview features, to be decided how to handle -->
<module>core-java-modules/core-java-9-streams</module>
<module>core-java-modules/core-java-10</module>
<!-- <module>core-java-modules/core-java-11</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-12</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-13</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-14</module> --> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>core-java-modules/core-java-11</module>
<!-- <module>core-java-modules/core-java-12</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-13</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-14</module> --> <!-- uses preview features, to be decided how to handle -->
<module>core-java-modules/core-java-collections-set</module>
<!-- <module>core-java-modules/core-java-date-operations-1</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-datetime-conversion</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-datetime-string</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>core-java-modules/core-java-date-operations-1</module>
<module>core-java-modules/core-java-datetime-conversion</module>
<module>core-java-modules/core-java-datetime-string</module>
<module>core-java-modules/core-java-jpms</module>
<!-- <module>core-java-modules/core-java-os</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-time-measurements</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>core-java-modules/core-java-os</module>
<module>core-java-modules/core-java-time-measurements</module>
<module>core-java-modules/multimodulemavenproject</module>
<!-- <module>maven-java-11</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
</modules>
</profile>
@@ -1349,23 +1340,22 @@
<modules>
<module>core-java-modules/core-java-9</module>
<module>core-java-modules/core-java-9-improvements</module>
<!-- <module>core-java-modules/core-java-9-jigsaw</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-9-new-features</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>core-java-modules/core-java-9-jigsaw</module>
<!-- <module>core-java-modules/core-java-9-new-features</module> --> <!-- uses preview features, to be decided how to handle -->
<module>core-java-modules/core-java-9-streams</module>
<module>core-java-modules/core-java-10</module>
<!-- <module>core-java-modules/core-java-11</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-12</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-13</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-14</module> --> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>core-java-modules/core-java-11</module>
<!-- <module>core-java-modules/core-java-12</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-13</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-14</module> --> <!-- uses preview features, to be decided how to handle -->
<module>core-java-modules/core-java-collections-set</module>
<!-- <module>core-java-modules/core-java-date-operations-1</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-datetime-conversion</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-datetime-string</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>core-java-modules/core-java-date-operations-1</module>
<module>core-java-modules/core-java-datetime-conversion</module>
<module>core-java-modules/core-java-datetime-string</module>
<module>core-java-modules/core-java-jpms</module>
<!-- <module>core-java-modules/core-java-os</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<!-- <module>core-java-modules/core-java-time-measurements</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>core-java-modules/core-java-os</module>
<module>core-java-modules/core-java-time-measurements</module>
<module>core-java-modules/multimodulemavenproject</module>
<!-- <module>maven-java-11</module>--> <!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
</modules>
</profile>
</profiles>
+1
View File
@@ -176,6 +176,7 @@
<commons-collections4.version>4.1</commons-collections4.version>
<jetty-reactive-httpclient.version>1.0.3</jetty-reactive-httpclient.version>
<okhttp.version>4.0.1</okhttp.version>
<spring-boot.version>2.3.3.RELEASE</spring-boot.version>
</properties>
</project>
@@ -5,6 +5,7 @@ import static org.springframework.web.reactive.function.BodyInserters.fromResour
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.boot.web.server.WebServer;
import org.springframework.core.io.ClassPathResource;
@@ -102,6 +103,7 @@ public class FunctionalWebApplicationIntegrationTest {
.isEqualTo(String.valueOf(resource.contentLength()));
}
@Ignore("We get 404 after Spring Boot 2.4 upgrade. We need to solve it in a new task.")
@Test
public void givenActors_whenAddActor_thenAdded() throws Exception {
client.get()
+4
View File
@@ -64,4 +64,8 @@
</plugins>
</build>
<properties>
<spring-boot.version>2.3.3.RELEASE</spring-boot.version>
</properties>
</project>

Some files were not shown because too many files have changed in this diff Show More