下面列出了怎么用org.junit.jupiter.api.Tag的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@Tag("TODO")
@Order(1)
public void verifyInstantAndDateHaveSameEpochMilliseconds() {
// TODO: Replace the Instant.now() with an instant from classicDate.
// Use a Date API that converts Date instances into Instant instances.
// Check: java.util.Date.toInstant()
Instant instant = Instant.now();
// TODO: Replace the "null" below to get milliseconds from epoch from the Instant
// Use an Instant API which converts it into milliseconds
// Check: java.time.Instant.toEpochMilli()
assertEquals(Long.valueOf(classicDate.getTime()),
null,
"Date and Instant milliseconds should be equal");
}
@Test
@Tag("TODO")
@Order(1)
public void verifyLocalDateUsingIntegers() {
// *****************************************************
// Is March = month 2 ( remember old date API? ) or
// did Java 8 Date Time FINALLY address that and make
// month numbering consistent with ISO8601 standard?
// *****************************************************
// TODO: Replace the LocalDate.now() below to create a LocalDate of 2015-03-17.
// Fix LocalDate to a date of 2015-03-17. Try using integers for years, months and dates.
// Check : java.time.LocalDate.of(int, int, int)
LocalDate stPatricksDay2015 = LocalDate.now();
assertEquals("2015-03-17",
stPatricksDay2015.toString(),
"The stPatricksDay2015 toString() should match the expected [2015-03-17]");
}
@Test
@Tag("TODO")
@Order(4)
public void verifyYearMonth() {
// Real world: CreditCard or Medicine expiration.
// TODO: Replace the YearMonth.now() below get a YearMonth for the Judegement Day.
// Check: java.time.YearMonth.now(java.time.Clock)
YearMonth yearMonthOfJudgementDay = YearMonth.now();
assertEquals(Month.AUGUST,
yearMonthOfJudgementDay.getMonth(),
"The month enumeration should match August.");
assertEquals(8,
yearMonthOfJudgementDay.getMonthValue(),
"The month value should match 8.");
assertEquals(1997,
yearMonthOfJudgementDay.getYear(),
"The year value should match 1997.");
}
/**
* @see IntegerPair
* @see Function
*/
@Test
@Tag("PASSING")
@Order(4)
public void methodCallAsMethodReference() {
IntegerPair integerPair = new IntegerPair();
// DONE:
// Replace the below anonymous class with a method reference
// Most IDEs allow for an automatic conversion (no parenthesis for method)
// Hint: object -> Object::method
Function<IntegerPair, Integer> getSecond = IntegerPair::getSecond;
// DONE:
// Fix the assertion to return the correct expectation (6)
// Check API: java.util.function.Function.apply(?)
assertEquals(6, getSecond.apply(integerPair),
"The key should have a value of \'defaultKey\'");
}
@Test
@Tag("PASSING")
@Order(5)
public void convertAnonymousClassToLambda() {
final AtomicInteger counter = new AtomicInteger();
// DONE:
// Replace the anonymous class with a lambda. Hint: () ->
// The addAndGet() needs to be updated to add 1 instead of 0.
Runnable runnable = () -> counter.addAndGet(1);
runnable.run();
assertEquals(1, counter.get() );
}
@Test
@Tag("PASSING")
@Order(7)
public void customFunctionWithMethodReference() {
// DONE:
// Create a Function that maps any integer into a String using a method reference
// Do not create a new method. Replace the lambda below to invoke a toBinaryString
// as a method reference
// Check API: java.util.function.Function
// Check API: java.util.function.Function.apply(?)
// Check API: java.lang.Integer.toBinaryString(?)
Function<Integer, String> toBinaryStringFunction = Integer::toBinaryString;
assertEquals("1010",
toBinaryStringFunction.apply(10),
"");
assertEquals("11110",
toBinaryStringFunction.apply(30),
"");
}
@Test
@Tag("TODO")
@Order(2)
public void verifyLocalDateUsingMonthEnums() {
// *****************************************************
// A tribute to 2001: A Space Odyssey.
// HAL, the sentient computer,
// was 'born' on January 12th 1999
// *****************************************************
// TODO: Replace the LocalDate.now() below to create a LocalDate of 1999-01-12.
// Fix LocalDate below to HAL's birthday. Use Month enums.
// No longer a confusion about whether January is 0 or 1.
LocalDate halsBirthday = LocalDate.now();
assertEquals(1999,
halsBirthday.getYear(),
"LocalDate year should match the expected");
assertEquals(Month.JANUARY,
halsBirthday.getMonth(),
"LocalDate month should match the expected");
}
@Test
@Tag("TODO")
@Order(6)
public void customFunctionWithLambda() {
int integer = 10;
String s = Integer.toBinaryString(integer);
// TODO:
// Create a Function that maps any integer into a String using a lambda syntax
// Do not create a new method. Replace the empty String below to invoke a toBinaryString
// Check API: java.util.function.Function
// Check API: java.util.function.Function.apply(?)
Function<Integer, String> toBinaryStringFunction = i -> "";
assertEquals("1010",
toBinaryStringFunction.apply(10),
"");
assertEquals("11110",
toBinaryStringFunction.apply(30),
"");
}
@Test
@Tag("TODO")
@Order(4)
public void sortNames() {
List<Person> persons =
Arrays.asList(Person.ALICE, Person.BOB, Person.CATHY, Person.DHRUV, Person.EMILY);
List<Person> expectedList =
Arrays.asList(Person.EMILY, Person.BOB, Person.DHRUV, Person.ALICE, Person.CATHY);
// TODO:
// Replace the anonymous class with a lambda.
// Replace the postions of o2 and o1 to pass the test as well
Comparator<Person> nameSorter = new Comparator<>() {
@Override
public int compare(Person o1, Person o2) {
return o2.getLastName().compareTo(o1.getLastName());
}
};
List<Person> actualList = new ArrayList<>();
actualList.addAll(persons);
Collections.sort(actualList, nameSorter);
assertEquals(expectedList, actualList, "The sorted lists should match");
}
@Test
@DisplayName("return an Optional of either a non-null value or from a Supplier")
@Tag("PASSING")
@Order(1)
public void orReturnOptional() {
Optional<String> defaultOptional = Optional.of("supplied");
Optional<String> anOptional = Optional.empty();
/*
* DONE:
* Replace the empty optional to either return the anOptional, if it has a value
* or return the defaultOptional (use a Supplier)
* Check API: java.util.Optional.or(?)
*/
Optional<String> nonNullOptional = anOptional.or(() -> defaultOptional);
assertTrue(nonNullOptional instanceof Optional,
"The nonNullOptional should be an instance of Optional");
assertFalse(nonNullOptional.isEmpty(),
"The nonNullOptional should not be empty");
}
@Test
@DisplayName("return either a value from non-empty Optional or a default value")
@Tag("PASSING")
@Order(2)
public void orElseReturnValue() {
Integer anInteger = null;
Optional<Integer> nullableInteger = Optional.ofNullable(anInteger);
/*
* DONE:
* Replace the below to use an orElse(?) - instead of - the or(?)
* and the need to use get()
* Check API: java.util.Optional.orElse(?)
*/
Integer nonNullInteger = nullableInteger.orElse(10);
assertTrue(nonNullInteger instanceof Integer,
"The nonNullInteger should be an instance of Integer");
assertEquals(nonNullInteger,
10,
"The nonNullInteger should not be empty");
}
@Test
@Tag("TODO")
@Order(5)
public void verifyInstantDateInteroperability() {
// *****************************************************
// Converting Date to an Instant.
// *****************************************************
Instant instant = classicDate.toInstant();
assertEquals(classicDate.getTime(), instant.toEpochMilli());
// *****************************************************
// Converting an Instant to a Date.
// *****************************************************
// TODO: Replace the "null" below to convert an Instant into a Date
// Check: java.util.Date.from()
Date anotherDate = null;
assertEquals(classicDate, anotherDate);
// *****************************************************
// Think about why all conversions and inter-ops are
// built into Date and not the newer java.time API.
// *****************************************************
}
@Test
@DisplayName("create an empty Optional")
@Tag("PASSING")
@Order(1)
public void emptyOptional() {
/*
* DONE:
* Replace the "null" to create an empty Optional.
* Check API: java.util.Optional.empty()
*/
Optional<String> optionalEmptyString = Optional.empty();
assertTrue(optionalEmptyString instanceof Optional,
"The optionalEmptyString should be an instance of Optional");
assertTrue(optionalEmptyString.isEmpty(),
"The optionalEmptyString should be empty");
}
@Test
@DisplayName("create an Optional from a variable")
@Tag("PASSING")
@Order(2)
public void createOptionalFromValue() {
Integer anInteger = 10;
/*
* DONE:
* Replace the "null" to create an Optional for anInteger.
* Check API: java.util.Optional.of(?)
*/
Optional<Integer> optionalForInteger = Optional.of(anInteger);
assertTrue(optionalForInteger instanceof Optional,
"The optionalEmptyString should be an instance of Optional");
assertFalse(optionalForInteger.isEmpty(),
"The optionalForInteger should not be empty");
}
@Test
@DisplayName("create a nullable Optional from a variable")
@Tag("PASSING")
@Order(3)
public void createNullableOptionalFromValue() {
Integer anInteger = null;
/*
* DONE:
* Replace the "null" to create a nullable Optional for anInteger.
* Check API: java.util.Optional.ofNullable(?)
*/
Optional<Integer> optionalNullableInteger = Optional.ofNullable(anInteger);
assertTrue(optionalNullableInteger instanceof Optional,
"The optionalNullableInteger should be an instance of Optional");
assertTrue(optionalNullableInteger.isEmpty(),
"The optionalNullableInteger should be empty");
}
@Test
@DisplayName("create an Optional from a variable")
@Tag("TODO")
@Order(2)
public void createOptionalFromValue() {
Integer anInteger = 10;
/*
* TODO:
* Replace the "null" to create an Optional for anInteger.
* Check API: java.util.Optional.of(?)
*/
Optional<Integer> optionalForInteger = null;
assertTrue(optionalForInteger instanceof Optional,
"The optionalEmptyString should be an instance of Optional");
assertFalse(optionalForInteger.isEmpty(),
"The optionalForInteger should not be empty");
}
@Test
@Tag("PASSING")
@Order(6)
public void verifyLocalDateTimeUsingIntegers() {
// DONE: Replace the LocalDateTime.now() to produce the desired date and time.
// Fix LocalDateTime to a date of 2005-05-05 and a time on 05:05:05 AM.
// Check: java.time.LocalDateTime.of(int, int, int, int, int, int)
LocalDateTime allDateTimeOhFives =
LocalDateTime.of(5, 5, 5, 5, 5, 5);
assertTrue(allDateTimeOhFives.getMonthValue() == 5,
"The month should be May (5th Month)");
assertEquals(5,
allDateTimeOhFives.getMinute(),
"The minute should be 5");
assertTrue(allDateTimeOhFives.getSecond() == 5,
"The second should be 5");
}
@Test
@Tag("PASSING")
@Order(7)
public void verifyLocalDateTimeUsingClock() {
// DONE: Replace the LocalDateTime.now() to produce the desired date and time.
// Fix LocalDateTime to the exact date-time of the Terminator (Original) Judgement Day.
// Check: java.time.LocalDateTime.now(java.time.Clock)
LocalDateTime theOriginalJudgementDayDateTime =
LocalDateTime.now(terminatorOriginalJudgementDay);
assertEquals(8,
theOriginalJudgementDayDateTime.getMonthValue(),
"The Original Terminator Judgement Day was in the 8th month (August)");
assertEquals(2,
theOriginalJudgementDayDateTime.getHour(),
"The hour should be at 2 AM");
assertEquals(14,
theOriginalJudgementDayDateTime.getMinute(),
"The minute should be at 14");
}
@Test
@DisplayName("return a value either from non-empty Optional or from a Supplier")
@Tag("TODO")
@Order(3)
public void orElseGetSupplierValue() {
String defaultOptional = "supplied";
Optional<String> anOptional = Optional.empty();
/*
* TODO:
* Replace the below to use an orElseGet(?) - instead of - the or(?)
* and the need to use get()
* Check API: java.util.Optional.ofNullable(?)
*/
String nonNullString = null;
assertTrue(nonNullString instanceof String,
"The nonNullString should be an instance of String");
assertEquals(nonNullString,
"supplied",
"The nonNullString should have a value of \"supplied\"");
}
@Test
@Tag("PASSING")
@Order(1)
public void reflectionNoParamConstructor() {
String expectedOutput = "[No param DemoClass constructor]" +
" - Default constructor via Reflection";
try {
Class<DemoClass> demoClassClass =
(Class<DemoClass>) Class.forName("none.cvg.handles.DemoClass");
DemoClass demoClass =
demoClassClass.getDeclaredConstructor().newInstance();
assertEquals(expectedOutput,
demoClass.printStuff("Default constructor via Reflection"),
"Reflection invocation failed");
} catch (InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException | ClassNotFoundException e) {
fail(REFLECTION_FAILURE.getValue() + e.getMessage());
}
}
@Test
@Tag("TODO")
@Order(2)
public void verifyInstantAndDateHaveAlmostSameEpochSeconds() {
Instant instant = classicDate.toInstant();
// NOTE: There is no simpler API method to get epoch seconds.
long classicDateInSeconds = classicDate.getTime() / 1000;
// TODO: Replace the "null" below to get seconds from epoch from the Instant
// Assert that the seconds from epoch from both Date and Instant are equal.
// Check: java.time.Instant.getEpochSecond()
// NOTE: We use a custom assertion here since the millis to second arithmetic may cause
// rounding issues. We add a tolerance of 1 second.
assertAlmostEquals(classicDateInSeconds,
null,
1L,
"Date and Instant seconds should almost match");
}
@Test
@Tag("TODO")
@Order(6)
public void verifyLocalDateTimeUsingIntegers() {
// TODO: Replace the LocalDateTime.now() to produce the desired date and time.
// Fix LocalDateTime to a date of 2005-05-05 and a time on 05:05:05 AM.
// Check: java.time.LocalDateTime.of(int, int, int, int, int, int)
LocalDateTime allDateTimeOhFives =
LocalDateTime.now();
assertTrue(allDateTimeOhFives.getMonthValue() == 5,
"The month should be May (5th Month)");
assertEquals(5,
allDateTimeOhFives.getMinute(),
"The minute should be 5");
assertTrue(allDateTimeOhFives.getSecond() == 5,
"The second should be 5");
}
@Test
@Tag("PASSING")
@Order(1)
public void verifyInstantAndDateHaveSameEpochMilliseconds() {
// DONE: Replace the Instant.now() with an instant from classicDate.
// Use a Date API that converts Date instances into Instant instances.
// Check: java.util.Date.toInstant()
Instant instant = classicDate.toInstant();
// DONE: Replace the "null" below to get milliseconds from epoch from the Instant
// Use an Instant API which converts it into milliseconds
// Check: java.time.Instant.toEpochMilli()
assertEquals(Long.valueOf(classicDate.getTime()),
instant.toEpochMilli(),
"Date and Instant milliseconds should be equal");
}
@Test
@Tag("PASSING")
@Order(5)
public void verifyInstantDateInteroperability() {
// *****************************************************
// Converting Date to an Instant.
// *****************************************************
Instant instant = classicDate.toInstant();
assertEquals(classicDate.getTime(), instant.toEpochMilli());
// *****************************************************
// Converting an Instant to a Date.
// *****************************************************
// DONE: Replace the "null" below to convert an Instant into a Date
// Check: java.util.Date.from()
Date anotherDate = Date.from(instant);
assertEquals(classicDate, anotherDate);
// *****************************************************
// Think about why all conversions and inter-ops are
// built into Date and not the newer java.time API.
// *****************************************************
}
@Test
@Tag("PASSING")
@Order(9)
public void verifyZonedDateTimeUsingClock() {
// *****************************************************
// Demonstrate creating a new ZonedDateTime if GMT +1
// from the clock now(). Convert a LocalDateTime into
// an Instant, which can subsequently be used to
// create the new ZonedDateTime
// *****************************************************
LocalDateTime theOriginalJudgementDayDateTime =
LocalDateTime.now(terminatorOriginalJudgementDay);
Instant tojdInstant = theOriginalJudgementDayDateTime
.toInstant(ZoneOffset.of("+0000"));
// DONE: Replace ZonedDateTime.now() to get date time in GMT +1 offset.
// Given a timestamp of 1997-08-29T07:14:30Z,
// fix it to display in GMT +1. Show the same Instant in a different zone.
// Check: java.time.ZonedDateTime.ofInstant(java.time.Instant, java.time.ZoneId)
ZonedDateTime gmtPlusOneHourTimeForTOJD =
ZonedDateTime.ofInstant(tojdInstant, ZoneId.of("GMT+1"));
assertEquals(8,
gmtPlusOneHourTimeForTOJD.getMonthValue(),
"The expected and actual month values should match");
assertEquals(3,
gmtPlusOneHourTimeForTOJD.getHour(),
"The expected and actual hour values should match");
assertEquals(Integer.valueOf(14),
gmtPlusOneHourTimeForTOJD.getMinute(),
"The expected and actual minute values should match");
}
@Test
@Tag("TODO")
@Order(1)
public void verifyPeriodCreatedUsingIntegers() {
// Create a Period instance
// TODO: Replace the Period.ZERO to a time period of 20 years and 10 days.
// Check : java.time.Period.of(int, int, int)
Period twentyYearsAndTenDays = Period.ZERO;
assertEquals(20,
twentyYearsAndTenDays.get(ChronoUnit.YEARS),
"The Period should include twenty years");
assertEquals(10,
twentyYearsAndTenDays.get(ChronoUnit.DAYS),
"The Period should include ten days");
// Add the Period to a LocalDateTime
LocalDateTime tOJDateTime = LocalDateTime.now(terminatorOriginalJudgementDay);
// TODO: Call a method on tOJDateTime to add the newly created Period
// Check : java.time.LocalDateTime.plus(java.time.temporal.TemporalAmount)
LocalDateTime calculatedTwentyYearsAndTenDaysLater =
tOJDateTime;
assertEquals(2017,
calculatedTwentyYearsAndTenDaysLater.getYear(),
"The year after 20 years and 10 days should be 2017");
assertEquals(9,
calculatedTwentyYearsAndTenDaysLater.getMonthValue(),
"The month value after 20 years and 10 days should be 9");
assertEquals(8,
calculatedTwentyYearsAndTenDaysLater.getDayOfMonth(),
"The date after 20 years and 10 days should be 8");
}
@Test
@Tag("TODO")
@Order(5)
public void verifyDayOfWeek() {
LocalDateTime tOJDateTime = LocalDateTime.now(terminatorOriginalJudgementDay);
// TODO: Replace the null below to get the Day Of Week from the tOJDateTime.
// Check: java.time.LocalDateTime.getDayOfWeek()
DayOfWeek dayOfWeek = null;
assertEquals(DayOfWeek.FRIDAY,
dayOfWeek,
"The day of the week enumeration should match Friday.");
}
@Test
@Tag(Constants.USE_BASIC_AUTH_SOURCE_TAG)
@Tag(Constants.USE_BASIC_AUTH_DEST_TAG)
public void testBothBasicHttpAuthUserInfo() throws IOException {
configure(
Constants.HTTP_AUTH_SOURCE_CREDENTIALS_FIXTURE,
Constants.HTTP_AUTH_DEST_CREDENTIALS_FIXTURE,
ExplicitAuthType.USER_INFO);
this.passSimpleMessage();
}
@Test
@Tag("PASSING")
@Order(4)
public void cannotModifyConstantUsingVarHandles() throws Throwable {
/*
* NOTE:
* A call to alter the value of a constant should ideally fail, per the JEP / spec.
* Constants (static finals) cannot be modified using VarHandles.
*/
assertThrows(java.lang.UnsupportedOperationException.class, () -> {
ClassWithPrivateFinalField instance = new ClassWithPrivateFinalField(10);
/*
* DONE:
* Replace the "null"s with valid values to get a VarHandle to PRIVATE_FINAL_FIELD.
* Note that the final field is in an inner class.
* Check API: java.lang.invoke.MethodHandles.privateLookupIn(?, ?)
* HINT: params are Target class, Lookup type
* Check API: java.lang.invoke.MethodHandles.Lookup.findVarHandle(?, ?, ?)
* HINT: params are Declaring class, Variable name, Variable type
* Remember CONSTANT in of type Integer.class
*/
VarHandle publicStaticFinalConstant = MethodHandles
.privateLookupIn(TestSolutionVarHandlesForbiddenUnsafeFeatures.class,
MethodHandles.lookup())
.findStaticVarHandle(ClassWithPrivateFinalField.class,
"CONSTANT",
Integer.class);
/*
* NOT ALLOWED:
* Should throw the expected exception.
*/
publicStaticFinalConstant.set(instance, -20);
});
}
@Test
@Tag("PASSING")
@Order(10)
@DisplayName("verify conversion of UTC date time to Indian Standard Time")
public void verifyConversionOfUTCDateTimeToIndianStandardTime() {
ZonedDateTime allDateTimeOhFives =
ZonedDateTime.of(5,
5,
5,
5,
5,
5,
555,
ZoneId.ofOffset("", ZoneOffset.UTC));
ZoneId gmtPlusOneZoneId = ZoneId.ofOffset("", ZoneOffset.of("+0530"));
// DONE: Replace the ZonedDateTime.now() below to display the below UTC time in GMT +0530
// The ZonedDateTime created in GMT. Fix the calls so a ZonedDateTime
// can be created with the offset of GMT +0530. Use an ofInstant from a toInstant.
// Check: java.time.ZonedDateTime.ofInstant(java.time.Instant, java.time.ZoneId)
// Check: java.time.ZonedDateTime.toInstant()
ZonedDateTime gmtPlusOneHourTimeForAllFives =
ZonedDateTime.ofInstant(
allDateTimeOhFives.toInstant(),
gmtPlusOneZoneId);
assertEquals(10,
gmtPlusOneHourTimeForAllFives.getHour(),
"The hour should be at 10 AM when Zone Offset is GMT +0530");
assertEquals(35,
gmtPlusOneHourTimeForAllFives.getMinute(),
"The minute should be 35 when Zone Offset is GMT +0530");
}