下面列出了怎么用org.junit.jupiter.api.function.Executable的API类实例代码及写法,或者点击链接到github查看源代码。
static Stream<Executable> checkRdfStream(final Resource res, final long userManaged,
final long serverManaged, final long acl, final long audit, final long membership, final long containment) {
final long total = userManaged + acl + audit + membership + containment + serverManaged;
return Stream.of(
() -> assertEquals(serverManaged, res.stream(singleton(Trellis.PreferServerManaged)).count(),
"Incorrect server managed triple count!"),
() -> assertEquals(userManaged, res.stream(singleton(Trellis.PreferUserManaged)).count(),
"Incorrect user managed triple count!"),
() -> assertEquals(acl, res.stream(singleton(Trellis.PreferAccessControl)).count(),
"Incorrect acl triple count!"),
() -> assertEquals(audit, res.stream(singleton(Trellis.PreferAudit)).count(),
"Incorrect audit triple count!"),
() -> assertEquals(membership, res.stream(singleton(LDP.PreferMembership)).count(),
"Incorrect member triple count!"),
() -> assertEquals(containment, res.stream(singleton(LDP.PreferContainment)).count(),
"Incorrect containment triple count!"),
() -> assertEquals(total, res.stream().count(), "Incorrect total triple count!"));
}
static Stream<Executable> checkHtmlWithoutNamespaces(final String html) {
return of(
() -> assertTrue(html.contains("<title>http://example.com/</title>"), "Title not in HTML!"),
() -> assertTrue(html.contains("_:B"), "bnode value not in HTML!"),
() -> assertTrue(
html.contains("<a href=\"http://sws.geonames.org/4929022/\">http://sws.geonames.org/4929022/</a>"),
"Geonames object IRI not in HTML!"),
() -> assertTrue(
html.contains("<a href=\"http://purl.org/dc/terms/spatial\">http://purl.org/dc/terms/spatial</a>"),
"dc:spatial predicate not in HTML!"),
() -> assertTrue(
html.contains("<a href=\"http://purl.org/dc/dcmitype/Text\">http://purl.org/dc/dcmitype/Text</a>"),
"dcmi type not in HTML output!"),
() -> assertTrue(html.contains("<a href=\"mailto:[email protected]\">mailto:[email protected]</a>"),
"email IRI not in output!"),
() -> assertTrue(html.contains("<h1>http://example.com/</h1>"), "Default title not in output!"));
}
@Test
public void testCommandLineRunnerSetToFalse() {
String[] enabledArgs = new String[] {};
this.applicationContext = SpringApplication.run(
new Class[] {
TaskJobLauncherCommandLineRunnerTests.JobConfiguration.class },
enabledArgs);
validateContext();
assertThat(this.applicationContext.getBean(JobLauncherApplicationRunner.class))
.isNotNull();
Executable executable = () -> this.applicationContext
.getBean(TaskJobLauncherCommandLineRunner.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(executable::execute).withMessage("No qualifying bean of type "
+ "'org.springframework.cloud.task.batch.handler.TaskJobLauncherCommandLineRunner' available");
validateContext();
}
@Test
public void does_not_allow_more_than_one_preferential_parameter_type_for_each_regexp() {
registry.defineParameterType(new ParameterType<>("name", CAPITALISED_WORD, Name.class, Name::new, false, true));
registry.defineParameterType(new ParameterType<>("person", CAPITALISED_WORD, Person.class, Person::new, false, false));
final Executable testMethod = () -> registry.defineParameterType(new ParameterType<>(
"place",
CAPITALISED_WORD,
Place.class,
Place::new,
false,
true
));
final CucumberExpressionException thrownException = assertThrows(CucumberExpressionException.class, testMethod);
assertThat("Unexpected message", thrownException.getMessage(), is(equalTo("There can only be one preferential parameter type per regexp. The regexp /[A-Z]+\\w+/ is used for two preferential parameter types, {name} and {place}")));
}
@Test
@DisplayName("Environment must have a parent type")
void environment_must_have_parent_type() {
String uri = "abc123";
HGQLSchema schema = mock(HGQLSchema.class);
DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);
Field field1 = mock(Field.class);
List<Field> fields = Collections.singletonList(field1);
when(environment.getFields()).thenReturn(fields);
when(field1.getName()).thenReturn("field1");
FieldConfig fieldConfig = mock(FieldConfig.class);
Map<String, FieldConfig> schemaFields = Collections.singletonMap("field1", fieldConfig);
when(schema.getFields()).thenReturn(schemaFields);
when(fieldConfig.getId()).thenReturn(uri);
Executable executable = () -> new FetchParams(environment, schema);
assertThrows(NullPointerException.class, executable);
}
/**
* Check a Trellis Resource.
* @param res the Resource
* @param identifier the identifier
* @param ldpType the LDP type
* @param time an instant before which the resource shouldn't exist
* @param dataset a dataset to compare against
* @return a stream of testable assertions
*/
default Stream<Executable> checkResource(final Resource res, final IRI identifier, final IRI ldpType,
final Instant time, final Dataset dataset) {
return Stream.of(
() -> assertEquals(ldpType, res.getInteractionModel(), "Check the interaction model"),
() -> assertEquals(identifier, res.getIdentifier(), "Check the identifier"),
() -> assertFalse(res.getModified().isBefore(time), "Check the modification time (1)"),
() -> assertFalse(res.getModified().isAfter(now()), "Check the modification time (2)"),
() -> assertFalse(res.hasMetadata(Trellis.PreferAccessControl), "Check for an ACL"),
() -> assertEquals(LDP.NonRDFSource.equals(ldpType), res.getBinaryMetadata().isPresent(),
"Check Binary"),
() -> assertEquals(asList(LDP.DirectContainer, LDP.IndirectContainer).contains(ldpType),
res.getMembershipResource().isPresent(), "Check ldp:membershipResource"),
() -> assertEquals(asList(LDP.DirectContainer, LDP.IndirectContainer).contains(ldpType),
res.getMemberRelation().isPresent() || res.getMemberOfRelation().isPresent(),
"Check ldp:hasMemberRelation or ldp:isMemberOfRelation"),
() -> assertEquals(asList(LDP.DirectContainer, LDP.IndirectContainer).contains(ldpType),
res.getInsertedContentRelation().isPresent(), "Check ldp:insertedContentRelation"),
() -> res.stream(Trellis.PreferUserManaged).filter(q -> !q.getPredicate().equals(type)).forEach(q ->
assertTrue(dataset.contains(q))));
}
static Stream<Executable> checkResource(final Resource res, final IRI identifier, final IRI ldpType,
final boolean hasBinary, final boolean hasAcl, final boolean hasParent) {
return Stream.of(
() -> assertEquals(identifier, res.getIdentifier(), "Incorrect identifier!"),
() -> assertEquals(ldpType, res.getInteractionModel(), "Incorrect interaction model!"),
() -> assertEquals(parse(time), res.getModified(), "Incorrect modified date!"),
() -> assertNotNull(res.getRevision(), "Revision is null!"),
() -> assertEquals(hasBinary, res.getBinaryMetadata().isPresent(), "Unexpected binary presence!"),
() -> assertEquals(hasParent, res.getContainer().isPresent(), "Unexpected parent resource!"),
() -> assertEquals(res.stream(barGraph).findAny().isPresent(), res.hasMetadata(barGraph),
"Unexpected metadata"),
() -> assertEquals(res.stream(fooGraph).findAny().isPresent(), res.hasMetadata(fooGraph),
"Unexpected metadata"),
() -> assertEquals(res.getMetadataGraphNames().contains(Trellis.PreferAudit),
res.hasMetadata(Trellis.PreferAudit), "Unexpected Audit quads"),
() -> assertEquals(res.stream(Trellis.PreferAudit).findAny().isPresent(),
res.hasMetadata(Trellis.PreferAudit), "Missing audit quads"),
() -> assertEquals(res.getMetadataGraphNames().contains(Trellis.PreferAccessControl),
res.hasMetadata(Trellis.PreferAccessControl), "Unexpected ACL presence!"),
() -> assertEquals(hasAcl, res.hasMetadata(Trellis.PreferAccessControl), "Unexpected ACL presence!"));
}
/**
* 测试用例: 测试createProblemCategoryRelationship(long, ProblemCategory)方法
* 测试数据: 使用存在的存在试题ID和存在的试题分类对象
* 预期结果: 抛出DuplicateKeyException异常
*/
@Test
public void testCreateProblemCategoryRelationshipUsingExistingProblemIdAndExistingProblemCategory() {
ProblemCategory problemCategory = problemCategoryMapper.getProblemCategoryUsingCategoryId(1);
Executable e = () -> {
problemCategoryMapper.createProblemCategoryRelationship(1000, problemCategory);
};
Assertions.assertThrows(org.springframework.dao.DuplicateKeyException.class, e);
}
/**
* 测试用例: 测试updateProblemCategory(ProblemCategory)方法
* 测试数据: 使用不合法的数据集(过长的类别名称)
* 预期结果: 抛出DataIntegrityViolationException异常
*/
@Test
public void testUpdateProblemCategoryUsingTooLongCategoryName() {
ProblemCategory problemCategory = problemCategoryMapper.getProblemCategoryUsingCategorySlug("uncategorized");
Assertions.assertNotNull(problemCategory);
problemCategory.setProblemCategoryName("New Category Very Very Very Long Name");
Executable e = () -> {
problemCategoryMapper.updateProblemCategory(problemCategory);
};
Assertions.assertThrows(org.springframework.dao.DataIntegrityViolationException.class, e);
}
/**
* 测试用例: 测试updateDiscussionTopic(DiscussionTopic)
* 测试数据: 使用合法的数据集, 但是该别名存在相应的记录
* 预期结果: 抛出DuplicateKeyException异常
*/
@Test
public void testUpdateDiscussionTopicWithDupliateSlug() {
DiscussionTopic topic = discussionTopicMapper.getDiscussionTopicUsingSlug("general");
Assertions.assertNotNull(topic);
topic.setDiscussionTopicSlug("support");
Executable e = () -> {
discussionTopicMapper.updateDiscussionTopic(topic);
};
Assertions.assertThrows(org.springframework.dao.DuplicateKeyException.class, e);
}
/**
* 测试用例: 测试createUser(User)方法
* 测试数据: 使用合法的数据集, 但数据表中已存在相同的用户名
* 预期结果: 抛出org.springframework.dao.DuplicateKeyException异常
*/
@Test
public void testCreateUserUsingExistingUsername() {
UserGroup userGroup = new UserGroup(1, "users", "Users");
Language language = new Language(2, "text/x-c++", "C++", "g++ foo.cpp -o foo", "./foo");
User user = new User("zjhzxhz", "Password","[email protected]", userGroup, language);
Executable e = () -> {
userMapper.createUser(user);
};
Assertions.assertThrows(org.springframework.dao.DuplicateKeyException.class, e);
}
/**
* Run the LDP Binary tests.
* @return an executable for each of the tests
* @throws Exception in the case of an error
*/
default Stream<Executable> runTests() throws Exception {
setUp();
return Stream.of(this::testGetBinary,
this::testGetBinaryDescription,
this::testPostBinary,
this::testPatchBinaryDescription,
this::testBinaryIsInContainer);
}
@Test
@DisplayName("Constructor exception with nulls for first 2 parameters")
void should_throw_exception_on_construction_from_first_2_null() {
Executable executable = () -> new HGQLSchemaWiring(null, null, new ArrayList<>());
Throwable exception = assertThrows(HGQLConfigurationException.class, executable);
assertEquals("Unable to perform schema wiring", exception.getMessage());
}
@Test
@DisplayName("Constructor exception with nulls for last 2 parameters")
void should_throw_exception_on_construction_from_last_2_null() {
TypeDefinitionRegistry registry = mock(TypeDefinitionRegistry.class);
Executable executable = () -> new HGQLSchemaWiring(registry, null, null);
Throwable exception = assertThrows(HGQLConfigurationException.class, executable);
assertEquals("Unable to perform schema wiring", exception.getMessage());
}
/**
* Assert that an IllegalArgumentException is thrown when specifying both reduce=true and
* include_docs=true
*
* @throws Exception
*/
@Test
public void validationIncludeDocsReduceView() throws Exception {
assertThrows(IllegalArgumentException.class,
new Executable() {
@Override
public void execute() throws Throwable {
ViewRequest<String, Object> paginatedQuery = db.getViewRequestBuilder
("example", "foo")
.newRequest(Key.Type.STRING,
Object.class).includeDocs(true).reduce(true).build();
}
});
}
@Test
public void testWithoutPerdatabaseconaRollbackAndFail() throws RollbackImpossibleException {
System.setProperty(Configuration.FAIL_IF_NO_PT, "true");
PTOnlineSchemaChangeStatement.available = false;
Assertions.assertThrows(RuntimeException.class, new Executable() {
@Override
public void execute() throws Throwable {
generateRollbackStatements();
}
});
}
private <T extends Throwable> void assertThrowsWithWrapper(@Nonnull Class<T> expectedType, @Nonnull Executable executable) {
try {
executable.execute();
} catch (Throwable actualException) {
while (actualException instanceof CompletionException) {
actualException = actualException.getCause();
}
if (expectedType.isInstance(actualException)) {
return;
} else {
throw new AssertionFailedError("Unexpected exception type thrown", actualException);
}
}
throw new AssertionFailedError(String.format("Expected %s to be thrown, but nothing was thrown.", expectedType.getCanonicalName()));
}
@Override
default Stream<Executable> runTests() {
setUp();
return Stream.of(this::testMementosWereFound,
this::testMementoDateTimeHeader,
this::testMementoAllowedMethods,
this::testMementoLdpResource,
this::testMementoContent,
this::testCanonicalHeader,
this::testCanonicalHeaderDescriptions);
}
@Test
void missingNamespaceShouldThrowException() {
// Given
final Executable newInstance = () -> new LeaseLock(null, "name", "1337");
// When - Then
assertThrows(NullPointerException.class, newInstance);
}
/**
* 测试用例: 测试createUser(User)方法
* 测试数据: 使用不合法的数据集(过长的用户名)
* 预期结果: 抛出org.springframework.dao.DataIntegrityViolationException异常
*/
@Test
public void testCreateUserUsingTooLongUsername() {
UserGroup userGroup = new UserGroup(1, "users", "Users");
Language language = new Language(2, "text/x-c++", "C++", "g++ foo.cpp -o foo", "./foo");
User user = new User("new-user-0xffffffff", "Password","[email protected]", userGroup, language);
Executable e = () -> {
userMapper.createUser(user);
};
Assertions.assertThrows(org.springframework.dao.DataIntegrityViolationException.class, e);
}
private Executable createTest(HdfFile hdfFile, String datasetPath) {
return () -> {
Dataset dataset = hdfFile.getDatasetByPath(datasetPath);
Object data = dataset.getData();
Object[] flatData = flatten(data);
for (int i = 0; i < flatData.length; i++) {
// Do element comparison as there are all different primitive numeric types
// convert to double
assertThat(Double.valueOf(flatData[i].toString()), is(equalTo((double) i)));
}
};
}
private Stream<Executable> checkJsonStructure(final Map<String, Object> obj, final List<String> include,
final List<String> omit) {
return Stream.concat(
include.stream().map(key ->
() -> assertTrue(obj.containsKey(key), "JSON-LD didn't contain expected key: " + key)),
omit.stream().map(key ->
() -> assertFalse(obj.containsKey(key), "JSON-LD contained extraneous key: " + key)));
}
/**
* Run the tests.
* @return the tests
*/
default Stream<Executable> runTests() {
setUp();
return of(this::testReceiveCreateMessage, this::testReceiveChildMessage, this::testReceiveDeleteMessage,
this::testReceiveCreateMessageDC, this::testReceiveDeleteMessageDC, this::testReceiveCreateMessageIC,
this::testReceiveReplaceMessageIC, this::testReceiveDeleteMessageIC);
}
@Test
public void vcapNoServicesPresent() {
Assertions.assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
ClientBuilder.bluemix(new CloudFoundryServiceTest.VCAPGenerator().toJson());
}
});
}
@Test
void shouldAddProduct_thenThrowException() {
final Product product = new Product(UUID.randomUUID(), BigDecimal.TEN, "test");
final UUID id = UUID.randomUUID();
when(orderRepository.findById(id)).thenReturn(Optional.empty());
final Executable executable = () -> tested.addProduct(id, product);
verify(orderRepository, times(0)).save(any(Order.class));
assertThrows(RuntimeException.class, executable);
}
@Test
void missingNameShouldThrowException() {
// Given
final Executable newInstance = () -> new LeaseLock("namespace", null, "1337");
// When - Then
assertThrows(NullPointerException.class, newInstance);
}
@Test
public void testWithoutPerconaAndFail() {
System.setProperty(Configuration.FAIL_IF_NO_PT, "true");
PTOnlineSchemaChangeStatement.available = false;
Assertions.assertThrows(RuntimeException.class, new Executable() {
@Override
public void execute() throws Throwable {
generateStatements();
}
});
}
@Test
void standard() {
final ShutdownEnabler se = new ShutdownEnabler();
final ExecutorService e = Executors.newFixedThreadPool(1);
final Future<?> f = e.submit(se::waitUntilTriggered);
assertThatThrownBy(() -> f.get(1, TimeUnit.SECONDS))
.isInstanceOf(TimeoutException.class); // the thread is blocked
final Consumer<ReturnCode> c = se.get()
.orElseThrow(() -> new IllegalStateException("Should have returned."));
c.accept(ReturnCode.OK); // this unblocks the thread
// this should return
assertTimeout(Duration.ofSeconds(5), (Executable) f::get);
assertThat(f).isDone();
e.shutdownNow();
}
private Executable createTest(HdfFile file, String nodePath, String attributeName, Object expectedData) {
return () -> {
Node node = file.getByPath(nodePath);
Attribute attribute = node.getAttribute(attributeName);
assertThat(attribute.getData(), is(equalTo(expectedData)));
// Call getData again to ensure the is no persisted state after the first read.
assertThat(attribute.getData(), is(equalTo(expectedData)));
assertThat(attribute.getName(), is(equalTo(attributeName)));
if (expectedData == null) {// Empty attributes
assertThat(attribute.isEmpty(), is(true));
assertThat(attribute.isScalar(), is(false));
assertThat(attribute.getSize(), is(0L));
assertThat(attribute.getDiskSize(), is(0L));
} else if (expectedData.getClass().isArray()) { // Array
assertThat(attribute.getJavaType(), is(equalTo(getArrayType(expectedData))));
assertThat(attribute.isEmpty(), is(false));
assertThat(attribute.isScalar(), is(false));
} else { // Scalar
assertThat(attribute.getJavaType(), is(equalTo(expectedData.getClass())));
assertThat(attribute.isEmpty(), is(false));
assertThat(attribute.isScalar(), is(true));
assertThat(attribute.getSize(), is(1L));
}
if (!node.isLink()) {
assertThat(attribute.getNode(), is(sameInstance(node)));
}
};
}
private Executable createTest(ByteBuffer buffer, FloatingPoint dataType, int[] dims, Object expected) {
return () -> {
buffer.rewind(); // For shared buffers
HdfFileChannel hdfFc = mock(HdfFileChannel.class);
Object actual = dataType.fillData(buffer, dims, hdfFc);
assertThat(actual, is(expected));
verifyNoInteractions(hdfFc);
};
}