下面列出了怎么用org.junit.jupiter.api.Assertions的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Verifies you can't modify values().
*/
@Test
public void testImmutabilityViaValues() {
ConsumerPartition expectedTopicPartition = new ConsumerPartition("MyTopic", 12);
Long expectedOffset = 3444L;
final ConsumerState.ConsumerStateBuilder builder = ConsumerState.builder();
final ConsumerState consumerState = builder
.withPartition(expectedTopicPartition, expectedOffset)
.build();
// Sanity check
assertEquals(3444L, (long) consumerState.getOffsetForNamespaceAndPartition(expectedTopicPartition), "Has expected offset");
assertEquals(1, consumerState.size(), "Size should be 1");
// Test using values
Assertions.assertThrows(UnsupportedOperationException.class, () ->
consumerState.values().remove(3444L)
);
}
@Test
void testAbsNaN() {
// The result is NaN if either argument is NaN and the other is not infinite
Assertions.assertEquals(nan, NAN.abs());
Assertions.assertEquals(nan, Complex.ofCartesian(3.0, nan).abs());
Assertions.assertEquals(nan, Complex.ofCartesian(nan, 3.0).abs());
// The result is positive infinite if either argument is infinite
Assertions.assertEquals(inf, Complex.ofCartesian(inf, nan).abs());
Assertions.assertEquals(inf, Complex.ofCartesian(-inf, nan).abs());
Assertions.assertEquals(inf, Complex.ofCartesian(nan, inf).abs());
Assertions.assertEquals(inf, Complex.ofCartesian(nan, -inf).abs());
Assertions.assertEquals(inf, Complex.ofCartesian(inf, 3.0).abs());
Assertions.assertEquals(inf, Complex.ofCartesian(-inf, 3.0).abs());
Assertions.assertEquals(inf, Complex.ofCartesian(3.0, inf).abs());
Assertions.assertEquals(inf, Complex.ofCartesian(3.0, -inf).abs());
}
@Test
public void testBlock()
{
Assertions.assertEquals("Hello", markdown.compute("```Hello```"));
Assertions.assertEquals("```Hello", markdown.compute("```Hello"));
Assertions.assertEquals("\\```Hello```", markdown.compute("\\```Hello```"));
Assertions.assertEquals("Hello **World**", markdown.compute("```Hello **World**```"));
Assertions.assertEquals("```Hello World", markdown.compute("```Hello **World**"));
Assertions.assertEquals("\\```Hello World```", markdown.compute("\\```Hello **World**```"));
Assertions.assertEquals("Hello `to` World", markdown.compute("```Hello `to` World```"));
Assertions.assertEquals("```Hello to World", markdown.compute("```Hello `to` World"));
Assertions.assertEquals("\\```Hello to World```", markdown.compute("\\```Hello `to` World```"));
Assertions.assertEquals("Test", markdown.compute("```java\nTest```"));
}
@Test
public void testSerialize() {
Assertions.assertEquals(
"{" +
"\"testbyte\":5b" + "," +
"\"testshort\":78s" + "," +
"\"testint\":555" + "," +
"\"testlong\":125l" + "," +
"\"testfloat\":26.55f" + "," +
"\"testdouble\":125.111d" + "," +
"\"testqnstring\":\"111\"" + "," +
"\"testuqstring\":\"uc\"" + "," +
"\"testqwsstring\":\"w s\"" + "," +
"\"testqestring\":\"\\\\\\\"\"" + "," +
"\"testba\":[B;1b,6b,73b,67b]" + "," +
"\"testia\":[I;1,6,6]" + "," +
"\"testla\":[L;6l,77l,888l]" + "," +
"\"testilist\":[1,10]" + "," +
"\"testslist\":[\";111\",\"111\",\"uc\",\"w s\"]" + "," +
"\"testcompound\":{\"test\":1s}" +
"}",
MojangsonSerializer.serialize(tag)
);
}
@Test
public void testRemove() throws NoAvailableSlaveException, ObjectNotFoundException {
Properties p = new Properties();
p.put("1.assign", "slave2-remove");
p.put("1.match", "/path1/*");
ScoreChart sc = new ScoreChart(Arrays.asList(rslaves));
Filter f = new MatchdirFilter(1, p);
f.process(sc, null, null, Transfer.TRANSFER_SENDING_DOWNLOAD, new DirectoryHandle("/path1/dir/file.txt"), null);
assertEquals(0, sc.getScoreForSlave(rslaves[0]).getScore());
assertEquals(0, sc.getScoreForSlave(rslaves[2]).getScore());
try {
sc.getScoreForSlave(rslaves[1]);
Assertions.fail("should not be called");
} catch (ObjectNotFoundException success) {
//success
}
}
@Test
final void testQuaternionEquals() {
final double inc = 1e-5;
final Quaternion q1 = Quaternion.of(2, 1, -4, -2);
final Quaternion q2 = Quaternion.of(q1.getW() + inc, q1.getX(), q1.getY(), q1.getZ());
final Quaternion q3 = Quaternion.of(q1.getW(), q1.getX() + inc, q1.getY(), q1.getZ());
final Quaternion q4 = Quaternion.of(q1.getW(), q1.getX(), q1.getY() + inc, q1.getZ());
final Quaternion q5 = Quaternion.of(q1.getW(), q1.getX(), q1.getY(), q1.getZ() + inc);
Assertions.assertFalse(q1.equals(q2, 0.9 * inc));
Assertions.assertFalse(q1.equals(q3, 0.9 * inc));
Assertions.assertFalse(q1.equals(q4, 0.9 * inc));
Assertions.assertFalse(q1.equals(q5, 0.9 * inc));
Assertions.assertTrue(q1.equals(q2, 1.1 * inc));
Assertions.assertTrue(q1.equals(q3, 1.1 * inc));
Assertions.assertTrue(q1.equals(q4, 1.1 * inc));
Assertions.assertTrue(q1.equals(q5, 1.1 * inc));
}
@Test
public void shouldGetStorage() throws Exception {
StorageInfoDTO dto = new StorageInfoDTO();
dto.setNumAccounts(1);
dto.setNumBlocks(2);
dto.setNumTransactions(3);
mockRemoteCall(dto);
StorageInfo storageInfo = repository.getNodeStorage().toFuture()
.get();
Assertions.assertEquals(dto.getNumAccounts(), storageInfo.getNumAccounts());
Assertions.assertEquals(dto.getNumBlocks(), storageInfo.getNumBlocks());
Assertions
.assertEquals(dto.getNumTransactions(), storageInfo.getNumTransactions());
}
@Test
public void testCreateOrReplace() throws IOException {
String jsonObject = "{\"apiVersion\": \"test.fabric8.io/v1alpha1\",\"kind\": \"Hello\"," +
"\"metadata\": {\"resourceVersion\":\"1\", \"name\": \"example-hello\"},\"spec\": {\"size\": 3}}";
server.expect().post().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos").andReturn(HttpURLConnection.HTTP_INTERNAL_ERROR, new StatusBuilder().build()).once();
server.expect().post().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos").andReturn(HttpURLConnection.HTTP_CREATED, jsonObject).once();
server.expect().post().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos").andReturn(HttpURLConnection.HTTP_CONFLICT, jsonObject).once();
server.expect().put().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/example-hello").andReturn(HttpURLConnection.HTTP_OK, jsonObject).once();
KubernetesClient client = server.getClient();
KubernetesClientException exception = Assertions.assertThrows(KubernetesClientException.class,
() -> client.customResource(customResourceDefinitionContext).createOrReplace("ns1", jsonObject));
assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, exception.getCode());
Map<String, Object> resource = client.customResource(customResourceDefinitionContext).createOrReplace("ns1", jsonObject);
assertEquals("example-hello", ((Map<String, Object>)resource.get("metadata")).get("name").toString());
resource = client.customResource(customResourceDefinitionContext).createOrReplace("ns1", jsonObject);
assertEquals("example-hello", ((Map<String, Object>)resource.get("metadata")).get("name").toString());
}
/**
* Test calling getConnectString() after calling start on the service.
*/
@Test
void testGetConnectString() throws Exception {
// Create instance.
try (final ZookeeperTestServer zookeeperTestServer = new ZookeeperTestServer()) {
// Start service.
zookeeperTestServer.start();
// Ask for the connect String
final String connectString = zookeeperTestServer.getConnectString();
Assertions.assertNotNull(connectString);
// Validate the zookeeper server appears to be functioning.
testZookeeperConnection(connectString);
}
}
@Test
public void shouldContainComponent() {
KubernetesList list = Serialization.unmarshalAsList(ComponentSpringBootExampleTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/halkyon.yml"));
assertNotNull(list);
List<HasMetadata> items = list.getItems();
Assertions.assertEquals(1, items.size());
Component component = (Component) items.get(0);
Assertions.assertEquals("Component", component.getKind());
// This doesn't work during release.
//assertEquals("https://github.com/dekorateio/dekorate.git", component.getSpec().getBuildConfig().getUrl());
assertEquals("docker", component.getSpec().getBuildConfig().getType());
assertEquals("feat-229-override-annotationbased-config", component.getSpec().getBuildConfig().getModuleDirName());
// This may be null during the release process where HEAD point to a commit instead of a branch.
//assertNotNull("", component.getSpec().getBuildConfig().getRef());
assertEquals(DeploymentMode.build, component.getSpec().getDeploymentMode());
Map<String, String> labels = component.getMetadata().getLabels();
Assertions.assertNotNull(labels.get("key1-from-properties"));
Assertions.assertEquals("val1-from-properties", labels.get("key1-from-properties"));
Assertions.assertEquals("hello-world", component.getMetadata().getName());
}
@Test
public void loops() {
CKClassResult c = report.get("wmc.CC8");
Assertions.assertEquals(3, c.getMethod("m0/0").get().getWmc());
Assertions.assertEquals(6, c.getMethod("m1/0").get().getWmc());
Assertions.assertEquals(6, c.getMethod("m2/0").get().getWmc());
Assertions.assertEquals(6, c.getMethod("m3/0").get().getWmc());
Assertions.assertEquals(2, c.getMethod("m4/0").get().getWmc());
Assertions.assertEquals(3, c.getMethod("m5/0").get().getWmc());
Assertions.assertEquals(6, c.getMethod("m6/0").get().getWmc());
Assertions.assertEquals(3+6+6+6+2+3+6, c.getWmc());
}
@Test
void addCameraPropertyListenerUseWeakReference() {
final WeakReference<CameraPropertyListener> weakReference = new WeakReference<>(cameraPropertyListener);
cameraPropertyEventLogic().addCameraPropertyListener(cameraPropertyListener);
cameraPropertyEventLogic().addCameraPropertyListener(fakeCamera, cameraPropertyListener);
cameraPropertyListener = null;
int i = 0;
while (weakReference.get() != null && i < 100) {
System.gc();
sleep(10);
i++;
}
Assertions.assertNull(weakReference.get(), "cameraPropertyEventLogic is holding a strong ref to listener");
sendAndAssertCountEvent(2,0);
}
@Test
void validateStartRoute102() {
PropertyFactory.get()
.register("startShell/startRoute",
true,
true,
false,
false);
Assertions.assertTrue(RouteValidation.validateStartRoute(this.shellConfiguration,
this.routerConfiguration,
"/error/show"));
}
@Test
void testMosaicRestrictionTypeEnumToMosaicRestrictionType() {
Set<Integer> existingValues = new HashSet<>();
Arrays.stream(MosaicRestrictionTypeEnum.values()).forEach(v -> {
Assertions.assertNotNull(MosaicRestrictionType.rawValueOf(v.getValue().byteValue()), v.name());
Assertions.assertTrue(existingValues.add(v.getValue()), v.getValue() + " is duplicated!!");
});
}
@Test
public void getTransactionStatements2Recipients() {
Statement statement = getStatement();
TransactionStatement transactionStatement = statement.getTransactionStatements().get(1);
Assertions.assertEquals("41BF730BD307EB507880CA0576A4CCEFEF95F3060DC334CA364AE737114D1F60",
transactionStatement.generateHash().toUpperCase());
Assertions.assertEquals(5, transactionStatement.getReceipts().size());
Assertions.assertEquals(
ReceiptType.NAMESPACE_RENTAL_FEE, transactionStatement.getReceipts().get(0).getType());
Assertions.assertEquals("85BBEA6CC462B244",
((BalanceTransferReceipt) transactionStatement.getReceipts().get(0)).getMosaicId()
.getIdAsHex());
Assertions.assertEquals(ReceiptType.MOSAIC_EXPIRED,
transactionStatement.getReceipts().get(1).getType());
Assertions.assertEquals(MosaicId.class,
((ArtifactExpiryReceipt) transactionStatement.getReceipts().get(1)).getArtifactId()
.getClass());
Assertions.assertEquals(ReceiptType.NAMESPACE_EXPIRED,
transactionStatement.getReceipts().get(2).getType());
Assertions.assertEquals(NamespaceId.class,
((ArtifactExpiryReceipt) transactionStatement.getReceipts().get(2)).getArtifactId()
.getClass());
Assertions.assertEquals(ReceiptType.NAMESPACE_DELETED,
transactionStatement.getReceipts().get(3).getType());
Assertions.assertEquals(NamespaceId.class,
((ArtifactExpiryReceipt) transactionStatement.getReceipts().get(3)).getArtifactId()
.getClass());
Assertions.assertEquals(ReceiptType.INFLATION,
transactionStatement.getReceipts().get(4).getType());
Assertions.assertEquals(333,
((InflationReceipt) transactionStatement.getReceipts().get(4)).getAmount().longValue());
}
@Test
@DisplayName("Page boots correctly, and displays index.html")
public void UI_contains_correct_heading() throws IOException {
ValidatorGui.start(new CliContext(), null, false);
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--disable-gpu");
WebDriver driver = new ChromeDriver(options);
driver.get("http://localhost:" + ValidatorGui.getPort() + "/home");
Assertions.assertTrue(driver.getPageSource().contains(HTML_TITLE_TAG));
driver.quit();
ValidatorGui.stop();
}
@Test
void assertCreatedUsingNamespaceIdAndSettingMosaicId() {
MosaicId mosaicId = new MosaicId(BigInteger.TEN);
NamespaceId namespaceId = NamespaceId.createFromName("mycurrency");
NetworkCurrency networkCurrency = new NetworkCurrencyBuilder(
namespaceId, 6).withSupplyMutable(false)
.withTransferable(true).withMosaicId(mosaicId).build();
Assertions.assertEquals(namespaceId, networkCurrency.getNamespaceId().get());
Assertions.assertEquals(namespaceId, networkCurrency.getUnresolvedMosaicId());
assertEquals(mosaicId, networkCurrency.getMosaicId().get());
}
@Test
void mergeArrays() {
String[] merged = {
"a", "b", "c",
"a", "b", "c", null
};
Assertions.assertArrayEquals(merged, ArrayUtils.mergeArrays(ARRAY, ARRAY_WITH_NULL));
Assertions.assertArrayEquals(merged, ArrayUtils.mergeArrays(String[]::new, ARRAY, ARRAY_WITH_NULL));
}
@Test
void updateProjectWithIdOne() throws MalformedURLException, ProjectIsBeingProcessedException {
UpdateProjectController testSubject = new UpdateProjectController(updateProjectUseCase);
UpdateProjectCommand command =
new UpdateProjectCommand(
"new name", "username", "password", "http://valid.url", true, new Date());
ResponseEntity<HttpStatus> responseEntity = testSubject.updateProject(command, 1L);
Mockito.verify(updateProjectUseCase, Mockito.times(1)).update(command, 1L);
Assertions.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}
/**
* 测试用例: 测试createContestContestant(Contest, User)方法.
* 测试数据: 使用合法的数据, 并且数据库中不存在相同的记录.
* 预期结果: 参赛记录被成功创建.
*/
@Test
public void testCreateContestContestantNormally() {
Contest contest = contestMapper.getContest(2);
User contestant = userMapper.getUserUsingUid(1002);
ContestContestant cc = new ContestContestant(contest, contestant);
int numberOfRowsAffected = contestContestantMapper.createContestContestant(cc);
Assertions.assertEquals(1, numberOfRowsAffected);
}
@Override
public void assertExtraction(@NotNull final Extraction extraction) {
Assertions.assertEquals(1, extraction.getCodeLocations().size());
NameVersionGraphAssert graphAssert = new NameVersionGraphAssert(Forge.GOLANG, extraction.getCodeLocations().get(0).getDependencyGraph());
graphAssert.hasRootSize(2);
graphAssert.hasRootDependency("github.com/golang/example", "0dea2d0bf90754ffa40e0cb2f23b638f3e3d7e09");
graphAssert.hasRootDependency("crypto", "9756ffdc24725223350eb3266ffb92590d28f278");
}
@Test
void testExecuteStepPhaseWithHooksBefore() {
Module moduleToDeploy = createModule("test-module");
Mockito.when(moduleDeterminer.determineModuleToDeploy(context))
.thenReturn(moduleToDeploy);
List<Hook> hooksForExecution = Collections.singletonList(createHook("test-hook"));
Mockito.when(hooksExecutor.executeBeforeStepHooks(context.getVariable(Variables.STEP_PHASE)))
.thenReturn(hooksForExecution);
Assertions.assertEquals(StepPhase.EXECUTE, step.executeAsyncStep(context));
}
@Test
public void usesModelDiscoveryWithCustomInvalidClasspath() {
CliError e = Assertions.assertThrows(CliError.class, () -> {
String dir = getClass().getResource("invalid.jar").getPath();
SmithyCli.create().run("validate", "--debug", "--discover-classpath", dir);
});
assertThat(e.getMessage(), containsString("1 ERROR(s)"));
}
@Test
public void isStartAnchored() {
Assertions.assertTrue(PatternMatcher.compile("^abc").isStartAnchored());
Assertions.assertTrue(PatternMatcher.compile("^[a-z]").isStartAnchored());
Assertions.assertTrue(PatternMatcher.compile("(^a|^b)").isStartAnchored());
Assertions.assertFalse(PatternMatcher.compile("(^a|b)").isStartAnchored());
Assertions.assertFalse(PatternMatcher.compile("abc").isStartAnchored());
}
@Test
public void testSchema() {
RequestSpecification request = RestAssured.given();
request.accept(MEDIATYPE_TEXT);
request.contentType(MEDIATYPE_TEXT);
Response response = request.get("/graphql/schema.graphql");
String body = response.body().asString();
LOG.error(body);
Assertions.assertEquals(200, response.statusCode());
Assertions.assertTrue(body.contains("\"Query root\""));
Assertions.assertTrue(body.contains("type Query {"));
Assertions.assertTrue(body.contains("ping: TestPojo"));
}
@Test
public void decompressEmpty() throws IOException {
Map<String, List<String>> headers = new HashMap<>();
headers.put("Content-Type", Collections.singletonList("application/json"));
headers.put("Content-Encoding", Collections.singletonList("gzip"));
HttpResponse res = new HttpResponse(200, headers);
Assertions.assertEquals("", res.decompress().entityAsString());
Assertions.assertEquals(0, res.decompress().entity().length);
}
@Test
public void testUnderline()
{
Assertions.assertEquals("Hello", markdown.compute("__Hello__"));
Assertions.assertEquals("__Hello", markdown.compute("__Hello"));
Assertions.assertEquals("\\__Hello__", markdown.compute("\\__Hello__"));
}
@Test
public void withTagEnumNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
Enum<?> value = null;
new DefaultId("test").withTag("enum", value);
});
}
@ParameterizedTest
@EnumSource(RepositoryType.class)
void getNamespacesFromAccounts(RepositoryType type) {
Account account = config().getDefaultAccount();
List<NamespaceInfo> namespacesInfo = get(getNamespaceRepository(type)
.getNamespacesFromAccounts(
Collections.singletonList(
account.getAddress())));
namespacesInfo.forEach(n -> {
Assertions.assertEquals(account.getAddress(), n.getOwnerAddress());
});
}
@Test
void testDescriptor()
{
String value = "path/to/application.xml";
ObjectNode options = JsonNodeFactory.instance.objectNode();
ArrayList<String> result = new ArrayList<>();
parser.parse(AIRPlatform.AIR, false, value, "content.swf", options, result);
Assertions.assertEquals(4, result.indexOf(value));
}