src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
SeedExtractor { public Seeds extract() { Select stmt = null; try { stmt = (Select) CCJSqlParserUtil.parse(sql); } catch (JSQLParserException e) { throw new RuntimeException(e); } Seeds seeds = new Seeds(); stmt.getSelectBody().accept(new SeedVisitor(seeds)); return seeds; } SeedExtractor(String sql); Seeds extract(); ... | @Test public void extractNothing() { Seeds seeds = new SeedExtractor("select * from table where age = age2").extract(); Assert.assertTrue(seeds.getLongs().isEmpty()); Assert.assertTrue(seeds.getStrings().isEmpty()); Assert.assertTrue(seeds.getDoubles().isEmpty()); seeds = new SeedExtractor("select * from table").extrac... |
SqlSecurer { public String getSecureSql() { sql = sql.replaceAll("(?i)(?!`)([\\s\\.]?)primary([\\s\\.?])(?!`)", "$1`primary`$2"); sql = sql.replaceAll("(?i)AS '(.*?)'", "AS \"$1\""); sql = sql.replaceAll("(?i)([\\s(])DATE\\((.*?)\\)", "$1TIMESTAMP($2)"); sql = sql.replaceAll("(?i)\\sFOR UPDATE", ""); sql = sql.replaceA... | @Test public void secureSelectAllQuery() { String sql = new SqlSecurer("SELECT * FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT * FROM \"Table\""); }
@Test public void secureSelectColumnsQuery() { String sql = new SqlSecurer("SELECT Column1, Column2, Column3 FROM Table").getSecureSql(); Assert.assertEqua... |
DBTypeSelector { public DBType create(int dataType, int length) { switch (dataType) { case Types.DOUBLE: return new DBDouble(); case Types.REAL: return new DBDouble("REAL"); case Types.DECIMAL: return new DBDouble("DECIMAL"); case Types.INTEGER: return new DBInteger(); case Types.SMALLINT: return new DBInteger("SMALLIN... | @Test void dbBooleanTest() { assertThat(dbTypeSelector.create(Types.BIT, 0)).isInstanceOf(DBBoolean.class); assertThat(dbTypeSelector.create(Types.BOOLEAN, 0)).isInstanceOf(DBBoolean.class); }
@Test void dbDateTest() { assertThat(dbTypeSelector.create(Types.DATE, 0)).isInstanceOf(DBDate.class); }
@Test void dbDateTimeT... |
DBDouble implements DBType { static String truncateDecimals(double value, int decimals) { StringBuilder builder = new StringBuilder("0"); if (decimals > 0) builder.append('.'); for (int i = 0; i < decimals; i++) builder.append('#'); DecimalFormat df = new DecimalFormat(builder.toString(), defaultDecimalFormatSymbols); ... | @Test void truncateDecimals() { assertThat(DBDouble.truncateDecimals(3, 4)).isEqualTo("3"); assertThat(DBDouble.truncateDecimals(4.52, 1)).isEqualTo("4.5"); assertThat(DBDouble.truncateDecimals(4.58, 1)).isEqualTo("4.5"); assertThat(DBDouble.truncateDecimals(5.1, 3)).isEqualTo("5.1"); }
@Test void truncateDecimals_loca... |
Fixture implements Cloneable { public String prettyPrint() { StringBuilder prettyFixture = new StringBuilder(); for (FixtureTable table : tables) { prettyFixture.append("-- Table: " + table.getName() + "\n"); Iterator<FixtureRow> it = table.getRows().iterator(); int rowCount = 1; while (it.hasNext()) { FixtureRow row =... | @Test public void prettyPrint() { TableSchema t1Schema = Mockito.mock(TableSchema.class); Mockito.when(t1Schema.getName()).thenReturn("t1"); FixtureRow r1 = new FixtureRow("t1", t1Schema); r1.set("c1", "1"); r1.set("c2", "Mauricio"); FixtureRow r2 = new FixtureRow("t1", t1Schema); r2.set("c1", "2"); r2.set("c2", "Jeroe... |
Pipeline { public void execute() { Result queryRunnerResult = queryRunner.runQuery(sqlQuery, connectionData); Map<Generator, List<Output>> outputCache = new HashMap<>(); for (ResultProcessor rp : resultProcessors) { List<Output> generatedOutputs; if (outputCache.containsKey(rp.getGenerator())) { generatedOutputs = outp... | @Test @DisplayName("Methods should not be called more than once") void pipelineTest() { final QueryRunner queryRunner = mock(QueryRunner.class); final String sql = "Select * From any;"; final ConnectionData connectionData = new ConnectionData("", "", "", ""); final Result result = mock(Result.class); when(queryRunner.r... |
JUnitGeneratorHelper { public MethodSpec buildRunSqlImplementation() { MethodSpec.Builder runSql = MethodSpec.methodBuilder(METHOD_RUN_SQL) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(RETURN_TYPE_RUN_SQL) .addParameter(String.class, "query") .addParameter(TypeName.BOOLEAN, "isUpdate") .addException(SQLExc... | @Test void runSqlImplementationTest() { JUnitGeneratorHelper helper = new JUnitGeneratorHelper(); String expected = "\n" + "private static java.util.ArrayList<java.util.HashMap<java.lang.String, java.lang.String>> runSql(\n" + " java.lang.String query, boolean isUpdate) throws java.sql.SQLException {\n" + " java.sql.Co... |
JUnitGeneratorHelper { public MethodSpec buildRunSqlEmpty() { MethodSpec.Builder runSql = MethodSpec.methodBuilder(METHOD_RUN_SQL) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(RETURN_TYPE_RUN_SQL) .addParameter(String.class, "query") .addParameter(TypeName.BOOLEAN, "isUpdate") .addException(SQLException.cl... | @Test void runSqlEmptyTest() { JUnitGeneratorHelper helper = new JUnitGeneratorHelper(); String expected = "\n" + "private static java.util.ArrayList<java.util.HashMap<java.lang.String, java.lang.String>> runSql(\n" + " java.lang.String query, boolean isUpdate) throws java.sql.SQLException {\n" + " " return null;\n" + ... |
JUnitGeneratorHelper { public MethodSpec buildMapMaker() { MethodSpec.Builder mapMaker = MethodSpec.methodBuilder(METHOD_MAP_MAKER) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(ParameterizedTypeName.get(HashMap.class, String.class, String.class)) .addParameter(String[].class, "strings") .varargs() .addJava... | @Test void mapMakerTest() { JUnitGeneratorHelper helper = new JUnitGeneratorHelper(); String expected = "\n" + "private static java.util.HashMap<java.lang.String, java.lang.String> makeMap(\n" + " java.lang.String... strings) {\n" + " java.util.HashMap<java.lang.String, java.lang.String> result = new java.util.HashMap<... |
JUnitGeneratorHelper { public MethodSpec buildGetResultColumns() { MethodSpec.Builder getResultColumns = MethodSpec.methodBuilder(METHOD_GET_RESULT_COLUMNS) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(ParameterizedTypeName.get(List.class, String.class)) .addParameter(ResultSet.class, "result") .addExcepti... | @Test void getResultColumnsTest() { JUnitGeneratorHelper helper = new JUnitGeneratorHelper(); String expected = "\n" + "private static java.util.List<java.lang.String> getResultColumns(java.sql.ResultSet result) throws\n" + " java.sql.SQLException {\n" + " java.sql.ResultSetMetaData meta = result.getMetaData();\n" + " ... |
JUnitGeneratorSettings { public static JUnitGeneratorSettings getDefault( ConnectionData connectionData, String filePackage, String className) { return new JUnitGeneratorSettings( connectionData, filePackage, className, true, true, true, false, true ); } static JUnitGeneratorSettings getDefault(
Connection... | @Test void staticDefaultMethod() { ConnectionData connectionData = new ConnectionData("", "", "", ""); JUnitGeneratorSettings settings = JUnitGeneratorSettings.getDefault( connectionData, "pack", "className"); assertThat(settings.getConnectionData()).isSameAs(connectionData); assertThat(settings.getFilePackage()).isEqu... |
EvoSQLRunner implements QueryRunner { @Override public Result runQuery(@NonNull String sqlQuery, @NonNull ConnectionData connectionData) { EvoSQL evoSQL = evoSQLFactory.createEvoSQL(connectionData); nl.tudelft.serg.evosql.Result evoSQLResult = evoSQL.execute(sqlQuery); return convertResult(evoSQLResult); } @Override R... | @Test void testRunQueryFail() { assertThatNullPointerException().isThrownBy(() -> { new EvoSQLRunner().runQuery(null, Mockito.mock(ConnectionData.class)); }); assertThatNullPointerException().isThrownBy(() -> { new EvoSQLRunner().runQuery("Select * From all", null); }); }
@Test void runQueryTest() { EvoSQL evoSQL = Moc... |
EvoSQLRunner implements QueryRunner { Result convertResult(nl.tudelft.serg.evosql.Result evoSqlResult) { return new Result( evoSqlResult.getInputQuery(), evoSqlResult.getPathResults().stream() .filter(pr -> pr.getFixture() != null) .filter(pr -> pr.isSuccess()) .map(this::convertPathResult) .collect(Collectors.toList()... | @Test void conversionTest() { Result result = new Result("Select * From table", 0); result.getPathResults().add(buildPathResult(1)); result.getPathResults().add(buildPathResult(2)); EvoSQLRunner evoSQLRunner = new EvoSQLRunner(); nl.tudelft.serg.evosql.brew.data.Result brewResult = evoSQLRunner.convertResult(result); a... |
EvoSQLFactory { public EvoSQL createEvoSQL(ConnectionData connectionData) { return new EvoSQL( connectionData.getConnectionString(), connectionData.getDatabase(), connectionData.getUsername(), connectionData.getPassword(), false); } EvoSQL createEvoSQL(ConnectionData connectionData); } | @Test void createEvoSQLTest() { ConnectionData connectionData = new ConnectionData("cs", "db", "user", "pass"); EvoSQLFactory evoSQLFactory = new EvoSQLFactory(); assertThat(evoSQLFactory.createEvoSQL(connectionData)).isInstanceOf(EvoSQL.class); } |
ExistingDataRunner implements QueryRunner { @Override public Result runQuery(String sqlQuery, ConnectionData connectionData) { return result; } @Override Result runQuery(String sqlQuery, ConnectionData connectionData); } | @Test void testRunQuerySame() { final Result expected = Mockito.mock(Result.class); Result actual = new ExistingDataRunner(expected).runQuery(null, null); assertThat(actual).isSameAs(expected); }
@Test void testRunQueryNull() { final Result expected = null; Result actual = new ExistingDataRunner(expected).runQuery(null... |
FileConsumer implements OutputConsumer { @Override public void consumeOutput(List<Output> outputs) { try { Files.createDirectories(directory); for (Output output : outputs) { File outfile = Paths.get(directory.toString(), output.getName()).toFile(); FileOutputStream outStream = fileOutputStreamProvider.createStream(out... | @Test void ioExceptionTest() throws FileNotFoundException { final IOException ioException = new IOException(); FileConsumer.FileOutputStreamProvider fileOutputStreamProvider = Mockito.mock(FileConsumer.FileOutputStreamProvider.class); Mockito.when(fileOutputStreamProvider.createStream(Mockito.any())).then(invocation ->... |
TableCreationBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return path.getFixture().getTables().stream().map(table -> { StringBuilder createBuilder = new StringBuilder(); createBuilder.append("CREATE TABLE "); createBuilder.append(getVendorOptions().escapeIdentifier(table.getSch... | @Test void createTableMySQLStringTestSmall() { String expected = "CREATE TABLE `table1` (`column1_1` INTEGER, `column1_2` DOUBLE, `column1_3` VARCHAR(100));"; TableCreationBuilder tableCreationBuilder = new TableCreationBuilder(new MySQLOptions()); assertThat(tableCreationBuilder.buildQueries(pathsSmall.get(0)).get(0))... |
QueryBuilder { protected String getEscapedValue(FixtureColumn fixtureColumn, FixtureRow fixtureRow) { String value = fixtureRow.getValues().get(fixtureColumn.getName()); if (value == null || "NULL".equals(value)) { return "NULL"; } if (!numericSqlTypes.contains(fixtureColumn.getType())) { return "'" + value.replaceAll(... | @Test void testGetEscapedValueNull() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(new FixtureColumn("nulltest", "STRING"), fixtureRow)) .isEqualTo("NULL"); }
@Test void testInteger() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(fixt... |
SelectionBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return Collections.singletonList(path.getPathSql()); } SelectionBuilder(VendorOptions vendorOptions); @Override List<String> buildQueries(Path path); } | @Test void selectionBuilderTestSmall() { SelectionBuilder selectionBuilder = new SelectionBuilder(new MySQLOptions()); Result result1 = DataGenerator.makeResult1(); assertThat(selectionBuilder.buildQueries(result1.getPaths().get(0))) .isEqualTo(Collections.singletonList(result1.getPaths().get(0).getPathSql())); }
@Test... |
CleaningBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return path.getFixture().getTables().stream().map(table -> { StringBuilder truncateBuilder = new StringBuilder(); truncateBuilder.append("TRUNCATE TABLE "); truncateBuilder.append(getVendorOptions().escapeIdentifier(table.get... | @Test void truncateTableMySQLStringTest() { String expected = "TRUNCATE TABLE `table1`;"; CleaningBuilder cleaningBuilder = new CleaningBuilder(new MySQLOptions()); assertThat(cleaningBuilder.buildQueries(pathsSmall.get(0)).get(0)).isEqualTo(expected); }
@Test void truncateTablePostgreSQLTest() { String expected = "TRU... |
InsertionBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return path.getFixture().getTables().stream().map(table -> { StringBuilder insertBuilder = new StringBuilder(); insertBuilder.append("INSERT INTO "); insertBuilder.append(getVendorOptions().escapeIdentifier(table.getSchema()... | @Test void result1Test() { Result result1 = DataGenerator.makeResult1(); InsertionBuilder insertionBuilder = new InsertionBuilder(new MySQLOptions()); List<String> insertionQueries = insertionBuilder.buildQueries(result1.getPaths().get(0)); List<String> expectedQueries = Arrays.asList( "INSERT INTO `table1` (`column1_1... |
PostgreSQLOptions implements VendorOptions { @Override public String escapeIdentifier(String id) { return "\"" + id + "\""; } @Override String escapeIdentifier(String id); } | @Test void testStandard() { VendorOptions postgreSQLOptions = new PostgreSQLOptions(); assertThat(postgreSQLOptions.escapeIdentifier("table")).isEqualTo("\"table\""); }
@Test void testSpace() { VendorOptions postgreSQLOptions = new PostgreSQLOptions(); assertThat(postgreSQLOptions.escapeIdentifier("table space")).isEqu... |
MySQLOptions implements VendorOptions { @Override public String escapeIdentifier(String id) { return "`" + id + "`"; } @Override String escapeIdentifier(String id); } | @Test void testNormal() { VendorOptions mySQLOptions = new MySQLOptions(); assertThat(mySQLOptions.escapeIdentifier("table")).isEqualTo("`table`"); }
@Test void testSpace() { VendorOptions mySQLOptions = new MySQLOptions(); assertThat(mySQLOptions.escapeIdentifier("table space")).isEqualTo("`table space`"); }
@Test voi... |
DestructionBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return path.getFixture().getTables().stream().map(table -> { StringBuilder destructionBuilder = new StringBuilder(); destructionBuilder.append("DROP TABLE "); destructionBuilder.append(getVendorOptions().escapeIdentifier(t... | @Test void dropTableMySQLStringTestSmall() { String expected = "DROP TABLE `table1`;"; DestructionBuilder destructionBuilder = new DestructionBuilder(new MySQLOptions()); assertThat(destructionBuilder.buildQueries(pathsSmall.get(0)).get(0)).isEqualTo(expected); }
@Test void dropTablePostgreSQLTestSmall() { String expec... |
Vector3D { public static float[] vectorMultiply(float[] lhs, float[] rhs) { float[] result = new float[3]; result[x] = lhs[y]*rhs[z] - lhs[z]*rhs[y]; result[y] = lhs[z]*rhs[x] - lhs[x]*rhs[z]; result[z] = lhs[x]*rhs[y] - lhs[y]*rhs[x]; return result; } static float[] vectorMultiply(float[] lhs, float[] rhs); static fl... | @Test public void vectorMultiply() throws Exception { float vec1[] = {1, 0, 0}; float vec2[] = {0, 1, 0}; float res[] = Vector3D.vectorMultiply(vec1, vec2); assertTrue(vectorEqual(res, new float[] {0, 0, 1})); res = Vector3D.vectorMultiply(vec2, vec1); assertTrue(vectorEqual(res, new float[] {0, 0, -1})); float[] vec3 ... |
Vector3D { public static float scalarMultiply(float[] lhs, float[] rhs) { return lhs[x]*rhs[x] + lhs[y]*rhs[y] + lhs[z]*rhs[z]; } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] right); static float vect... | @Test public void scalarMultiply() throws Exception { float vec1[] = {1, 0, 0}; float vec2[] = {0, 1, 0}; float res = Vector3D.scalarMultiply(vec1, vec2); assertTrue(equal(res, 0)); float v3[] = {5, 0, 0}; float v4[] = {3, -1, 0}; res = Vector3D.scalarMultiply(v3, v4); assertTrue(equal(res, 15)); } |
Vector3D { public static float distanceVertices(float[] left, float[] right) { float sum = 0; for (int i = 0; i < 3; i++) { sum += (left[i] - right[i])*(left[i] - right[i]); } return (float) Math.sqrt(sum); } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs)... | @Test public void distanceVertices() throws Exception { float[] start = {0, 1, 0, 1}; float[] end = {5, 1, 0, 1}; float[] vertex = {3, 0, 0, 1}; float res = Vector3D.distanceVertices(start, end); assertTrue(equal(res, 5)); res = Vector3D.distanceVertices(start, vertex); assertTrue(equal(res, 3.1623f)); } |
Vector3D { public static float vectorLength(float[] vector) { return (float) Math.sqrt(vector[x]*vector[x] + vector[y]*vector[y] + vector[z]*vector[z]); } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] ... | @Test public void vectorLength() throws Exception { } |
Vector3D { public static float[] createVector(float[] start, float[] end) { float[] res = new float[4]; for (int i = 0; i < 3; i++) { res[i] = end[i] - start[i]; } res[w] = 0; return res; } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float dist... | @Test public void createVector() throws Exception { } |
Vector3D { public static float distanceDotLine(float[] dot, float[] lineA, float[] lineB) { float[] v_l = createVector(lineA, lineB); float[] w = createVector(lineA, dot); float[] mul = vectorMultiply(v_l, w); return vectorLength(mul)/vectorLength(v_l); } static float[] vectorMultiply(float[] lhs, float[] rhs); static... | @Test public void distanceDotLine() throws Exception { } |
Vector3D { public static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd) { float[] vecSegment = createVector(segmentStart, segmentEnd); float[] vecDot = createVector(segmentStart, dot); float scalarMul = scalarMultiply(vecSegment, vecDot); if ((Math.abs(scalarMul) < Epsilon) || (scala... | @Test public void distanceVertexSegment() throws Exception { float[] start = {0, 1, 0, 1}; float[] end = {5, 1, 0, 1}; float[] vertex = {3, 0, 0, 1}; float res = Vector3D.distancevertexSegment(vertex, start, end); assertTrue(equal(res, 1)); float[] vertex2 = {0, 0, 0}; res = Vector3D.distancevertexSegment(vertex2, star... |
ProductEventConsumer extends AbstractKafkaConsumer { @KafkaListener(topics = "${eventing.topic_name}") public void listen(final ConsumerRecord<String, String> consumerRecord, final Acknowledgment ack) { super.handleConsumerRecord(consumerRecord, ack); } @Inject protected ProductEventConsumer(ProductEventProcessor mess... | @Test public void eventWithSyntaxErrorShouldNeitherBeProcessedNorStoredAsUnprocessable() { productEventConsumer = new ProductEventConsumer(mockedProcessor(SUCCESS), unprocessableEventService); productEventConsumer.listen(CONSUMER_RECORD,ack); verify(ack).acknowledge(); verify(unprocessableEventService, never()).save(an... |
ApiVerticle extends AbstractVerticle { private void getProducts(RoutingContext rc) { catalogService.getProducts(ar -> { if (ar.succeeded()) { List<Product> products = ar.result(); JsonArray json = new JsonArray(); products.stream() .map(Product::toJson) .forEach(json::add); rc.response() .putHeader("Content-type", "app... | @Test public void testGetProducts(TestContext context) throws Exception { String itemId1 = "111111"; JsonObject json1 = new JsonObject() .put("itemId", itemId1) .put("name", "productName1") .put("desc", "productDescription1") .put("price", new Double(100.0)); String itemId2 = "222222"; JsonObject json2 = new JsonObject... |
ApiVerticle extends AbstractVerticle { private void getProduct(RoutingContext rc) { String itemId = rc.request().getParam("itemid"); catalogService.getProduct(itemId, ar -> { if (ar.succeeded()) { Product product = ar.result(); if (product != null) { rc.response() .putHeader("Content-type", "application/json") .end(pro... | @Test public void testGetProduct(TestContext context) throws Exception { String itemId = "111111"; JsonObject json = new JsonObject() .put("itemId", itemId) .put("name", "productName1") .put("desc", "productDescription1") .put("price", new Double(100.0)); Product product = new Product(json); doAnswer(new Answer<Void>()... |
ApiVerticle extends AbstractVerticle { private void addProduct(RoutingContext rc) { JsonObject json = rc.getBodyAsJson(); catalogService.addProduct(new Product(json), ar -> { if (ar.succeeded()) { rc.response().setStatusCode(201).end(); } else { rc.fail(ar.cause()); } }); } ApiVerticle(CatalogService catalogService); @... | @Test public void testAddProduct(TestContext context) throws Exception { doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<String>> handler = invocation.getArgument(1); handler.handle(Future.succeededFuture(null)); return null; } }).when(catalogService).addProduct(any(),... |
FileEventStorage implements InteractionContextSink, Closeable { String serialize(InteractionContext interactionContext) throws JsonProcessingException { return mapper.writeValueAsString(interactionContext); } FileEventStorage(ObjectMapper mapper); @Override void apply(InteractionContext interactionContext); void load(F... | @Test public void givenInteractionContextWithEventWhenSerializeThenIsSerialized() throws JsonProcessingException { List<Event> events = new ArrayList<>(); events.add(new ChangedDescriptionEvent() {{ description = "Hello World"; }}); events.add(new ChangedDescriptionEvent() {{ description = "Hello World2"; }}); Map<Stri... |
FileEventStorage implements InteractionContextSink, Closeable { InteractionContext deserialize(String line) throws IOException { return mapper.readValue(line, InteractionContext.class); } FileEventStorage(ObjectMapper mapper); @Override void apply(InteractionContext interactionContext); void load(File file, EventStore ... | @Test public void givenEventStringWhenDeserializeThenInteractionContextDeserialized() throws IOException { String json = "{\"type\":\"task\",\"version\":1,\"timestamp\":12345,\"id\":1," + "\"attributes\":{\"user\":\"rickard\"},\"events\":[{\"type\":\"com.github.rickardoberg.stuff.event" + ".ChangedDescriptionEvent\",\"... |
InboxModel implements InteractionContextSink { public abstract Map<Identifier, InboxTask> getTasks(); abstract Map<Identifier, InboxTask> getTasks(); } | @Test public void givenEmptyModelWhenCreatedTaskThenModelHasTask() { InboxModel model = new InMemoryInboxModel(); List<Event> events = new ArrayList<>(); Identifier id = new Identifier(0); events.add(new CreatedEvent()); InteractionContext context = new InteractionContext("task", -1, new Date(), Collections.<String, St... |
Inbox { public static Function<Inbox, Function<NewTask, Task>> newTask() { return inbox -> newTask -> { Task task = new Task(newTask.id); inbox.select(task); changeDescription().apply(inbox).apply(newTask.changeDescription); return task; }; } void select(Task task); static Function<Inbox, Function<NewTask, Task>> newT... | @Test public void givenInboxWhenCreateNewTaskThenNewTaskCreated() { Inbox inbox = new Inbox(); Inbox.ChangeDescription changeDescription = new Inbox.ChangeDescription(); changeDescription.description = "Description"; Inbox.NewTask newTask = new Inbox.NewTask(); newTask.changeDescription = changeDescription; Interaction... |
Version { public String toString() { return mMajor + "." + mMinor + "." + mBuild; } Version(String versionString); boolean isEqualTo(Version compareVersion); boolean isLowerThan(Version compareVersion); boolean ishIGHERThan(Version compareVersion); int getMajor(); int getMinor(); int getBuild(); String toString(); } | @Test public void toStringTest() { String testVersion = "7.0.0"; Version version = new Version(testVersion); assertEquals(version.toString(), testVersion); } |
JsonBindingExample extends JsonData { public Book deserializeBook() { return JsonbBuilder.create().fromJson(bookJson, Book.class); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); Stri... | @Test public void givenJSON_shouldDeserializeBook() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); Book book = jsonBindingExample.deserializeBook(); assertThat(book).isEqualTo(book1); } |
JsonBindingExample extends JsonData { public String bookAdapterToJson() { JsonbConfig jsonbConfig = new JsonbConfig().withAdapters(new BookletAdapter()); Jsonb jsonb = JsonbBuilder.create(jsonbConfig); return jsonb.toJson(book1); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Boo... | @Test @Ignore("adapter missing") public void givenAdapter_shouldSerialiseJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.bookAdapterToJson(); String json = "{\"isbn\":\"1234567890\",\"bookTitle\":\"Professional Java EE Design Patterns\",\"firstName\":\"Alex\... |
JsonBindingExample extends JsonData { public Book bookAdapterToBook() { JsonbConfig jsonbConfig = new JsonbConfig().withAdapters(new BookletAdapter()); Jsonb jsonb = JsonbBuilder.create(jsonbConfig); String json = "{\"isbn\":\"1234567890\",\"bookTitle\":\"Professional Java EE Design Patterns\",\"firstName\":\"Alex\",\"... | @Test @Ignore("Book adapter missing") public void givenAdapter_shouldDeserialiseJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); Book book = jsonBindingExample.bookAdapterToBook(); assertThat(book).isEqualTo(bookAdapted); } |
EnumExample { public String enumSerialisationInObject() { return JsonbBuilder.create().toJson(new container()); } String enumSerialisation(); String enumSerialisationInObject(); } | @Test public void enumSerialisationInObject() { String expectedJson = "{\"binding\":\"Hard Back\"}"; EnumExample enumExample = new EnumExample(); String actualJson = enumExample.enumSerialisationInObject(); assertThat(actualJson).isEqualTo(expectedJson); } |
EnumExample { public String enumSerialisation() { return JsonbBuilder.create().toJson(Binding.HARD_BACK.name()); } String enumSerialisation(); String enumSerialisationInObject(); } | @Test @Ignore public void givenEnum_shouldThrownExceptionWhenSerialised() { new EnumExample().enumSerialisation(); } |
ComprehensiveExample { public String serialiseMagazine() throws MalformedURLException { Magazine magazine = new Magazine(); magazine.setId("ABCD-1234"); magazine.setTitle("Fun with Java"); magazine.setAuthor(new Author("Alex", "Theedom")); magazine.setPrice(45.00f); magazine.setPages(300); magazine.setInPrint(true); ma... | @Test @Ignore("failing test fix!") public void givenMagazine_shouldSerialiseToJson() throws MalformedURLException { String expectedJson = "{\"author\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"},\"binding\":\"SOFT_BACK\",\"id\":\"ABCD-1234\",\"inPrint\":true,\"languages\":[\"French\",\"English\",\"Spanish\",null]... |
ComprehensiveExample { public Magazine deserialiseMagazine() { String json = "{\"author\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"},\"binding\":\"SOFT_BACK\",\"id\":\"ABCD-1234\",\"inPrint\":true,\"languages\":[\"French\",\"English\",\"Spanish\",null],\"pages\":300,\"price\":45.0,\"published\":\"2018-01-01\",\"... | @Test public void givenJson_shouldDeserialiseToMagazine() throws MalformedURLException { Magazine expectedMagazine = new Magazine(); expectedMagazine.setId("ABCD-1234"); expectedMagazine.setTitle("Fun with Java"); expectedMagazine.setAuthor(new Author("Alex", "Theedom")); expectedMagazine.setPrice(45.00f); expectedMaga... |
NestedClassExample { public String serializeNestedClasses() { OuterClass.InnerClass innerClass = new OuterClass().new InnerClass(); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(innerClass); return json; } String serializeNestedClasses(); OuterClass.InnerClass deserialiseNestedClasses(); } | @Test public void givenNestedInnerClass_shouldSerializeNestedClasses() { String expectedJson = "{\"name\":\"Inner Class\"}"; NestedClassExample nestedClassExample = new NestedClassExample(); String actualJson = nestedClassExample.serializeNestedClasses(); assertThat(actualJson).isEqualTo(expectedJson); } |
NestedClassExample { public OuterClass.InnerClass deserialiseNestedClasses() { String json = "{\"name\":\"Inner Class\"}"; OuterClass.InnerClass innerClass = JsonbBuilder.create().fromJson(json, OuterClass.InnerClass.class); return innerClass; } String serializeNestedClasses(); OuterClass.InnerClass deserialiseNestedC... | @Test @Ignore public void givenJson_shouldDeserialiseToNestedClass() { OuterClass.InnerClass expectedInner = new OuterClass().new InnerClass(); NestedClassExample nestedClassExample = new NestedClassExample(); OuterClass.InnerClass actualInnerClass = nestedClassExample.deserialiseNestedClasses(); assertThat(actualInner... |
MinimalExample { public String serializeBook() { Book book = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(book); return json; } String serializeBook(); Book deserializeBook(); } | @Test public void givenBookInstance_shouldSerialiseToJSONString() { String expectedJson = "{\"author\":\"Alex Theedom\",\"id\":\"SHDUJ-4532\",\"title\":\"Fun with Java\"}"; MinimalExample minimalExample = new MinimalExample(); String actualJson = minimalExample.serializeBook(); assertThat(actualJson).isEqualTo(expected... |
MinimalExample { public Book deserializeBook() { Book book = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(book); book = jsonb.fromJson(json, Book.class); return book; } String serializeBook(); Book deserializeBook(); } | @Test public void givenJSONString_shouldDeserializeToBookObject() { Book expectedBook = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); MinimalExample minimalExample = new MinimalExample(); Book actualBook = minimalExample.deserializeBook(); assertThat(actualBook).isEqualTo(expectedBook); } |
JsonBindingExample extends JsonData { public String serializeBook() { return JsonbBuilder.create().toJson(book1); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapp... | @Test public void givenBookObject_shouldSerializeToJSONString() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeBook(); assertThat(json).isEqualToIgnoringCase(bookJson); } |
JsonPointerExample { public String find() { JsonPointer pointer = Json.createPointer("/topics/1"); JsonString jsonValue = (JsonString) pointer.getValue(jsonObject); return jsonValue.getString(); } String find(); String replace(); String add(); } | @Test public void givenPointerToTopic_shouldReturnTopic() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.find(); assertThat(topic).isEqualToIgnoringCase("Cloud"); } |
JsonPointerExample { public String replace() { JsonPointer pointer = Json.createPointer("/topics/1"); JsonObject newJsonObject = pointer.replace(jsonObject, Json.createValue("Big Data")); JsonString jsonValue = (JsonString) pointer.getValue(newJsonObject); return jsonValue.getString(); } String find(); String replace(... | @Test public void givenPointerToTopic_shouldReplaceTopic() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.replace(); assertThat(topic).isEqualToIgnoringCase("Big Data"); } |
JsonPointerExample { public String add(){ JsonPointer pointer = Json.createPointer("/topics/0"); JsonObject newJsonObject = pointer.add(jsonObject,Json.createValue("Java EE")); JsonString jsonValue = (JsonString) pointer.getValue(newJsonObject); return jsonValue.getString(); } String find(); String replace(); String a... | @Test public void givenPointerToArrayElement_shouldInsertTopicInToList() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.add(); assertThat(topic).isEqualToIgnoringCase("Java EE"); } |
JsonMergePatchExample extends JsonExample { public JsonValue changeValue() { JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue patch = Json.createValue("{\"colour\":\"red\"}"); JsonMergePatch jsonMergePatch = Json.createMergePatch(patch); return jsonMergePatch.apply(source); } JsonValue changeVal... | @Test public void givenPatch_sourceValueChanges() throws Exception { JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample(); JsonValue result = jsonMergePatchExample.changeValue(); assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{\"colour\":\"red\"}"); } |
JsonMergePatchExample extends JsonExample { public JsonValue addValue() { JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue patch = Json.createValue("{\"blue\":\"light\"}"); JsonMergePatch jsonMergePatch = Json.createMergePatch(patch); return jsonMergePatch.apply(source); } JsonValue changeValue(... | @Test @Ignore public void givenPatch_addNewJsonToSource() throws Exception { JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample(); JsonValue result = jsonMergePatchExample.addValue(); assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{\"colour\":\"blue\",\"blue\":\"light\"}"); } |
JsonMergePatchExample extends JsonExample { public JsonValue deleteValue() { JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue patch = Json.createValue("{\"colour\":null}"); JsonMergePatch jsonMergePatch = Json.createMergePatch(patch); return jsonMergePatch.apply(source); } JsonValue changeValue(... | @Test @Ignore public void givenPatch_deleteValue() throws Exception { JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample(); JsonValue result = jsonMergePatchExample.deleteValue(); assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{}"); } |
JsonPatchExample extends JsonExample { public JsonObject toJsonArray() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonArray jsonArray = builder.copy("/series/0", "/topics/0").build().toJsonArray(); return Json.createPatchBuilder(jsonArray).build().apply(jsonObject); } String replace(); JsonObject addAndRe... | @Test public void ifValueIsMoved_shouldNotAmendOriginalJSON() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.toJsonArray(); JsonPointer pointer = Json.createPointer("/series/0"); JsonString jsonString = (JsonString) pointer.getValue(jsonObject); assertThat(jsonStr... |
JsonPatchExample extends JsonExample { public JsonObject test() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder .test("/topics/2", "Data") .move("/series/2", "/topics/2") .build(); return jsonPatch.apply(jsonObject); } String replace(); JsonObject addAndRemove(); JsonObject move()... | @Test public void ifValueExists_moveItToDestination() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.test(); JsonPointer pointer = Json.createPointer("/series/2"); JsonString jsonString = (JsonString) pointer.getValue(jsonObject); assertThat(jsonString.getString()... |
JsonPatchExample extends JsonExample { public JsonObject copy() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder.copy("/series/0", "/topics/0").build(); return jsonPatch.apply(jsonObject); } String replace(); JsonObject addAndRemove(); JsonObject move(); JsonObject copy(); JsonObje... | @Test public void givenPath_copyToTargetPath() throws Exception { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.copy(); JsonPointer pointer = Json.createPointer("/series/0"); JsonString jsonString = (JsonString) pointer.getValue(jsonObject); assertThat(jsonString.g... |
JsonPatchExample extends JsonExample { public JsonObject move() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder.move("/series/0", "/topics/0").build(); return jsonPatch.apply(jsonObject); } String replace(); JsonObject addAndRemove(); JsonObject move(); JsonObject copy(); JsonObje... | @Test public void givenPath_moveToTargetPath() throws Exception { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.move(); JsonPointer pointer = Json.createPointer("/series/0"); JsonString jsonString = (JsonString) pointer.getValue(jsonObject); assertThat(jsonString.g... |
JsonBindingExample extends JsonData { public String serializeListOfBooks() { return JsonbBuilder.create().toJson(books); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customi... | @Test public void givenListOfBooks_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeListOfBooks(); assertThat(json).isEqualToIgnoringCase(bookListJson); } |
JsonPatchExample extends JsonExample { public JsonObject addAndRemove() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder .add("/comments", Json.createArrayBuilder().add("Very Good!").add("Excellent").build()) .remove("/notes") .build(); return jsonPatch.apply(jsonObject); } String ... | @Test public void givenPatchPath_shouldRemoveAndAdd() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.addAndRemove(); JsonPointer pointer = Json.createPointer("/comments"); JsonValue jsonValue = pointer.getValue(jsonObject); assertThat(jsonValue.getValueType()).isE... |
JsonPatchExample extends JsonExample { public String replace() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder.replace("/series/0", "Spring 5").build(); JsonObject newJsonObject = jsonPatch.apply(jsonObject); JsonPointer pointer = Json.createPointer("/series/0"); JsonString jsonVal... | @Test public void givenPatchPath_shouldReplaceElement() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); String series = jsonPatchExample.replace(); assertThat(series).isEqualToIgnoringCase("Spring 5"); } |
JsonMergeDiffExample extends JsonExample { public JsonMergePatch createMergePatch(){ JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue target = Json.createValue("{\"colour\":\"red\"}"); JsonMergePatch jsonMergePatch = Json.createMergeDiff(source, target); return jsonMergePatch; } JsonMergePatch c... | @Test public void givenSourceAndTarget_shouldCreateMergePatch() { JsonMergeDiffExample jsonMergeDiffExample = new JsonMergeDiffExample(); JsonMergePatch mergePatch = jsonMergeDiffExample.createMergePatch(); JsonString jsonString = (JsonString) mergePatch.toJsonValue(); assertThat(jsonString.getString()).isEqualToIgnori... |
Java8Integration extends JsonExample { public List<String> filterJsonArrayToList() { List<String> topics = jsonObject.getJsonArray("topics").stream() .filter(jsonValue -> ((JsonString) jsonValue).getString().startsWith("C")) .map(jsonValue -> ((JsonString) jsonValue).getString()) .collect(Collectors.toList()); return t... | @Test public void givenJsonArray_shouldFilterAllTopicsStartingCToList() throws Exception { Java8Integration java8Integration = new Java8Integration(); List<String> topics = java8Integration.filterJsonArrayToList(); assertThat(topics).contains("Cloud"); assertThat(topics).contains("Cognitive"); } |
Java8Integration extends JsonExample { public JsonArray filterJsonArrayToJsonArray() { JsonArray topics = jsonObject.getJsonArray("topics").stream() .filter(jsonValue -> ((JsonString) jsonValue).getString().startsWith("C")) .collect(JsonCollectors.toJsonArray()); return topics; } List<String> filterJsonArrayToList(); ... | @Test public void givenJsonArray_shouldFilterAllTopicsStartingCToJsonArray() throws Exception { Java8Integration java8Integration = new Java8Integration(); JsonArray topics = java8Integration.filterJsonArrayToJsonArray(); assertThat(topics.contains(Json.createValue("Cloud"))).isTrue(); assertThat(topics.contains(Json.c... |
Book { public void addChapterTitle(String chapterTitle) { chapterTitles.add(chapterTitle); } List<String> getChapterTitles(); void addChapterTitle(String chapterTitle); Map<String, String> getAuthorChapter(); void addAuthorChapter(String author, String chapter); } | @Test public void givenListWithConstraints_shouldValidate() { Book book = new Book(); book.addChapterTitle("Chapter 1"); Set<ConstraintViolation<Book>> constraintViolations = validator.validate(book); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenListWithConstraints_shouldNotValidate() ... |
Book { public void addAuthorChapter(String author, String chapter) { authorChapter.put(author,chapter); } List<String> getChapterTitles(); void addChapterTitle(String chapterTitle); Map<String, String> getAuthorChapter(); void addAuthorChapter(String author, String chapter); } | @Test public void givenMapWithConstraints_shouldValidate() { Book book = new Book(); book.addAuthorChapter("Alex","Chapter 1"); book.addAuthorChapter("John","Chapter 2"); book.addAuthorChapter("May","Chapter 3"); Set<ConstraintViolation<Book>> constraintViolations = validator.validate(book); assertThat(constraintViolat... |
ClientChoice { public void addChoices(Choice choice) { choices.add(choice); } void addChoices(Choice choice); void addClientChoices(String name, List<Choice> choices); List<Choice> getChoices(); Map<String, List<Choice>> getClientChoices(); } | @Test public void givenListWithConstraints_shouldValidate() { ClientChoice clientChoice = new ClientChoice(); clientChoice.addChoices(new Choice(1, "Pineapple")); clientChoice.addChoices(new Choice(2, "Banana")); clientChoice.addChoices(new Choice(3, "Apple")); Set<ConstraintViolation<ClientChoice>> constraintViolation... |
JsonBindingExample extends JsonData { public List<Book> deserializeListOfBooks() { return JsonbBuilder.create().fromJson(bookListJson, new ArrayList<Book>().getClass().getGenericSuperclass()); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String s... | @Test @Ignore public void givenJSON_deserializeToListOfBooks() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); List<Book> actualBooks = jsonBindingExample.deserializeListOfBooks(); assertThat(actualBooks).isEqualTo(books); } |
ClientChoice { public void addClientChoices(String name, List<Choice> choices) { clientChoices.put(name, choices); } void addChoices(Choice choice); void addClientChoices(String name, List<Choice> choices); List<Choice> getChoices(); Map<String, List<Choice>> getClientChoices(); } | @Test public void givenMapWithConstraints_shouldValidate() { ClientChoice clientChoice = new ClientChoice(); clientChoice.addClientChoices("John", new ArrayList<Choice>() {{ add(new Choice(1, "Roast Lamb")); add(new Choice(1, "Ice Cream")); add(new Choice(1, "Apple")); }}); clientChoice.addClientChoices("May", new Arra... |
Customer { public void setEmail(String email) { this.email = email; } String getFirstName(); void setFirstName(String firstName); String getSecondName(); void setSecondName(String secondName); String getEmail(); void setEmail(String email); } | @Test public void givenBeanWithValidEmailConstraints_shouldValidate() { Customer customer = new Customer(); customer.setEmail("alex.theedom@example.com"); Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void giv... |
Person { public void setEmail(String email) { this.email = email; } String getFirstName(); void setFirstName(String firstName); String getSecondName(); void setSecondName(String secondName); String getEmail(); void setEmail(String email); } | @Test public void givenBeanWithValidEmailConstraints_shouldValidate() { Person person = new Person(); person.setEmail("alex.theedom@example.com"); Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenBeanWithIn... |
Person { public void setCars(List<String> cars) { this.cars = cars; } String getFirstName(); void setFirstName(String firstName); String getSecondName(); void setSecondName(String secondName); String getEmail(); void setEmail(String email); List<String> getCars(); void setCars(List<String> cars); } | @Test public void givenBeanWithEmptyElementInCollection_shouldValidate() { Person person = new Person(); person.setCars(new ArrayList<String>() { { add(null); } }); Set<ConstraintViolation<Person>> constraintViolations = validator.validateProperty(person, "cars"); assertThat(constraintViolations.size()).isEqualTo(1); }... |
RepeatedConstraint { public void setText(String text) { this.text = text; } String getText(); void setText(String text); } | @Test public void givenBeanWithValidDomain_shouldValidate() { RepeatedConstraint repeatedConstraint = new RepeatedConstraint(); repeatedConstraint.setText("www.readlearncode.com"); Set<ConstraintViolation<RepeatedConstraint>> constraintViolations = validator.validate(repeatedConstraint); assertThat(constraintViolations... |
JsonBindingExample extends JsonData { public String serializeArrayOfBooks() { return JsonbBuilder.create().toJson(arrayBooks); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String c... | @Test public void givenArrayOfBooks_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeArrayOfBooks(); assertThat(json).isEqualToIgnoringCase(bookListJson); } |
OptionalExample { public void setText(String text) { this.text = Optional.of(text); } Optional<String> getName(); void setName(String name); Optional<String> getText(); void setText(String text); } | @Test public void givenBeanWithOptionalStringExample_shouldNotValidate() { OptionalExample optionalExample = new OptionalExample(); optionalExample.setText(" "); Set<ConstraintViolation<OptionalExample>> constraintViolations = validator.validate(optionalExample); assertThat(constraintViolations.size()).isEqualTo(2); } |
JsonBindingExample extends JsonData { public String serializeArrayOfStrings() { return JsonbBuilder.create().toJson(new String[]{"Java EE", "Java SE"}); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serialize... | @Test public void givenArrayOfStrings_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeArrayOfStrings(); assertThat(json).isEqualToIgnoringCase("[\"Java EE\",\"Java SE\"]"); } |
JsonBindingExample extends JsonData { public String customizedMapping() { JsonbConfig jsonbConfig = new JsonbConfig() .withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_DASHES) .withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL) .withStrictIJSON(true) .withFormatting(true) .withNullValues(... | @Test public void givenCustomisationOnProperties_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.customizedMapping(); assertThat(result).isEqualToIgnoringCase(customisedJson); } |
JsonBindingExample extends JsonData { public String annotationMethodMapping() { return JsonbBuilder.create().toJson(newspaper); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String ... | @Test public void givenCustomisationOnMethods_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationMethodMapping(); assertThat(result).isEqualToIgnoringCase(customisedJsonNewspaper); } |
JsonBindingExample extends JsonData { public String annotationPropertyAndMethodMapping() { return JsonbBuilder.create().toJson(booklet); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings()... | @Test public void givenCustomisationOnPropertiesAndMethods_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationPropertyAndMethodMapping(); assertThat(result).isEqualToIgnoringCase("{\"cost\":\"10.00\",\"author\":{\"firstName\":\"Alex\",\"l... |
JsonBindingExample extends JsonData { public String annotationPropertiesMapping() { return JsonbBuilder.create().toJson(magazine); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); Stri... | @Test public void givenAnnotationPojo_shouldProduceJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationPropertiesMapping(); assertThat(result).isEqualToIgnoringCase(expectedMagazine); } |
AuthenticationUtil { public static void clearAuthentication() { SecurityContextHolder.getContext().setAuthentication(null); } private AuthenticationUtil(); static void clearAuthentication(); static void configureAuthentication(String role); } | @Test public void clearAuthentication_ShouldRemoveAuthenticationFromSecurityContext() { Authentication authentication = createAuthentication(); SecurityContextHolder.getContext().setAuthentication(authentication); AuthenticationUtil.clearAuthentication(); Authentication currentAuthentication = SecurityContextHolder.get... |
AuthenticationUtil { public static void configureAuthentication(String role) { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(role); Authentication authentication = new UsernamePasswordAuthenticationToken( USERNAME, role, authorities ); SecurityContextHolder.getContext().setAuthentication... | @Test public void configurationAuthentication_ShouldSetAuthenticationToSecurityContext() { AuthenticationUtil.configureAuthentication(ROLE); Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication(); assertThat(currentAuthentication.getAuthorities()).hasSize(1); assertThat(currentAut... |
SerializerFactoryLoader { public static SerializerFactory getFactory(ProcessingEnvironment processingEnv) { return new SerializerFactoryImpl(loadExtensions(processingEnv), processingEnv); } private SerializerFactoryLoader(); static SerializerFactory getFactory(ProcessingEnvironment processingEnv); } | @Test public void getFactory_extensionsLoaded() throws Exception { SerializerFactory factory = SerializerFactoryLoader.getFactory(mockProcessingEnvironment); Serializer actualSerializer = factory.getSerializer(typeMirrorOf(String.class)); assertThat(actualSerializer.getClass().getName()) .contains("TestStringSerializer... |
AnnotationValues { public static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value) { return TYPE_MIRRORS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotation... | @Test public void getTypeMirrors() { TypeMirror insideClassA = getTypeElement(InsideClassA.class).asType(); TypeMirror insideClassB = getTypeElement(InsideClassB.class).asType(); AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "classValues"); ImmutableList<DeclaredType> valueElements = An... |
AnnotationValues { public static AnnotationMirror getAnnotationMirror(AnnotationValue value) { return AnnotationMirrorVisitor.INSTANCE.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnno... | @Test public void getAnnotationMirror() { TypeElement insideAnnotation = getTypeElement(InsideAnnotation.class); AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "insideAnnotationValue"); AnnotationMirror annotationMirror = AnnotationValues.getAnnotationMirror(value); assertThat(annotation... |
AnnotationValues { public static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value) { return ANNOTATION_MIRRORS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirr... | @Test public void getAnnotationMirrors() { TypeElement insideAnnotation = getTypeElement(InsideAnnotation.class); AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "insideAnnotationValues"); ImmutableList<AnnotationMirror> annotationMirrors = AnnotationValues.getAnnotationMirrors(value); Im... |
AnnotationValues { public static String getString(AnnotationValue value) { return valueOfType(value, String.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue valu... | @Test public void getString() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "stringValue"); assertThat(AnnotationValues.getString(value)).isEqualTo("hello"); } |
AnnotationValues { public static ImmutableList<String> getStrings(AnnotationValue value) { return STRINGS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(Annotati... | @Test public void getStrings() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "stringValues"); assertThat(AnnotationValues.getStrings(value)).containsExactly("it's", "me").inOrder(); } |
AnnotationValues { public static VariableElement getEnum(AnnotationValue value) { return EnumVisitor.INSTANCE.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationVa... | @Test public void getEnum() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "enumValue"); assertThat(AnnotationValues.getEnum(value)).isEqualTo(value.getValue()); } |
AnnotationValues { public static ImmutableList<VariableElement> getEnums(AnnotationValue value) { return ENUMS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(Ann... | @Test public void getEnums() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "enumValues"); assertThat(getEnumNames(AnnotationValues.getEnums(value))) .containsExactly(Foo.BAZ.name(), Foo.BAH.name()) .inOrder(); } |
AnnotationValues { public static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value) { return ANNOTATION_VALUES_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror ... | @Test public void getAnnotationValues() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "intValues"); ImmutableList<AnnotationValue> values = AnnotationValues.getAnnotationValues(value); assertThat(values) .comparingElementsUsing(Correspondence.transforming(AnnotationValue::getValue, "h... |
AnnotationValues { public static int getInt(AnnotationValue value) { return valueOfType(value, Integer.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); s... | @Test public void getInt() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "intValue"); assertThat(AnnotationValues.getInt(value)).isEqualTo(5); } |
AnnotationValues { public static ImmutableList<Integer> getInts(AnnotationValue value) { return INTS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationVal... | @Test public void getInts() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "intValues"); assertThat(AnnotationValues.getInts(value)).containsExactly(1, 2).inOrder(); } |
OptionalSerializerExtension implements SerializerExtension { @Override public Optional<Serializer> getSerializer( TypeMirror typeMirror, SerializerFactory factory, ProcessingEnvironment processingEnv) { if (!isOptional(typeMirror)) { return Optional.empty(); } TypeMirror containedType = getContainedType(typeMirror); Se... | @Test public void toProxy() { TypeMirror typeMirror = declaredTypeOf(Optional.class, Integer.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); CodeBlock actualCodeBlock = serializer.toProxy(CodeBlock.of("x")); assertThat(actualCodeBlock.toString... |
AnnotationValues { public static long getLong(AnnotationValue value) { return valueOfType(value, Long.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); st... | @Test public void getLong() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "longValue"); assertThat(AnnotationValues.getLong(value)).isEqualTo(6L); } |
AnnotationValues { public static ImmutableList<Long> getLongs(AnnotationValue value) { return LONGS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValu... | @Test public void getLongs() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "longValues"); assertThat(AnnotationValues.getLongs(value)).containsExactly(3L, 4L).inOrder(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.