org.skyscreamer.jsonassert.JSONAssert Java Examples
The following examples show how to use
org.skyscreamer.jsonassert.JSONAssert.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AgentStatusReportExecutorTest.java From docker-elastic-agents-plugin with Apache License 2.0 | 6 votes |
@Test public void shouldGetAgentStatusReportWithJobIdentifier() throws Exception { JobIdentifier jobIdentifier = new JobIdentifier("up42", 2L, "label", "stage1", "1", "job", 1L); AgentStatusReportRequest agentStatusReportRequest = new AgentStatusReportRequest(null, jobIdentifier, clusterProfileConfigurations); AgentStatusReport agentStatusReport = new AgentStatusReport(jobIdentifier, "elastic-agent-id", null, null, null, null, null, new HashMap<>(), new ArrayList<>()); DockerContainer dockerContainer = new DockerContainer("id", "name", jobIdentifier, new Date(), new HashMap<>(), null); when(dockerContainers.find(jobIdentifier)).thenReturn(Optional.ofNullable(dockerContainer)); when(dockerContainers.getAgentStatusReport(clusterProfile, dockerContainer)).thenReturn(agentStatusReport); when(viewBuilder.getTemplate("agent-status-report.template.ftlh")).thenReturn(template); when(viewBuilder.build(template, agentStatusReport)).thenReturn("agentStatusReportView"); GoPluginApiResponse goPluginApiResponse = new AgentStatusReportExecutor(agentStatusReportRequest, pluginRequest, dockerContainers, viewBuilder) .execute(); JsonObject expectedResponseBody = new JsonObject(); expectedResponseBody.addProperty("view", "agentStatusReportView"); assertThat(goPluginApiResponse.responseCode(), is(200)); JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true); }
Example #2
Source File: SchemaGeneratorCustomDefinitionsTest.java From jsonschema-generator with Apache License 2.0 | 6 votes |
@Test @Parameters(source = SchemaVersion.class) public void testGenerateSchema_CircularCustomStandardDefinition(SchemaVersion schemaVersion) throws Exception { String accessProperty = "get(0)"; CustomDefinitionProviderV2 customDefinitionProvider = (javaType, context) -> { if (!javaType.isInstanceOf(List.class)) { return null; } ResolvedType generic = context.getTypeContext().getContainerItemType(javaType); SchemaGeneratorConfig config = context.getGeneratorConfig(); return new CustomDefinition(config.createObjectNode() .put(config.getKeyword(SchemaKeyword.TAG_TYPE), config.getKeyword(SchemaKeyword.TAG_TYPE_OBJECT)) .set(config.getKeyword(SchemaKeyword.TAG_PROPERTIES), config.createObjectNode() .set(accessProperty, context.createDefinitionReference(generic)))); }; SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion); configBuilder.forTypesInGeneral() .withCustomDefinitionProvider(customDefinitionProvider); SchemaGenerator generator = new SchemaGenerator(configBuilder.build()); JsonNode result = generator.generateSchema(TestCircularClass1.class); JSONAssert.assertEquals('\n' + result.toString() + '\n', TestUtils.loadResource(this.getClass(), "circular-custom-definition-" + schemaVersion.name() + ".json"), result.toString(), JSONCompareMode.STRICT); }
Example #3
Source File: CommonGTest.java From bdt with Apache License 2.0 | 6 votes |
@Test public void modifyDataAddToJsonNumberTest_3() throws Exception { ThreadProperty.set("class", this.getClass().getCanonicalName()); CommonG commong = new CommonG(); JSONObject jsonObject = new JSONObject(); jsonObject.put("key1", new JSONArray(Arrays.asList("value1"))); String data = jsonObject.toString(); String expectedData = "{\"key1\":[\"value1\",0]}"; String type = "json"; List<List<String>> rawData = Arrays.asList(Arrays.asList("key1", "ADDTO", "0", "number")); DataTable modifications = DataTable.create(rawData); String modifiedData = commong.modifyData(data, type, modifications); JSONAssert.assertEquals(expectedData, modifiedData, false); }
Example #4
Source File: BulkExportJobRestTest.java From FHIR with Apache License 2.0 | 6 votes |
@Test public void testBulkExportJobInstanceRequestEmpty() throws Exception { String jsonString = "{}"; String expected = "{}"; try (InputStream in = new ByteArrayInputStream(jsonString.getBytes())) { JobInstanceRequest parsedObj = JobInstanceRequest.Parser.parse(in); String str = JobInstanceRequest.Writer.generate(parsedObj, false); JSONAssert.assertEquals(expected, str, false); } catch (Exception e) { fail("failed to parse", e); } }
Example #5
Source File: PaymentRequestTest.java From moip-sdk-java-le with MIT License | 6 votes |
@Test public void testPaymentWithOnlineDebit() throws JSONException { PaymentRequest payment = new PaymentRequest() .orderId("ORD-VN1DD41V9G45") .installmentCount(1) .fundingInstrument( new FundingInstrumentRequest() .onlineBankDebit(new OnlineBankDebitRequest() .bankNumber("341") .expirationDate(new ApiDateRequest().date(new GregorianCalendar(2020, Calendar.AUGUST, 10).getTime())) .returnUri("https://moip.com.br/") ) ); String paymentJSON = new Gson().toJson(payment); JsonObject expectedJSON = getJsonFileAsJsonObject("payment/create_online_debit.json"); JSONAssert.assertEquals(expectedJSON.toString(), paymentJSON, false); }
Example #6
Source File: TransformationServiceTest.java From data-prep with Apache License 2.0 | 6 votes |
@Test public void noAction() throws Exception { // given String dataSetId = createDataset("input_dataset.csv", "uppercase", "text/csv"); String preparationId = createEmptyPreparationFromDataset(dataSetId, "uppercase prep"); // when String transformedContent = given() // .when() // .get("/apply/preparation/{preparationId}/dataset/{datasetId}/{format}", preparationId, dataSetId, "JSON") // .asString(); // then String expectedContent = IOUtils.toString(this.getClass().getResourceAsStream("no_action_expected.json"), UTF_8); JSONAssert.assertEquals(expectedContent, transformedContent, false); }
Example #7
Source File: AuthConfigValidateRequestExecutorTest.java From github-oauth-authorization-plugin with Apache License 2.0 | 6 votes |
@Test public void shouldValidateGitHubEnterpriseUrl() throws Exception { when(request.requestBody()).thenReturn("{\n" + " \"ClientId\": \"client-id\",\n" + " \"AllowedOrganizations\": \"example-1,example-2\",\n" + " \"AuthenticateWith\": \"GitHubEnterprise\",\n" + " \"ClientSecret\": \"client-secret\",\n" + " \"PersonalAccessToken\": \"Foobar\"\n" + "}"); GoPluginApiResponse response = AuthConfigValidateRequest.from(request).execute(); String expectedJSON = "[\n" + " {\n" + " \"key\": \"GitHubEnterpriseUrl\",\n" + " \"message\": \"GitHubEnterpriseUrl must not be blank.\"\n" + " }\n" + "]"; JSONAssert.assertEquals(expectedJSON, response.responseBody(), JSONCompareMode.NON_EXTENSIBLE); }
Example #8
Source File: JsonValueTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Deployment(resources = ONE_TASK_PROCESS) public void testGetTypedJsonValue() throws JSONException { // given JsonValue jsonValue = jsonValue(jsonString).create(); VariableMap variables = Variables.createVariables().putValueTyped(variableName, jsonValue); String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); // when JsonValue typedValue = runtimeService.getVariableTyped(processInstanceId, variableName); // then SpinJsonNode value = typedValue.getValue(); JSONAssert.assertEquals(jsonString, value.toString(), true); assertTrue(typedValue.isDeserialized()); assertEquals(JSON, typedValue.getType()); assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); JSONAssert.assertEquals(jsonString, typedValue.getValueSerialized(), true); }
Example #9
Source File: JsonbHttpMessageConverterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test @SuppressWarnings("unchecked") public void writeParameterizedBaseType() throws Exception { ParameterizedTypeReference<List<MyBean>> beansList = new ParameterizedTypeReference<List<MyBean>>() {}; ParameterizedTypeReference<List<MyBase>> baseList = new ParameterizedTypeReference<List<MyBase>>() {}; String body = "[{\"bytes\":[1,2],\"array\":[\"Foo\",\"Bar\"]," + "\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8)); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); List<MyBean> results = (List<MyBean>) converter.read(beansList.getType(), null, inputMessage); assertEquals(1, results.size()); MyBean result = results.get(0); assertEquals("Foo", result.getString()); assertEquals(42, result.getNumber()); assertEquals(42F, result.getFraction(), 0F); assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); assertTrue(result.isBool()); assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, baseList.getType(), new MediaType("application", "json"), outputMessage); JSONAssert.assertEquals(body, outputMessage.getBodyAsString(StandardCharsets.UTF_8), true); }
Example #10
Source File: ClusterStatusReportExecutorTest.java From docker-elastic-agents-plugin with Apache License 2.0 | 6 votes |
@Test public void shouldGetStatusReport() throws Exception { StatusReport statusReport = aStatusReport(); when(clusterStatusReportRequest.getClusterProfile()).thenReturn(clusterProfile); when(dockerContainers.getStatusReport(clusterProfile)).thenReturn(statusReport); when(viewBuilder.getTemplate("status-report.template.ftlh")).thenReturn(template); when(viewBuilder.build(template, statusReport)).thenReturn("statusReportView"); ClusterStatusReportExecutor statusReportExecutor = new ClusterStatusReportExecutor(clusterStatusReportRequest, dockerContainers, viewBuilder); GoPluginApiResponse goPluginApiResponse = statusReportExecutor.execute(); JsonObject expectedResponseBody = new JsonObject(); expectedResponseBody.addProperty("view", "statusReportView"); assertThat(goPluginApiResponse.responseCode(), is(200)); JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true); }
Example #11
Source File: FlexDeserializeSerializeTest.java From line-bot-sdk-java with Apache License 2.0 | 6 votes |
@SuppressWarnings("GrazieInspection") private DynamicTest testResource(final Path resource) { return dynamicTest(resource.getFileName().toString(), () -> { final FileInputStream fileInputStream = new FileInputStream(resource.toFile()); final String json = copyToString(fileInputStream, StandardCharsets.UTF_8); log.debug("JSON : {}", json); final FlexContainer flexContainer = mapper.readValue(json, FlexContainer.class); log.debug("Deserialized : {}", flexContainer); final String jsonReconstructed = mapper.writeValueAsString(flexContainer); log.debug("Re-Serialized JSON : {}", jsonReconstructed); JSONAssert.assertEquals(json, jsonReconstructed, true); }); }
Example #12
Source File: JsonValueIT.java From camunda-external-task-client-java with Apache License 2.0 | 6 votes |
@Test public void shouldGetTypedJson() throws JSONException { // given engineRule.startProcessInstance(processDefinition.getId(), VARIABLE_NAME_JSON, VARIABLE_VALUE_JSON_VALUE); // when client.subscribe(EXTERNAL_TASK_TOPIC_FOO) .handler(handler) .open(); // then clientRule.waitForFetchAndLockUntil(() -> !handler.getHandledTasks().isEmpty()); ExternalTask task = handler.getHandledTasks().get(0); JsonValue typedValue = task.getVariableTyped(VARIABLE_NAME_JSON); assertThat(typedValue.getType()).isEqualTo(JSON); JSONAssert.assertEquals(VARIABLE_VALUE_JSON_SERIALIZED, typedValue.getValue(), true); }
Example #13
Source File: QueryConverterIT.java From sql-to-mongo-db-query-converter with Apache License 2.0 | 6 votes |
@Test public void countGroupByQueryHavingByCountAlias() throws ParseException, IOException, JSONException { QueryConverter queryConverter = new QueryConverter.Builder().sqlString("select cuisine, count(cuisine) as cc from "+COLLECTION+" WHERE borough = 'Manhattan' GROUP BY cuisine HAVING cc > 500").build(); QueryResultIterator<Document> distinctIterable = queryConverter.run(mongoDatabase); queryConverter.write(System.out); List<Document> results = Lists.newArrayList(distinctIterable); assertEquals(4, results.size()); JSONAssert.assertEquals("[{\n" + " \"cuisine\": \"Chinese\",\n" + " \"cc\": 510\n" + "}," + "{\n" + " \"cuisine\": \"Italian\",\n" + " \"cc\": 621\n" + "}," + "{\n" + " \"cuisine\": \"Café/Coffee/Tea\",\n" + " \"cc\": 680\n" + "}," + "{\n" + " \"cuisine\": \"American \",\n" + " \"cc\": 3205\n" + "}]",toJson(results),false); }
Example #14
Source File: QueryConverterIT.java From sql-to-mongo-db-query-converter with Apache License 2.0 | 6 votes |
@Test public void simpleSubqueryAliasGroup_WhereProjectGroupSort() throws ParseException, JSONException, IOException { QueryConverter queryConverter = new QueryConverter.Builder().sqlString("select c.cuisine, sum(c.c) as c from(select borough, cuisine, count(*) as c from "+COLLECTION+" group by borough, cuisine) as c where c.c > 500 group by c.cuisine order by cuisine desc ").build(); QueryResultIterator<Document> distinctIterable = queryConverter.run(mongoDatabase); List<Document> results = Lists.newArrayList(distinctIterable); assertEquals(4, results.size()); JSONAssert.assertEquals("[{\n" + " \"c\": 621,\n" + " \"cuisine\": \"Italian\"\n" + "},{\n" + " \"c\": 2001,\n" + " \"cuisine\": \"Chinese\"\n" + "},{\n" + " \"c\": 680,\n" + " \"cuisine\": \"Café/Coffee/Tea\"\n" + "},{\n" + " \"c\": 5518,\n" + " \"cuisine\": \"American \"\n" + "}]",toJson(results),false); }
Example #15
Source File: JsonbHttpMessageConverterTests.java From java-technology-stack with MIT License | 6 votes |
@Test @SuppressWarnings("unchecked") public void readAndWriteGenerics() throws Exception { Field beansList = ListHolder.class.getField("listField"); String body = "[{\"bytes\":[1,2],\"array\":[\"Foo\",\"Bar\"]," + "\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8)); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); Type genericType = beansList.getGenericType(); List<MyBean> results = (List<MyBean>) converter.read(genericType, MyBeanListHolder.class, inputMessage); assertEquals(1, results.size()); MyBean result = results.get(0); assertEquals("Foo", result.getString()); assertEquals(42, result.getNumber()); assertEquals(42F, result.getFraction(), 0F); assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); assertTrue(result.isBool()); assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, genericType, new MediaType("application", "json"), outputMessage); JSONAssert.assertEquals(body, outputMessage.getBodyAsString(StandardCharsets.UTF_8), true); }
Example #16
Source File: TimeseriesMeanValueFieldTest.java From TomboloDigitalConnector with MIT License | 6 votes |
@Test public void testJsonValueForSubjectWithMultipleValues() throws Exception { TestFactory.makeTimedValue(subject.getSubjectType(), "E01000001", attribute, "2011-01-01T00:00", 100d); TestFactory.makeTimedValue(subject.getSubjectType(), "E01000001", attribute, "2011-01-02T00:00", 200d); String jsonString = field.jsonValueForSubject(subject, true).toJSONString(); JSONAssert.assertEquals("{" + " aLabel: [" + " {" + " value: 100," + " timestamp: '2011-01-01T00:00:00'" + " }," + " {" + " value: 200," + " timestamp: '2011-01-02T00:00:00'" + " }" + " ]," + " aLabel Mean: 150" + "}", jsonString, false); }
Example #17
Source File: IntegrationTest.java From jsonschema-generator with Apache License 2.0 | 6 votes |
/** * Test * * @throws Exception */ @Test public void testIntegration() throws Exception { // active all optional modules JavaxValidationModule module = new JavaxValidationModule( JavaxValidationOption.NOT_NULLABLE_FIELD_IS_REQUIRED, JavaxValidationOption.NOT_NULLABLE_METHOD_IS_REQUIRED, JavaxValidationOption.INCLUDE_PATTERN_EXPRESSIONS); SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(new ObjectMapper(), SchemaVersion.DRAFT_2019_09) .with(module) .build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode result = generator.generateSchema(TestClass.class); String rawJsonSchema = result.toString(); JSONAssert.assertEquals('\n' + rawJsonSchema + '\n', loadResource("integration-test-result.json"), rawJsonSchema, JSONCompareMode.STRICT); }
Example #18
Source File: QueryConverterIT.java From sql-to-mongo-db-query-converter with Apache License 2.0 | 5 votes |
@Test public void simpleSubqueryAlias_Project() throws ParseException, JSONException, IOException { QueryConverter queryConverter = new QueryConverter.Builder().sqlString("select c.borough from(select borough, cuisine from "+COLLECTION+" order by restaurant_id asc limit 1) as c").build(); QueryResultIterator<Document> distinctIterable = queryConverter.run(mongoDatabase); List<Document> results = Lists.newArrayList(distinctIterable); assertEquals(1, results.size()); JSONAssert.assertEquals("[{\n" + " \"borough\" : \"Bronx\"\n" + "}]",toJson(results),false); }
Example #19
Source File: JsonSerializationTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test @Deployment(resources = ONE_TASK_PROCESS) public void testSerializationAsJson() throws JSONException { ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); JsonSerializable bean = new JsonSerializable("a String", 42, true); // request object to be serialized as JSON runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(JSON_FORMAT_NAME).create()); // validate untyped value Object value = runtimeService.getVariable(instance.getId(), "simpleBean"); assertEquals(bean, value); // validate typed value ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); assertEquals(ValueType.OBJECT, typedValue.getType()); assertTrue(typedValue.isDeserialized()); assertEquals(bean, typedValue.getValue()); assertEquals(bean, typedValue.getValue(JsonSerializable.class)); assertEquals(JsonSerializable.class, typedValue.getObjectType()); assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); assertEquals(JsonSerializable.class.getName(), typedValue.getObjectTypeName()); JSONAssert.assertEquals(bean.toExpectedJsonString(), new String(typedValue.getValueSerialized()), true); }
Example #20
Source File: JsonSubTypesResolverCustomDefinitionsTest.java From jsonschema-generator with Apache License 2.0 | 5 votes |
private void assertCustomDefinitionsAreEqual(String customDefinition, CustomDefinition result, CustomDefinition.DefinitionType definitionType) throws Exception { if (customDefinition == null) { Assert.assertNull(result); } else { Assert.assertNotNull(result); Assert.assertNotNull(result.getValue()); JSONAssert.assertEquals('\n' + result.getValue().toString() + '\n', customDefinition, result.getValue().toString(), JSONCompareMode.STRICT); Assert.assertEquals(definitionType, result.getDefinitionType()); Assert.assertEquals(CustomDefinition.AttributeInclusion.NO, result.getAttributeInclusion()); } }
Example #21
Source File: QueryConverterIT.java From sql-to-mongo-db-query-converter with Apache License 2.0 | 5 votes |
@Test public void sumQueryAliasWhere() throws ParseException, JSONException, IOException { QueryConverter queryConverter = new QueryConverter.Builder().sqlString("select sum(_id) as s from "+COLLECTION_FILMS+" where Category = 'Sports'").build(); QueryResultIterator<Document> distinctIterable = queryConverter.run(mongoDatabase); List<Document> results = Lists.newArrayList(distinctIterable); JSONAssert.assertEquals("[{\n" + " \"s\": 39584\n" + "}]",toJson(results),false); }
Example #22
Source File: CommonGTest.java From bdt with Apache License 2.0 | 5 votes |
@Test public void modifyDataArrayAddNullTest() throws Exception{ String data = "[{\"businessAssets\":{\"id\":1},\"metadataPath\":\"\",\"description\":\"\",\"id\":-1,\"name\":\"\"}]"; String expectedData = "[{\"businessAssets\":{\"id\":1},\"metadataPath\":\"\",\"description\":\"\",\"id\":-1,\"name\":\"\",\"key\":null}]"; CommonG commong = new CommonG(); String type = "json"; List<List<String>> rawData = Arrays.asList(Arrays.asList("$.[0].key", "ADD", "null", "null")); DataTable modifications = DataTable.create(rawData); String modifiedData = commong.modifyData(data, type, modifications); JSONAssert.assertEquals(expectedData, modifiedData, false); }
Example #23
Source File: ProfileValidateRequestExecutorTest.java From kubernetes-elastic-agents with Apache License 2.0 | 5 votes |
@Test public void shouldValidateMandatoryKeysForConfigProperties() throws Exception { Map<String, String> properties = new HashMap<>(); properties.put("PodSpecType", "properties"); ProfileValidateRequestExecutor executor = new ProfileValidateRequestExecutor(new ProfileValidateRequest(properties)); String json = executor.execute().responseBody(); JSONAssert.assertEquals("[{\"message\":\"Image must not be blank.\",\"key\":\"Image\"}]", json, JSONCompareMode.NON_EXTENSIBLE); }
Example #24
Source File: ClusterProfilePropertiesValidateRequestExecutorTest.java From docker-elastic-agents-plugin with Apache License 2.0 | 5 votes |
@Test public void shouldValidateMandatoryKeys() throws Exception { ClusterProfileValidateRequestExecutor executor = new ClusterProfileValidateRequestExecutor(new ClusterProfileValidateRequest(Collections.<String, String>emptyMap())); String json = executor.execute().responseBody(); String expectedStr = "[" + " {\"message\":\"Go Server URL must not be blank.\",\"key\":\"go_server_url\"}," + " {\"message\":\"max_docker_containers must not be blank.\",\"key\":\"max_docker_containers\"}," + " {\"message\":\"docker_uri must not be blank.\",\"key\":\"docker_uri\"}," + " {\"message\":\"auto_register_timeout must not be blank.\",\"key\":\"auto_register_timeout\"}" + "]\n"; JSONAssert.assertEquals(expectedStr, json, JSONCompareMode.NON_EXTENSIBLE); }
Example #25
Source File: CommonGTest.java From bdt with Apache License 2.0 | 5 votes |
@Test public void modifyDataArrayReplaceStringTest() throws Exception{ String data = "[{\"businessAssets\":{\"id\":1},\"metadataPath\":\"\",\"description\":\"\",\"id\":-1,\"name\":\"\"}]"; String expectedData = "[{\"businessAssets\":{\"id\":1},\"metadataPath\":\"\",\"description\":\"\",\"id\":-1,\"name\":\"newname\"}]"; CommonG commong = new CommonG(); String type = "json"; List<List<String>> rawData = Arrays.asList(Arrays.asList("$.[0].name", "REPLACE", "newname", "string")); DataTable modifications = DataTable.create(rawData); String modifiedData = commong.modifyData(data, type, modifications); JSONAssert.assertEquals(expectedData, modifiedData, false); }
Example #26
Source File: TodoControllerTest.java From Mastering-Spring-5.1 with MIT License | 5 votes |
@Test public void retrieveTodos() throws Exception { List<Todo> mockList = Arrays.asList(new Todo(1, "Jack", "Learn Spring MVC", new Date(), false), new Todo(2, "Jack", "Learn Struts", new Date(), false)); when(service.retrieveTodos(anyString())).thenReturn(mockList); MvcResult result = mvc .perform(MockMvcRequestBuilders.get("/users/Jack/todos").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); String expected = "[" + "{id:1,user:Jack,desc:\"Learn Spring MVC\",done:false}" + "," + "{id:2,user:Jack,desc:\"Learn Struts\",done:false}" + "]"; JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false); }
Example #27
Source File: DummyArtifactPluginTest.java From go-plugins with Apache License 2.0 | 5 votes |
@Test void shouldValidateFetchArtifactConfig() throws UnhandledRequestTypeException, JSONException { final GoPluginApiRequest request = mock(GoPluginApiRequest.class); when(request.requestName()).thenReturn(RequestFromServer. REQUEST_FETCH_ARTIFACT_VALIDATE.getRequestName()); when(request.requestBody()).thenReturn("{}"); final GoPluginApiResponse response = new DummyArtifactPlugin().handle(request); final String expectedJson = "[{\"key\":\"Path\",\"message\":\"must be provided.\"}]"; assertThat(response.responseCode()).isEqualTo(200); JSONAssert.assertEquals(expectedJson,response.responseBody(),true); }
Example #28
Source File: ClusterProfileValidateRequestExecutorTest.java From kubernetes-elastic-agents with Apache License 2.0 | 5 votes |
@Test public void shouldBarfWhenUnknownKeysArePassed() throws Exception { Map<String, String> properties = new HashMap<>(); properties.put("foo", "bar"); properties.put("go_server_url", "https://foobar.com/go"); properties.put("kubernetes_cluster_url", "something"); properties.put("security_token", "something"); ClusterProfileValidateRequestExecutor executor = new ClusterProfileValidateRequestExecutor(new ClusterProfileValidateRequest(properties), mock(PluginRequest.class)); String json = executor.execute().responseBody(); JSONAssert.assertEquals("[{\"key\":\"foo\",\"message\":\"Is an unknown property\"}]", json, JSONCompareMode.NON_EXTENSIBLE); }
Example #29
Source File: SendTest.java From messenger4j with MIT License | 5 votes |
@Test void shouldSendReusableImageAttachmentMessageWithUrl() throws Exception { // tag::send-ImageMessageUrlReusable[] final IdRecipient recipient = IdRecipient.create("USER_ID"); final NotificationType notificationType = NotificationType.NO_PUSH; final String imageUrl = "https://petersapparel.com/img/shirt.png"; final UrlRichMediaAsset richMediaAsset = UrlRichMediaAsset.create(IMAGE, new URL(imageUrl), of(true)); final RichMediaMessage richMediaMessage = RichMediaMessage.create(richMediaAsset); final MessagePayload payload = MessagePayload.create( recipient, MessagingType.RESPONSE, richMediaMessage, of(notificationType), empty()); messenger.send(payload); // end::send-ImageMessageUrlReusable[] final ArgumentCaptor<String> payloadCaptor = ArgumentCaptor.forClass(String.class); final String expectedJsonBody = "{\"recipient\":{\"id\":\"USER_ID\"}," + "\"notification_type\":\"NO_PUSH\"," + "\"messaging_type\":\"RESPONSE\"," + "\"message\":{\"attachment\":{" + "\"type\":\"image\"," + "\"payload\":{\"url\":\"https://petersapparel.com/img/shirt.png\",\"is_reusable\":true}" + "}}}"; verify(mockHttpClient).execute(eq(POST), endsWith(PAGE_ACCESS_TOKEN), payloadCaptor.capture()); JSONAssert.assertEquals(expectedJsonBody, payloadCaptor.getValue(), true); }
Example #30
Source File: ApplicationTest.java From prebid-server-java with Apache License 2.0 | 5 votes |
@Test public void biddersParamsShouldReturnBidderSchemas() throws JSONException { // given final Map<String, JsonNode> bidderNameToSchema = getBidderNamesFromParamFiles().stream() .collect(Collectors.toMap(Function.identity(), ApplicationTest::jsonSchemaToJsonNode)); // when final Response response = given(SPEC) .when() .get("/bidders/params"); // then JSONAssert.assertEquals(bidderNameToSchema.toString(), response.asString(), JSONCompareMode.NON_EXTENSIBLE); }