下面列出了怎么用org.junit.jupiter.api.Order的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@Order(2)
public void testUpdate() throws SQLException {
if (getConnection() == null) {
LOG.warn("Test 'testUpdate' is skipped, because container is not running.");
return;
}
executeUpdate(String.format("INSERT INTO %s (name, city) VALUES ('%s', '%s')", getCompanyTableName(),
COMPANY_2, CITY_2));
//validate that event is in queue
receiveResponse(200, containsString(COMPANY_2));
executeUpdate(String.format("UPDATE %s SET name = '%s_changed' WHERE city = '%s'", getCompanyTableName(),
COMPANY_2, CITY_2));
//validate that event for delete is in queue
receiveResponse(204, is(emptyOrNullString()));
//validate that event for create is in queue
receiveResponse(200, containsString(COMPANY_2 + "_changed"));
}
@Test
@Tag("TODO")
@Order(2)
public void verifyMonthDay() {
// Real world: Birthday or anniversary
// TODO: Replace the MonthDay.now() below get a MonthDay anniversary for the Judegement Day.
// Check: java.time.MonthDay.now(java.time.Clock)
MonthDay anniversaryofJudgementDay = MonthDay.now();
assertEquals(Month.AUGUST,
anniversaryofJudgementDay.getMonth(),
"The month enumeration should match August.");
assertEquals(8,
anniversaryofJudgementDay.getMonthValue(),
"The month value should match 8.");
assertEquals(29,
anniversaryofJudgementDay.getDayOfMonth(),
"The date value should match 29.");
}
@Test
@Tag("PASSING")
@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;
// DONE: 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,
instant.getEpochSecond(),
1L,
"Date and Instant seconds should almost match");
}
@Test
@Tag("TODO")
@Order(4)
public void verifyLocalTimeUsingIntegers() {
// *****************************************************
// Demonstrate setting just the time to 7:52
// *****************************************************
// TODO: Replace the LocalTime.now() below to display a LocalTime of 7:52 AM.
// Fix LocalTime to 07:52 AM, using LocalTime with integers for hours and minutes.
// Check: java.time.LocalTime.of(int, int)
//-----------------------------------------
LocalTime sevenFiftyTwoAm = LocalTime.now();
assertEquals("07:52",
sevenFiftyTwoAm.toString(),
"The time should show 07:52");
}
@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("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("TODO")
@Order(5)
public void convertAnonymousClassToLambda() {
final AtomicInteger counter = new AtomicInteger();
// TODO:
// Replace the anonymous class with a lambda. Hint: () ->
// The addAndGet() needs to be updated to add 1 instead of 0.
Runnable runnable = new Runnable() {
@Override
public void run() {
counter.addAndGet(0);
}
};
runnable.run();
assertEquals(1, counter.get() );
}
@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
@Order(6)
public void testOfferTake() {
// Take the offer
BT.callMethod(takerPass, contract.getId(), compiled.getMethod("take"),
BurstValue.fromPlanck(security + SellContract.ACTIVATION_FEE), BurstValue.fromBurst(0.1), 100,
security, amount_chain).blockingGet();
BT.forgeBlock();
BT.forgeBlock();
System.out.println("balance " + BT.getContractBalance(contract).longValue());
// order should be taken, waiting for payment
state_chain = BT.getContractFieldValue(contract, compiled.getField("state").getAddress());
taker_chain = BT.getContractFieldValue(contract, compiled.getField("taker").getAddress());
state = SellContract.STATE_WAITING_PAYMT;
assertEquals(state, state_chain);
assertEquals(taker.getSignedLongId(), taker_chain);
}
@Test
@Tag("PASSING")
@Order(1)
public void reflectionPublicStaticMethod() {
String expectedOutput = "DemoClass.class - Public static method via reflection";
try {
// Find the method on the class via a getMethod.
Method publicStaticMethod =
DemoClass.class.getMethod("publicStaticMethod",
String.class);
assertEquals(expectedOutput,
publicStaticMethod.invoke(DemoClass.class, "via reflection"),
"Reflection invocation failed");
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
fail(REFLECTION_FAILURE.getValue() + e.getMessage());
}
}
@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(1)
public void reflectionPublicMethod() {
String expectedOutput = "[DemoClass] - Public method - via reflection";
try {
// Find the method on the class via a getMethod.
Method publicMethod =
DemoClass.class.getMethod("publicMethod",
String.class);
DemoClass demoClass = new DemoClass();
assertEquals(expectedOutput,
publicMethod.invoke(demoClass, "via reflection"),
"Reflection invocation failed");
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
fail(REFLECTION_FAILURE.getValue() + e.getMessage());
}
}
@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
@Order(1)
public void initSC() throws IOException {
sc = new CreateNoDepositSC(block * 10);
makerPass = Long.toString(System.currentTimeMillis());
sc.registerSC(makerPass);
BurstAddress maker = BT.getBurstAddressFromPassphrase(makerPass);
BT.forgeBlock();
compiled = sc.getCompiled();
contract = BT.findContract(maker, sc.getName());
BurstValue send = BurstValue.fromBurst(100);
BT.sendAmount(makerPass, contract.getId(), send, BurstValue.fromBurst(0.1)).blockingGet();
BT.forgeBlock();
BT.forgeBlock();
state_chain = BT.getContractFieldValue(contract, compiled.getField("state").getAddress());
state = SellNoDepositContract.STATE_OPEN;
assertEquals(state, state_chain, "State not equal");
}
@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
@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.");
}
@Test
@Tag("PASSING")
@Order(2)
public void verifyMonthDay() {
// Real world: Birthday or anniversary
// TODO: Replace the MonthDay.now() below get a MonthDay anniversary for the Judegement Day.
// Check: java.time.MonthDay.now(java.time.Clock)
MonthDay anniversaryofJudgementDay = MonthDay.now(terminatorOriginalJudgementDay);
assertEquals(Month.AUGUST,
anniversaryofJudgementDay.getMonth(),
"The month enumeration should match August.");
assertEquals(8,
anniversaryofJudgementDay.getMonthValue(),
"The month value should match 8.");
assertEquals(29,
anniversaryofJudgementDay.getDayOfMonth(),
"The date value should match 29.");
}
@Test
@Order(1)
public void initSC() {
sc = new InitSC();
long state = SellContract.STATE_WAITING_PAYMT;
long state_chain = sc.getContractFieldValue("state");
if(state_chain == -1){
System.out.println("Contract not found");
return;
} else if(state_chain == -2){
System.out.println("Field not found");
return;
}
assertEquals(state, state_chain);
}
@Test
@DisplayName("return an Optional of either a non-null value or from a Supplier")
@Tag("TODO")
@Order(1)
public void orReturnOptional() {
Optional<String> defaultOptional = Optional.of("supplied");
Optional<String> anOptional = Optional.empty();
/*
* TODO:
* 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 = Optional.empty();
assertTrue(nonNullOptional instanceof Optional,
"The nonNullOptional should be an instance of Optional");
assertFalse(nonNullOptional.isEmpty(),
"The nonNullOptional should not be empty");
}
@Test
@Tag("PASSING")
@Order(6)
public void customFunctionWithLambda() {
int integer = 10;
String s = Integer.toBinaryString(integer);
// DONE:
// 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 -> Integer.toBinaryString(i);
assertEquals("1010",
toBinaryStringFunction.apply(10),
"");
assertEquals("11110",
toBinaryStringFunction.apply(30),
"");
}
@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
@Order(0)
void actorToFilmCount() {
final Join<Tuple3<FilmActor, Film, Actor>> join = joinComponent
.from(FilmActorManager.IDENTIFIER)
.innerJoinOn(Film.FILM_ID).equal(FilmActor.FILM_ID)
.innerJoinOn(Actor.ACTOR_ID).equal(FilmActor.ACTOR_ID)
.build(Tuples::of);
final Map<Actor, Long> expected = join.stream()
.collect(
groupingBy(Tuple3::get2, counting())
);
tester(expected, instance.actorToFilmCount(joinComponent));
}
@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
@Order(1)
public void initSC() {
sc = new InitSC();
state = BuyContract.STATE_WAITING_PAYMT;
long state_chain = sc.getContractFieldValue("state");
if(state_chain == -1){
System.out.println("Contract not found");
return;
} else if(state_chain == -2){
System.out.println("Field not found");
return;
}
assertEquals(state, state_chain);
}
@Test
@Order(1)
public void testInsert() throws SQLException {
if (getConnection() == null) {
LOG.warn("Test 'testInsert' is skipped, because container is not running.");
return;
}
int i = 0;
while (i++ < REPEAT_COUNT) {
executeUpdate(String.format("INSERT INTO %s (name, city) VALUES ('%s', '%s')", getCompanyTableName(),
COMPANY_1 + "_" + i, CITY_1));
Response response = receiveResponse();
//if status code is 204 (no response), try again
if (response.getStatusCode() == 204) {
LOG.debug("Response code 204. Debezium is not running yet, repeating (" + i + "/" + REPEAT_COUNT + ")");
continue;
}
response
.then()
.statusCode(200)
.body(containsString((COMPANY_1 + "_" + i)));
//if response is valid, no need for another inserts
break;
}
Assert.assertTrue("Debezium does not respond (consider changing timeout in AbstractDebeziumResource).",
i < REPEAT_COUNT);
}
@Test
@Tag("PASSING")
@Order(4)
public void getPrivateVariableFromConstructedClassViaVarHandles() {
try {
/*
* DONE:
* Replace the "null"s with valid values to get a VarHandle.
* Check API: java.lang.invoke.MethodHandles.privateLookupIn(?, ?)
* HINT: params are Target class and type of lookup
* Check API: java.lang.invoke.MethodHandles.Lookup.findVarHandle(?, ?, ?)
* HINT: params are Declaring class, Variable name, Variable type
*/
VarHandle privateVariableVarHandle = MethodHandles
.privateLookupIn(TestSolutionGetter.class, MethodHandles.lookup())
.findVarHandle(TestSolutionGetter.class, "privateVariable", Integer.class);
assertEquals(1,
privateVariableVarHandle.coordinateTypes().size(),
"There should only be one coordinateType");
assertEquals(TestSolutionGetter.class,
privateVariableVarHandle.coordinateTypes().get(0),
"The only coordinate type is AttributeGetterTest");
assertTrue(privateVariableVarHandle.isAccessModeSupported(VarHandle.AccessMode.GET),
"Access mode for a GET should be true");
assertEquals(2,
privateVariableVarHandle.get(this),
"The value of the field should be 2");
} catch (NoSuchFieldException | IllegalAccessException | NullPointerException e) {
fail(TEST_FAILURE.getValue() + e.getMessage());
}
}
@Test
@Tag("PASSING")
@Order(2)
public void verifyPeriodCreatedUsingFluentMethods() {
// Create a Period instance
// TODO: Replace the Period.ZERO to a time period of 20 years and 10 days.
// Check : java.time.Period.ofYears(int).withDays(int)
Period twentyYearsAndTenDays = Period.ofYears(20).withDays(10);
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.plus(twentyYearsAndTenDays);
//1997-08-29 after 20 years and 10 days => 2017-09=08
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
@Order(2)
void firstDistinctTwoWordsLongerThanThreeCharsInAlphabeticOrder() {
tester(
instance,
WORDS.stream().filter(s -> s.length() > 3).distinct().limit(2).sorted(),
i -> i.firstDistinctTwoWordsLongerThanThreeCharsInAlphabeticOrder(WORDS.stream()),
s -> s.collect(toList())
);
}
@Test
@DisplayName("fetch from a non-null and from a null holding Optional")
@Tag("TODO")
@Order(5)
public void getValueFromOptionalForNonNullValue() {
Integer anInteger = 10;
Optional<Integer> optionalInteger = Optional.ofNullable(anInteger);
/*
* TODO:
* Replace the "11" to check that the Optional has a non-null value.
* Check API: java.util.Optional.get()
*/
assertEquals(10,
11,
"The optionalNullableInteger should be present");
anInteger = null;
Optional<Integer> anotherOptionalInteger = Optional.ofNullable(anInteger);
/*
* TODO:
* Replace the "10" to get the Optional has a null value.
* Verify that the call throws a NoSuchElementException
* Check API: java.util.Optional.get()
*/
assertThrows(NoSuchElementException.class, () -> {
assertNotEquals(10,
10,
"This call should throw a NoSuchElementException");
});
}
@Test
@Tag("TODO")
@Order(3)
public void verifyDurationCreatedUsingIntegersAndChronoUnits() {
// Create a Duration instance
// TODO: Replace the Duration.ZERO to a duration of 3 hours and 6 seconds.
// Check: java.time.Duration.of(int, ChronoUnit)
Duration threeHoursAndSixSeconds = Duration.ZERO;
assertEquals(3,
threeHoursAndSixSeconds.toHours(),
"The time duration should include three hours.");
assertEquals(10806,
threeHoursAndSixSeconds.getSeconds(),
"The time duration should include three hours and six seconds in seconds.");
// Add the Duration to a LocalDateTime
LocalDateTime tOJDateTime = LocalDateTime.now(terminatorOriginalJudgementDay);
// TODO: Call a method on tOJDateTime to add the newly created Duration
// Check : java.time.LocalDateTime.plus(java.time.temporal.TemporalAmount)
LocalDateTime calculatedThreeHoursAndSixSecondsLater =
tOJDateTime;
//7:14:30 GMT = 2:14:30 in (GMT-5). Adding 3h 6s = 5:14:36 in (GMT-5)
assertEquals(5,
calculatedThreeHoursAndSixSecondsLater.getHour(),
"The hour after 3 hours and six seconds should be 5.");
assertEquals(14,
calculatedThreeHoursAndSixSecondsLater.getMinute(),
"The minute after 3 hours and six seconds should be 14.");
assertEquals(36,
calculatedThreeHoursAndSixSecondsLater.getSecond(),
"The second after 3 hours and six seconds should be 36.");
}