method2testcases
stringlengths
118
3.08k
### Question: EmployeeService { public List<Employee> findAll() { return entityManager.createNamedQuery("Employee.findAll", Employee.class) .getResultList(); } void persist(Employee employee); List<Employee> findAll(); }### Answer: @Test public void T1_testGet() throws Exception { assertNotNull(employeeService); List<Employee> employees = employeeService.findAll(); assertNotNull(employees); assertEquals(8, employees.size()); assertFalse(employees.contains(new Employee("Penny"))); assertFalse(employees.contains(new Employee("Sheldon"))); assertFalse(employees.contains(new Employee("Amy"))); assertFalse(employees.contains(new Employee("Leonard"))); assertFalse(employees.contains(new Employee("Bernadette"))); assertFalse(employees.contains(new Employee("Raj"))); assertFalse(employees.contains(new Employee("Howard"))); assertFalse(employees.contains(new Employee("Priya"))); }
### Question: MyResource { @POST @Path("index") @Consumes("text/plain") public String postSimple(int index) { return RESPONSE[index % 3]; } @POST @Consumes(MyObject.MIME_TYPE) String postWithCustomMimeType(MyObject myObject); @POST @Path("index") @Consumes("text/plain") String postSimple(int index); }### Answer: @Test public void testPostSimple() { String fruit = target .path("index") .request() .post(Entity.text("1"), String.class); assertEquals("banana", fruit); }
### Question: MyResource { @GET public String getFruit() { String clientHeaderValue = headers.getHeaderString("clientHeader"); String serverHeaderValue = headers.getHeaderString("serverHeader"); if (clientHeaderValue != null && clientHeaderValue.equals("clientHeaderValue") && serverHeaderValue != null && serverHeaderValue.equals("serverHeaderValue")) { return "apple"; } else { return "banana"; } } @GET String getFruit(); @POST @Consumes(value = "*/*") @Produces("text/plain") String echoFruit(String fruit); }### Answer: @Test public void testGetFruit() { String result = target.request().get(String.class); assertEquals("Likely that the headers set in the filter were not available in endpoint", "apple", result); }
### Question: MyResource { @GET() @Path("/{id1}/{id2}") @Produces(MediaType.TEXT_PLAIN) public String get(@BeanParam MyPathParams pathParams, @BeanParam MyQueryParams queryParams) { return "/" + pathParams.getId1() + "/" + pathParams.getId2() + "?param1=" + queryParams.getParam1() + "&param2=" + queryParams.getParam2() + "&param3=" + queryParams.getParam3(); } @GET() @Path("/{id1}/{id2}") @Produces(MediaType.TEXT_PLAIN) String get(@BeanParam MyPathParams pathParams, @BeanParam MyQueryParams queryParams); }### Answer: @Test public void testRequestWithAllParams() { WebTarget t = target.path("/123").path("/abc").queryParam("param1", "foo").queryParam("param2", "bar").queryParam("param3", "baz"); String r = t.request().get(String.class); assertEquals("/123/abc?param1=foo&param2=bar&param3=baz", r); }
### Question: ConnectionPool implements AutoCloseable { public <T> CompletableFuture<T> withConnection(Function<QueryReadyConnection.AutoCommit, CompletableFuture<T>> fn) { return withConnection(config.defaultTimeout, config.defaultTimeoutUnit, fn); } @SuppressWarnings("initialization") ConnectionPool(Config config); CompletableFuture<QueryReadyConnection.AutoCommit> borrowConnection(); CompletableFuture<QueryReadyConnection.AutoCommit> borrowConnection(long timeout, TimeUnit unit); @SuppressWarnings("dereference.of.nullable") void returnConnection(QueryReadyConnection.@Nullable AutoCommit conn); CompletableFuture<T> withConnection(Function<QueryReadyConnection.AutoCommit, CompletableFuture<T>> fn); CompletableFuture<T> withConnection(long waitForConnTimeout, TimeUnit waitForConnUnit, Function<QueryReadyConnection.AutoCommit, CompletableFuture<T>> fn); CompletableFuture<Void> terminateAll(); @Override void close(); }### Answer: @Test public void testFirstLazyConnectionIsOnlyOne() throws Exception { try (ConnectionPool pool = new ConnectionPool(newDefaultConfig().poolSize(5))) { long count = pool.withConnection(this::getConnectionCount).get(); Assert.assertEquals(1L, count); count = pool.withConnection(this::getConnectionCount).get(); Assert.assertEquals(1L, count); } } @Test public void testSecondLazyConnectionCreatedWhenNeeded() throws Exception { try (ConnectionPool pool = new ConnectionPool(newDefaultConfig().poolSize(5))) { CountDownLatch firstLatch = new CountDownLatch(1); CountDownLatch secondLatch = new CountDownLatch(1); CompletableFuture<Long> firstCount = pool.withConnection(c -> waitOn(getConnectionCount(c), firstLatch)); CompletableFuture<Long> secondCount = pool.withConnection(c -> waitOn(secondLatch).thenCompose(__ -> getConnectionCount(c))); firstLatch.countDown(); Assert.assertEquals(1L, firstCount.get().longValue()); secondLatch.countDown(); Assert.assertEquals(2L, secondCount.get().longValue()); } }
### Question: PwnedPasswordChecker { public CompletableFuture<Boolean> asyncCheck(String password) { Hex hashedPassword = hashPassword(password); return client.fetchHashesAsync(hashedPassword).thenApplyAsync(x -> x.contains(hashedPassword)); } PwnedPasswordChecker(PwnedPasswordClient client); CompletableFuture<Boolean> asyncCheck(String password); boolean check(String password); }### Answer: @Test public void asyncMultipleHashesWithPasswordShouldFindPassword() throws ExecutionException, InterruptedException { PwnedPasswordClient client = Mockito.mock(PwnedPasswordClient.class); doAnswer(invocation -> CompletableFuture.completedFuture(Arrays.asList(Hex.from("5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8")))) .when(client).fetchHashesAsync(any()); Future<Boolean> f = new PwnedPasswordChecker(client).asyncCheck("test"); assertFalse(f.get()); }
### Question: TextApplication { public static void main(String[] args) throws NamingException { TextProcessorRemote textProcessor = EJBFactory.createTextProcessorBeanFromJNDI("ejb:"); System.out.print(textProcessor.processText("sample text")); } static void main(String[] args); }### Answer: @Test public void givenInputString_whenCompareTtoStringPrintedToConsole_thenSuccessful() throws NamingException { TextApplication.main(new String[]{}); assertEquals("SAMPLE TEXT", outContent.toString()); }
### Question: AsciidoctorDemo { String generateHTMLFromString(final String input) { return asciidoctor.convert("Hello _Baeldung_!", new HashMap<String, Object>()); } AsciidoctorDemo(); void generatePDFFromString(final String input); }### Answer: @Test public void givenString_whenConverting_thenResultingHTMLCode() { final AsciidoctorDemo asciidoctorDemo = new AsciidoctorDemo(); Assert.assertEquals(asciidoctorDemo.generateHTMLFromString("Hello _Baeldung_!"), "<div class=\"paragraph\">\n<p>Hello <em>Baeldung</em>!</p>\n</div>"); }
### Question: DateToLocalDateTimeConverter { public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { return dateToConvert.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDateTime(); } static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert); static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert); static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert); static LocalDateTime convertToLocalDateTime(Date dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { Calendar calendar = Calendar.getInstance(); calendar.set(2010, 10, 10, 8, 20); Date dateToConvert = calendar.getTime(); LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert); assertEquals(2010, localDateTime.get(ChronoField.YEAR)); assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); }
### Question: DateToLocalDateTimeConverter { public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) { return Instant.ofEpochMilli(dateToConvert.getTime()) .atZone(ZoneId.systemDefault()) .toLocalDateTime(); } static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert); static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert); static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert); static LocalDateTime convertToLocalDateTime(Date dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() { Calendar calendar = Calendar.getInstance(); calendar.set(2010, 10, 10, 8, 20); Date dateToConvert = calendar.getTime(); LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert); assertEquals(2010, localDateTime.get(ChronoField.YEAR)); assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); }
### Question: DateToLocalDateTimeConverter { public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) { return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime(); } static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert); static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert); static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert); static LocalDateTime convertToLocalDateTime(Date dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() { Calendar calendar = Calendar.getInstance(); calendar.set(2010, 10, 10, 8, 20); Date dateToConvert = calendar.getTime(); LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert); assertEquals(2010, localDateTime.get(ChronoField.YEAR)); assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); }
### Question: DateToLocalDateTimeConverter { public static LocalDateTime convertToLocalDateTime(Date dateToConvert) { return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); } static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert); static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert); static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert); static LocalDateTime convertToLocalDateTime(Date dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() { Calendar calendar = Calendar.getInstance(); calendar.set(2010, 10, 10, 8, 20); Date dateToConvert = calendar.getTime(); LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert); assertEquals(2010, localDateTime.get(ChronoField.YEAR)); assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); }
### Question: LocalDateTimeToDateConverter { public static Date convertToDateViaInstant(LocalDateTime dateToConvert) { return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault()) .toInstant()); } static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert); static Date convertToDateViaInstant(LocalDateTime dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(2010, calendar.get(Calendar.YEAR)); assertEquals(10, calendar.get(Calendar.MONTH)); assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); assertEquals(8, calendar.get(Calendar.HOUR)); assertEquals(20, calendar.get(Calendar.MINUTE)); assertEquals(0, calendar.get(Calendar.SECOND)); }
### Question: LocalDateTimeToDateConverter { public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) { return java.sql.Timestamp.valueOf(dateToConvert); } static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert); static Date convertToDateViaInstant(LocalDateTime dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() { LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(2010, calendar.get(Calendar.YEAR)); assertEquals(10, calendar.get(Calendar.MONTH)); assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); assertEquals(8, calendar.get(Calendar.HOUR)); assertEquals(20, calendar.get(Calendar.MINUTE)); assertEquals(0, calendar.get(Calendar.SECOND)); }
### Question: DateToLocalDateConverter { public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) { return dateToConvert.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); } static LocalDate convertToLocalDateViaInstant(Date dateToConvert); static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert); static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert); static LocalDate convertToLocalDate(Date dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010WhenConvertViaInstant() { Calendar calendar = Calendar.getInstance(); calendar.set(2010, 10, 10); Date dateToConvert = calendar.getTime(); LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert); assertEquals(2010, localDate.get(ChronoField.YEAR)); assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); }
### Question: DateToLocalDateConverter { public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) { return Instant.ofEpochMilli(dateToConvert.getTime()) .atZone(ZoneId.systemDefault()) .toLocalDate(); } static LocalDate convertToLocalDateViaInstant(Date dateToConvert); static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert); static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert); static LocalDate convertToLocalDate(Date dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() { Calendar calendar = Calendar.getInstance(); calendar.set(2010, 10, 10); Date dateToConvert = calendar.getTime(); LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert); assertEquals(2010, localDate.get(ChronoField.YEAR)); assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); }
### Question: DateToLocalDateConverter { public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) { return new java.sql.Date(dateToConvert.getTime()).toLocalDate(); } static LocalDate convertToLocalDateViaInstant(Date dateToConvert); static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert); static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert); static LocalDate convertToLocalDate(Date dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { Calendar calendar = Calendar.getInstance(); calendar.set(2010, 10, 10); Date dateToConvert = calendar.getTime(); LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert); assertEquals(2010, localDate.get(ChronoField.YEAR)); assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); }
### Question: DateToLocalDateConverter { public static LocalDate convertToLocalDate(Date dateToConvert) { return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); } static LocalDate convertToLocalDateViaInstant(Date dateToConvert); static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert); static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert); static LocalDate convertToLocalDate(Date dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010WhenConvertToLocalDate() { Calendar calendar = Calendar.getInstance(); calendar.set(2010, 10, 10); Date dateToConvert = calendar.getTime(); LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert); assertEquals(2010, localDateTime.get(ChronoField.YEAR)); assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); }
### Question: LocalDateToDateConverter { public static Date convertToDateViaInstant(LocalDate dateToConvert) { return java.util.Date.from(dateToConvert.atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant()); } static Date convertToDateViaSqlDate(LocalDate dateToConvert); static Date convertToDateViaInstant(LocalDate dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010WhenConvertViaInstant() { LocalDate dateToConvert = LocalDate.of(2010, 11, 10); Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(2010, calendar.get(Calendar.YEAR)); assertEquals(10, calendar.get(Calendar.MONTH)); assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); }
### Question: LocalDateToDateConverter { public static Date convertToDateViaSqlDate(LocalDate dateToConvert) { return java.sql.Date.valueOf(dateToConvert); } static Date convertToDateViaSqlDate(LocalDate dateToConvert); static Date convertToDateViaInstant(LocalDate dateToConvert); }### Answer: @Test public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { LocalDate dateToConvert = LocalDate.of(2010, 11, 10); Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(2010, calendar.get(Calendar.YEAR)); assertEquals(10, calendar.get(Calendar.MONTH)); assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); }
### Question: TimeApi { public static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) { List<Date> datesInRange = new ArrayList<Date>(); Calendar calendar = new GregorianCalendar(); calendar.setTime(startDate); Calendar endCalendar = new GregorianCalendar(); endCalendar.setTime(endDate); while (calendar.before(endCalendar)) { Date result = calendar.getTime(); datesInRange.add(result); calendar.add(Calendar.DATE, 1); } return datesInRange; } static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate); static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate); static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate); }### Answer: @Test public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() { Date startDate = Calendar.getInstance().getTime(); Calendar endCalendar = Calendar.getInstance(); endCalendar.add(Calendar.DATE, 2); Date endDate = endCalendar.getTime(); List<Date> dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate); assertEquals(dates.size(), 2); Calendar calendar = Calendar.getInstance(); Date date1 = calendar.getTime(); assertEquals(dates.get(0).getDay(), date1.getDay()); assertEquals(dates.get(0).getMonth(), date1.getMonth()); assertEquals(dates.get(0).getYear(), date1.getYear()); calendar.add(Calendar.DATE, 1); Date date2 = calendar.getTime(); assertEquals(dates.get(1).getDay(), date2.getDay()); assertEquals(dates.get(1).getMonth(), date2.getMonth()); assertEquals(dates.get(1).getYear(), date2.getYear()); }
### Question: TimeApi { public static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate) { long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate); return IntStream.iterate(0, i -> i + 1) .limit(numOfDaysBetween) .mapToObj(i -> startDate.plusDays(i)) .collect(Collectors.toList()); } static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate); static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate); static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate); }### Answer: @Test public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() { LocalDate startDate = LocalDate.now(); LocalDate endDate = LocalDate.now().plusDays(2); List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate); assertEquals(dates.size(), 2); assertEquals(dates.get(0), LocalDate.now()); assertEquals(dates.get(1), LocalDate.now().plusDays(1)); }
### Question: TimeApi { public static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) { return startDate.datesUntil(endDate).collect(Collectors.toList()); } static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate); static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate); static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate); }### Answer: @Test public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() { LocalDate startDate = LocalDate.now(); LocalDate endDate = LocalDate.now().plusDays(2); List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate); assertEquals(dates.size(), 2); assertEquals(dates.get(0), LocalDate.now()); assertEquals(dates.get(1), LocalDate.now().plusDays(1)); }
### Question: UserApi { public void createUser(User body) throws RestClientException { Object postBody = body; if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUser"); } String path = UriComponentsBuilder.fromPath("/user").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); void createUsersWithArrayInput(List<User> body); void createUsersWithListInput(List<User> body); void deleteUser(String username); User getUserByName(String username); String loginUser(String username, String password); void logoutUser(); void updateUser(String username, User body); }### Answer: @Test public void createUserTest() { User body = null; api.createUser(body); }
### Question: UserApi { public void createUsersWithArrayInput(List<User> body) throws RestClientException { Object postBody = body; if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); } String path = UriComponentsBuilder.fromPath("/user/createWithArray").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); void createUsersWithArrayInput(List<User> body); void createUsersWithListInput(List<User> body); void deleteUser(String username); User getUserByName(String username); String loginUser(String username, String password); void logoutUser(); void updateUser(String username, User body); }### Answer: @Test public void createUsersWithArrayInputTest() { List<User> body = null; api.createUsersWithArrayInput(body); }
### Question: UserApi { public void createUsersWithListInput(List<User> body) throws RestClientException { Object postBody = body; if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithListInput"); } String path = UriComponentsBuilder.fromPath("/user/createWithList").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); void createUsersWithArrayInput(List<User> body); void createUsersWithListInput(List<User> body); void deleteUser(String username); User getUserByName(String username); String loginUser(String username, String password); void logoutUser(); void updateUser(String username, User body); }### Answer: @Test public void createUsersWithListInputTest() { List<User> body = null; api.createUsersWithListInput(body); }
### Question: UserApi { public void deleteUser(String username) throws RestClientException { Object postBody = null; if (username == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling deleteUser"); } final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("username", username); String path = UriComponentsBuilder.fromPath("/user/{username}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); void createUsersWithArrayInput(List<User> body); void createUsersWithListInput(List<User> body); void deleteUser(String username); User getUserByName(String username); String loginUser(String username, String password); void logoutUser(); void updateUser(String username, User body); }### Answer: @Test public void deleteUserTest() { String username = null; api.deleteUser(username); }
### Question: UserApi { public User getUserByName(String username) throws RestClientException { Object postBody = null; if (username == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling getUserByName"); } final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("username", username); String path = UriComponentsBuilder.fromPath("/user/{username}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<User> returnType = new ParameterizedTypeReference<User>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); void createUsersWithArrayInput(List<User> body); void createUsersWithListInput(List<User> body); void deleteUser(String username); User getUserByName(String username); String loginUser(String username, String password); void logoutUser(); void updateUser(String username, User body); }### Answer: @Test public void getUserByNameTest() { String username = null; User response = api.getUserByName(username); }
### Question: UserApi { public String loginUser(String username, String password) throws RestClientException { Object postBody = null; if (username == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling loginUser"); } if (password == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'password' when calling loginUser"); } String path = UriComponentsBuilder.fromPath("/user/login").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<String> returnType = new ParameterizedTypeReference<String>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); void createUsersWithArrayInput(List<User> body); void createUsersWithListInput(List<User> body); void deleteUser(String username); User getUserByName(String username); String loginUser(String username, String password); void logoutUser(); void updateUser(String username, User body); }### Answer: @Test public void loginUserTest() { String username = null; String password = null; String response = api.loginUser(username, password); }
### Question: UserApi { public void logoutUser() throws RestClientException { Object postBody = null; String path = UriComponentsBuilder.fromPath("/user/logout").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); void createUsersWithArrayInput(List<User> body); void createUsersWithListInput(List<User> body); void deleteUser(String username); User getUserByName(String username); String loginUser(String username, String password); void logoutUser(); void updateUser(String username, User body); }### Answer: @Test public void logoutUserTest() { api.logoutUser(); }
### Question: UserApi { public void updateUser(String username, User body) throws RestClientException { Object postBody = body; if (username == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser"); } if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser"); } final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("username", username); String path = UriComponentsBuilder.fromPath("/user/{username}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); void createUsersWithArrayInput(List<User> body); void createUsersWithListInput(List<User> body); void deleteUser(String username); User getUserByName(String username); String loginUser(String username, String password); void logoutUser(); void updateUser(String username, User body); }### Answer: @Test public void updateUserTest() { String username = null; User body = null; api.updateUser(username, body); }
### Question: StoreApi { public void deleteOrder(Long orderId) throws RestClientException { Object postBody = null; if (orderId == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling deleteOrder"); } final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("orderId", orderId); String path = UriComponentsBuilder.fromPath("/store/order/{orderId}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } StoreApi(); @Autowired StoreApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void deleteOrder(Long orderId); Map<String, Integer> getInventory(); Order getOrderById(Long orderId); Order placeOrder(Order body); }### Answer: @Test public void deleteOrderTest() { Long orderId = null; api.deleteOrder(orderId); }
### Question: StoreApi { public Map<String, Integer> getInventory() throws RestClientException { Object postBody = null; String path = UriComponentsBuilder.fromPath("/store/inventory").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference<Map<String, Integer>> returnType = new ParameterizedTypeReference<Map<String, Integer>>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } StoreApi(); @Autowired StoreApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void deleteOrder(Long orderId); Map<String, Integer> getInventory(); Order getOrderById(Long orderId); Order placeOrder(Order body); }### Answer: @Test public void getInventoryTest() { Map<String, Integer> response = api.getInventory(); }
### Question: StoreApi { public Order getOrderById(Long orderId) throws RestClientException { Object postBody = null; if (orderId == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling getOrderById"); } final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("orderId", orderId); String path = UriComponentsBuilder.fromPath("/store/order/{orderId}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Order> returnType = new ParameterizedTypeReference<Order>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } StoreApi(); @Autowired StoreApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void deleteOrder(Long orderId); Map<String, Integer> getInventory(); Order getOrderById(Long orderId); Order placeOrder(Order body); }### Answer: @Test public void getOrderByIdTest() { Long orderId = null; Order response = api.getOrderById(orderId); }
### Question: StoreApi { public Order placeOrder(Order body) throws RestClientException { Object postBody = body; if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling placeOrder"); } String path = UriComponentsBuilder.fromPath("/store/order").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Order> returnType = new ParameterizedTypeReference<Order>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } StoreApi(); @Autowired StoreApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void deleteOrder(Long orderId); Map<String, Integer> getInventory(); Order getOrderById(Long orderId); Order placeOrder(Order body); }### Answer: @Test public void placeOrderTest() { Order body = null; Order response = api.placeOrder(body); }
### Question: PetApi { public void addPet(Pet body) throws RestClientException { Object postBody = body; if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling addPet"); } String path = UriComponentsBuilder.fromPath("/pet").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "application/json", "application/xml" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); void deletePet(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); List<Pet> findPetsByTags(List<String> tags); Pet getPetById(Long petId); void updatePet(Pet body); void updatePetWithForm(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); }### Answer: @Test public void addPetTest() { Pet body = null; api.addPet(body); }
### Question: PetApi { public void deletePet(Long petId, String apiKey) throws RestClientException { Object postBody = null; if (petId == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling deletePet"); } final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("petId", petId); String path = UriComponentsBuilder.fromPath("/pet/{petId}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); if (apiKey != null) headerParams.add("api_key", apiClient.parameterToString(apiKey)); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); void deletePet(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); List<Pet> findPetsByTags(List<String> tags); Pet getPetById(Long petId); void updatePet(Pet body); void updatePetWithForm(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); }### Answer: @Test public void deletePetTest() { Long petId = null; String apiKey = null; api.deletePet(petId, apiKey); }
### Question: PetApi { public List<Pet> findPetsByStatus(List<String> status) throws RestClientException { Object postBody = null; if (status == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'status' when calling findPetsByStatus"); } String path = UriComponentsBuilder.fromPath("/pet/findByStatus").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase()), "status", status)); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference<List<Pet>> returnType = new ParameterizedTypeReference<List<Pet>>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); void deletePet(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); List<Pet> findPetsByTags(List<String> tags); Pet getPetById(Long petId); void updatePet(Pet body); void updatePetWithForm(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); }### Answer: @Test public void findPetsByStatusTest() { List<String> status = null; List<Pet> response = api.findPetsByStatus(status); }
### Question: PetApi { public List<Pet> findPetsByTags(List<String> tags) throws RestClientException { Object postBody = null; if (tags == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'tags' when calling findPetsByTags"); } String path = UriComponentsBuilder.fromPath("/pet/findByTags").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase()), "tags", tags)); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference<List<Pet>> returnType = new ParameterizedTypeReference<List<Pet>>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); void deletePet(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); List<Pet> findPetsByTags(List<String> tags); Pet getPetById(Long petId); void updatePet(Pet body); void updatePetWithForm(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); }### Answer: @Test public void findPetsByTagsTest() { List<String> tags = null; List<Pet> response = api.findPetsByTags(tags); }
### Question: PetApi { public Pet getPetById(Long petId) throws RestClientException { Object postBody = null; if (petId == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling getPetById"); } final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("petId", petId); String path = UriComponentsBuilder.fromPath("/pet/{petId}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference<Pet> returnType = new ParameterizedTypeReference<Pet>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); void deletePet(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); List<Pet> findPetsByTags(List<String> tags); Pet getPetById(Long petId); void updatePet(Pet body); void updatePetWithForm(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); }### Answer: @Test public void getPetByIdTest() { Long petId = null; Pet response = api.getPetById(petId); }
### Question: PetApi { public void updatePet(Pet body) throws RestClientException { Object postBody = body; if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updatePet"); } String path = UriComponentsBuilder.fromPath("/pet").build().toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "application/xml", "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "application/json", "application/xml" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); void deletePet(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); List<Pet> findPetsByTags(List<String> tags); Pet getPetById(Long petId); void updatePet(Pet body); void updatePetWithForm(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); }### Answer: @Test public void updatePetTest() { Pet body = null; api.updatePet(body); }
### Question: Executor { public static int countAutors(Stream<Author> stream) { RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true), RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine); return wordCounter.getCounter(); } static int countAutors(Stream<Author> stream); static List<Article> generateElements(); }### Answer: @Test public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() { Stream<Author> stream2 = StreamSupport.stream(spliterator, true); assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9); }
### Question: Executor { public static List<Article> generateElements() { return Stream.generate(() -> new Article("Java")).limit(35000).collect(Collectors.toList()); } static int countAutors(Stream<Author> stream); static List<Article> generateElements(); }### Answer: @Test public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() { assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + ""); assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + ""); }
### Question: Iterators { public static int failFast1() { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); Iterator<Integer> iterator = numbers.iterator(); while (iterator.hasNext()) { Integer number = iterator.next(); numbers.add(50); } return numbers.size(); } static int failFast1(); static int failFast2(); static int failSafe1(); }### Answer: @Test public void whenFailFast_ThenThrowsException() { assertThatThrownBy(() -> { failFast1(); }).isInstanceOf(ConcurrentModificationException.class); }
### Question: Iterators { public static int failFast2() { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); Iterator<Integer> iterator = numbers.iterator(); while (iterator.hasNext()) { if (iterator.next() == 30) { iterator.remove(); } } System.out.println("using iterator's remove method = " + numbers); iterator = numbers.iterator(); while (iterator.hasNext()) { if (iterator.next() == 40) { numbers.remove(2); } } return numbers.size(); } static int failFast1(); static int failFast2(); static int failSafe1(); }### Answer: @Test public void whenFailFast_ThenThrowsExceptionInSecondIteration() { assertThatThrownBy(() -> { failFast2(); }).isInstanceOf(ConcurrentModificationException.class); }
### Question: Iterators { public static int failSafe1() { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("First", 10); map.put("Second", 20); map.put("Third", 30); map.put("Fourth", 40); Iterator<String> iterator = map.keySet() .iterator(); while (iterator.hasNext()) { String key = iterator.next(); map.put("Fifth", 50); } return map.size(); } static int failFast1(); static int failFast2(); static int failSafe1(); }### Answer: @Test public void whenFailSafe_ThenDoesNotThrowException() { assertThat(failSafe1()).isGreaterThanOrEqualTo(0); }
### Question: StreamIndices { public static List<Indexed<String>> getOddIndexedStrings(List<String> names) { List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream()) .filter(i -> i.getIndex() % 2 == 1) .collect(Collectors.toList()); return list; } static List<String> getEvenIndexedStrings(String[] names); List<String> getEvenIndexedStringsVersionTwo(List<String> names); static List<Indexed<String>> getEvenIndexedStrings(List<String> names); static List<Indexed<String>> getOddIndexedStrings(List<String> names); static List<String> getOddIndexedStrings(String[] names); static List<String> getOddIndexedStringsVersionTwo(String[] names); }### Answer: @Test public void whenCalled_thenReturnListOfOddStrings() { String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"}; List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim"); List<String> actualResult = StreamIndices.getOddIndexedStrings(names); assertEquals(expectedResult, actualResult); } @Test public void givenList_whenCalled_thenReturnListOfOddIndexedStrings() { List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"); List<Indexed<String>> expectedResult = Arrays .asList(Indexed.index(1, "Bashkim"), Indexed.index(3, "Lulzim"), Indexed .index(5, "Shpetim")); List<Indexed<String>> actualResult = StreamIndices.getOddIndexedStrings(names); assertEquals(expectedResult, actualResult); }
### Question: StreamIndices { public static List<String> getOddIndexedStringsVersionTwo(String[] names) { List<String> oddIndexedNames = Stream.of(names) .zipWithIndex() .filter(tuple -> tuple._2 % 2 == 1) .map(tuple -> tuple._1) .toJavaList(); return oddIndexedNames; } static List<String> getEvenIndexedStrings(String[] names); List<String> getEvenIndexedStringsVersionTwo(List<String> names); static List<Indexed<String>> getEvenIndexedStrings(List<String> names); static List<Indexed<String>> getOddIndexedStrings(List<String> names); static List<String> getOddIndexedStrings(String[] names); static List<String> getOddIndexedStringsVersionTwo(String[] names); }### Answer: @Test public void whenCalled_thenReturnListOfOddStringsVersionTwo() { String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"}; List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim"); List<String> actualResult = StreamIndices.getOddIndexedStringsVersionTwo(names); assertEquals(expectedResult, actualResult); }
### Question: StreamApi { public static String getLastElementUsingReduce(List<String> valueList) { Stream<String> stream = valueList.stream(); return stream.reduce((first, second) -> second).orElse(null); } static String getLastElementUsingReduce(List<String> valueList); static Integer getInfiniteStreamLastElementUsingReduce(); static String getLastElementUsingSkip(List<String> valueList); }### Answer: @Test public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() { List<String> valueList = new ArrayList<>(); valueList.add("Joe"); valueList.add("John"); valueList.add("Sean"); String last = StreamApi.getLastElementUsingReduce(valueList); assertEquals("Sean", last); }
### Question: StreamApi { public static Integer getInfiniteStreamLastElementUsingReduce() { Stream<Integer> stream = Stream.iterate(0, i -> i + 1); return stream.limit(20).reduce((first, second) -> second).orElse(null); } static String getLastElementUsingReduce(List<String> valueList); static Integer getInfiniteStreamLastElementUsingReduce(); static String getLastElementUsingSkip(List<String> valueList); }### Answer: @Test public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() { int last = StreamApi.getInfiniteStreamLastElementUsingReduce(); assertEquals(19, last); }
### Question: StreamApi { public static String getLastElementUsingSkip(List<String> valueList) { long count = (long) valueList.size(); Stream<String> stream = valueList.stream(); return stream.skip(count - 1).findFirst().orElse(null); } static String getLastElementUsingReduce(List<String> valueList); static Integer getInfiniteStreamLastElementUsingReduce(); static String getLastElementUsingSkip(List<String> valueList); }### Answer: @Test public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() { List<String> valueList = new ArrayList<>(); valueList.add("Joe"); valueList.add("John"); valueList.add("Sean"); String last = StreamApi.getLastElementUsingSkip(valueList); assertEquals("Sean", last); }
### Question: ConvertContainerToAnother { @SuppressWarnings("rawtypes") public static List convertToList() { UnifiedSet<String> cars = new UnifiedSet<>(); cars.add("Toyota"); cars.add("Mercedes"); cars.add("Volkswagen"); return cars.toList(); } @SuppressWarnings("rawtypes") static List convertToList(); }### Answer: @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void whenConvertContainerToAnother_thenCorrect() { MutableList<String> cars = (MutableList) ConvertContainerToAnother.convertToList(); Assertions.assertThat(cars).containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); }
### Question: SafeAdditionUtil { int safeAdd(int a, int b) { long result = ((long) a) + b; if (result > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if (result < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) result; } }### Answer: @Test @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @Test @Parameters(method = "parametersToTestAdd") public void whenCalledWithNamedMethod_thendSafeAddAndReturn(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @Test @Parameters public void whenCalledWithnoParam_thenLoadByNameSafeAddAndReturn(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @Test @Parameters(source = TestDataProvider.class) public void whenCalledWithNamedClass_thenSafeAddAndReturn(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @Test @FileParameters("src/test/resources/JunitParamsTestParameters.csv") public void whenCalledWithCsvFile_thenSafeAddAndReturn(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); }
### Question: Account { void adjustBy(final int amount) { adjustBy(amount, System.currentTimeMillis()); } Account(final int balance); @Override String toString(); }### Answer: @Test(expected = IllegalArgumentException.class) public void givenAccount_whenDecrementTooMuch_thenShouldThrow() { Account a = new Account(10); a.adjustBy(-11); } @Test public void givenTwoThreads_whenBothApplyOperation_thenShouldThrow() throws InterruptedException { ExecutorService ex = Executors.newFixedThreadPool(2); Account a = new Account(10); CountDownLatch countDownLatch = new CountDownLatch(1); AtomicBoolean exceptionThrown = new AtomicBoolean(false); ex.submit(() -> { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } try { a.adjustBy(-6); } catch (IllegalArgumentException e) { exceptionThrown.set(true); } }); ex.submit(() -> { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } try { a.adjustBy(-5); } catch (IllegalArgumentException e) { exceptionThrown.set(true); } }); countDownLatch.countDown(); ex.awaitTermination(1, TimeUnit.SECONDS); ex.shutdown(); assertTrue(exceptionThrown.get()); }
### Question: Cnt { public int d(int a, int b) { if (b == 0) return Integer.MAX_VALUE; else return a / b; } int d(int a, int b); }### Answer: @Test public void whenSecondParamIsZeroShouldReturnIntMax(){ service = new Cnt(); int answer = service.d(100,0); assertEquals(Integer.MAX_VALUE, answer); }
### Question: JerseyClient { public static String getHelloGreeting() { return createClient().target(URI_GREETINGS) .request() .get(String.class); } static String getHelloGreeting(); static String getHiGreeting(); static Response getCustomGreeting(); }### Answer: @Test public void givenGreetingResource_whenCallingHelloGreeting_thenHelloReturned() { String response = JerseyClient.getHelloGreeting(); Assert.assertEquals("hello", response); }
### Question: JerseyClient { public static String getHiGreeting() { return createClient().target(URI_GREETINGS + "/hi") .request() .get(String.class); } static String getHelloGreeting(); static String getHiGreeting(); static Response getCustomGreeting(); }### Answer: @Test public void givenGreetingResource_whenCallingHiGreeting_thenHiReturned() { String response = JerseyClient.getHiGreeting(); Assert.assertEquals("hi", response); }
### Question: JerseyClient { public static Response getCustomGreeting() { return createClient().target(URI_GREETINGS + "/custom") .request() .post(Entity.text("custom")); } static String getHelloGreeting(); static String getHiGreeting(); static Response getCustomGreeting(); }### Answer: @Test public void givenGreetingResource_whenCallingCustomGreeting_thenCustomGreetingReturned() { Response response = JerseyClient.getCustomGreeting(); Assert.assertEquals(HTTP_OK, response.getStatus()); }
### Question: BreakContinue { public static int unlabeledBreak() { String searchName = "Wilson"; int counter = 0; List<String> names = Arrays.asList("John", "Peter", "Robert", "Wilson", "Anthony", "Donald", "Richard"); for (String name : names) { counter++; if (name.equalsIgnoreCase(searchName)) { break; } } return counter; } static int unlabeledBreak(); static int unlabeledBreakNestedLoops(); static int labeledBreak(); static int unlabeledContinue(); static int labeledContinue(); }### Answer: @Test public void whenUnlabeledBreak_ThenEqual() { assertEquals(4, unlabeledBreak()); }
### Question: BreakContinue { public static int unlabeledBreakNestedLoops() { String searchName = "Wilson"; int counter = 0; Map<String, List<String>> nameMap = new HashMap<>(); nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson")); nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold")); nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan")); Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet() .iterator(); Entry<String, List<String>> entry = null; List<String> names = null; while (iterator.hasNext()) { entry = iterator.next(); names = entry.getValue(); for (String name : names) { if (name.equalsIgnoreCase(searchName)) { counter++; break; } } } return counter; } static int unlabeledBreak(); static int unlabeledBreakNestedLoops(); static int labeledBreak(); static int unlabeledContinue(); static int labeledContinue(); }### Answer: @Test public void whenUnlabeledBreakNestedLoops_ThenEqual() { assertEquals(2, unlabeledBreakNestedLoops()); }
### Question: BreakContinue { public static int labeledBreak() { String searchName = "Wilson"; int counter = 0; Map<String, List<String>> nameMap = new HashMap<>(); nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson")); nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold")); nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan")); Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet() .iterator(); Entry<String, List<String>> entry = null; List<String> names = null; compare: while (iterator.hasNext()) { entry = iterator.next(); names = entry.getValue(); for (String name : names) { if (name.equalsIgnoreCase(searchName)) { counter++; break compare; } } } return counter; } static int unlabeledBreak(); static int unlabeledBreakNestedLoops(); static int labeledBreak(); static int unlabeledContinue(); static int labeledContinue(); }### Answer: @Test public void whenLabeledBreak_ThenEqual() { assertEquals(1, labeledBreak()); }
### Question: BreakContinue { public static int unlabeledContinue() { String searchName = "Wilson"; int counter = 0; Map<String, List<String>> nameMap = new HashMap<>(); nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson")); nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan")); Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet() .iterator(); Entry<String, List<String>> entry = null; List<String> names = null; while (iterator.hasNext()) { entry = iterator.next(); names = entry.getValue(); for (String name : names) { if (!name.equalsIgnoreCase(searchName)) { continue; } counter++; } } return counter; } static int unlabeledBreak(); static int unlabeledBreakNestedLoops(); static int labeledBreak(); static int unlabeledContinue(); static int labeledContinue(); }### Answer: @Test public void whenUnlabeledContinue_ThenEqual() { assertEquals(5, unlabeledContinue()); }
### Question: BreakContinue { public static int labeledContinue() { String searchName = "Wilson"; int counter = 0; Map<String, List<String>> nameMap = new HashMap<>(); nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson")); nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan")); Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet() .iterator(); Entry<String, List<String>> entry = null; List<String> names = null; compare: while (iterator.hasNext()) { entry = iterator.next(); names = entry.getValue(); for (String name : names) { if (name.equalsIgnoreCase(searchName)) { counter++; continue compare; } } } return counter; } static int unlabeledBreak(); static int unlabeledBreakNestedLoops(); static int labeledBreak(); static int unlabeledContinue(); static int labeledContinue(); }### Answer: @Test public void whenLabeledContinue_ThenEqual() { assertEquals(3, labeledContinue()); }
### Question: PropertiesLoader { public static Properties loadProperties(String resourceFileName) throws IOException { Properties configuration = new Properties(); InputStream inputStream = PropertiesLoader.class .getClassLoader() .getResourceAsStream(resourceFileName); configuration.load(inputStream); inputStream.close(); return configuration; } static Properties loadProperties(String resourceFileName); }### Answer: @Test public void loadProperties_whenPropertyReaded_thenSuccess() throws IOException { final String RESOURCE_FILE_NAME = "configuration.properties"; final String SAMPLE_CONF_ENTRY = "sampleConfEntry"; final String COLON_SEPARATED_CONF_ENTRY = "colonSeparatedEntry"; final String GIVEN_CONF_ENTRY_VALUE = "sample String value"; final String COLON_SEPARATED_CONF_ENTRY_VALUE = "colon separated entry value"; Properties config = PropertiesLoader.loadProperties(RESOURCE_FILE_NAME); String sampleConfEntryValue = config.getProperty(SAMPLE_CONF_ENTRY); String colonSeparatedConfEntryValue = config.getProperty(COLON_SEPARATED_CONF_ENTRY); assertEquals(GIVEN_CONF_ENTRY_VALUE, sampleConfEntryValue); assertEquals(COLON_SEPARATED_CONF_ENTRY_VALUE, colonSeparatedConfEntryValue); }
### Question: SneakyThrows { public static void throwsSneakyIOException() { sneakyThrow(new IOException("sneaky")); } static void sneakyThrow(Throwable e); static void throwsSneakyIOException(); static void main(String[] args); }### Answer: @Test public void whenCallSneakyMethod_thenThrowSneakyException() { try { SneakyThrows.throwsSneakyIOException(); } catch (Exception ex) { assertEquals("sneaky", ex.getMessage().toString()); } }
### Question: SneakyRunnable implements Runnable { @SneakyThrows public void run() { try { throw new InterruptedException(); } catch (InterruptedException e) { e.printStackTrace(); } } @SneakyThrows void run(); static void main(String[] args); }### Answer: @Test public void whenCallSneakyRunnableMethod_thenThrowException() { try { new SneakyRunnable().run(); } catch (Exception e) { assertEquals(InterruptedException.class, e.getStackTrace()); } }
### Question: BaeldungReflectionUtils { static List<String> getNullPropertiesList(Customer customer) throws Exception { PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors(); return Arrays.stream(propDescArr) .filter(nulls(customer)) .map(PropertyDescriptor::getName) .collect(Collectors.toList()); } }### Answer: @Test public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception { Customer customer = new Customer(1, "Himanshu", null, null); List<String> result = BaeldungReflectionUtils.getNullPropertiesList(customer); List<String> expectedFieldNames = Arrays.asList("emailId", "phoneNumber"); assertTrue(result.size() == expectedFieldNames.size()); assertTrue(result.containsAll(expectedFieldNames)); }
### Question: User { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (this.getClass() != o.getClass()) return false; User user = (User) o; return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); } User(long id, String name, String email); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void equals_EqualUserInstance_TrueAssertion() { Assert.assertTrue(user.equals(comparisonUser)); }
### Question: User { @Override public int hashCode() { int hash = 7; hash = 31 * hash + (int) id; hash = 31 * hash + (name == null ? 0 : name.hashCode()); hash = 31 * hash + (email == null ? 0 : email.hashCode()); logger.info("hashCode() method called - Computed hash: " + hash); return hash; } User(long id, String name, String email); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void hashCode_UserHash_TrueAssertion() { Assert.assertEquals(1792276941, user.hashCode()); }
### Question: AsciiArt { public void drawString(String text, String artChar, Settings settings) { BufferedImage image = getImageIntegerMode(settings.width, settings.height); Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings); graphics2D.drawString(text, 6, ((int) (settings.height * 0.67))); for (int y = 0; y < settings.height; y++) { StringBuilder stringBuilder = new StringBuilder(); for (int x = 0; x < settings.width; x++) { stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar); } if (stringBuilder.toString() .trim() .isEmpty()) { continue; } System.out.println(stringBuilder); } } AsciiArt(); void drawString(String text, String artChar, Settings settings); }### Answer: @Test public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() { AsciiArt asciiArt = new AsciiArt(); String text = "BAELDUNG"; Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); asciiArt.drawString(text, "*", settings); }
### Question: User implements Serializable, Cloneable { @Override protected Object clone() throws CloneNotSupportedException { return this; } User(String name, int id); User(); String getName(); void setName(String name); int getId(); void setId(int id); }### Answer: @Test public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException { User user = new User("Alice", 3); User clonedUser = (User) user.clone(); assertThat(clonedUser).isEqualTo(user); }
### Question: Palindrome { public boolean isPalindrome(String text) { String clean = text.replaceAll("\\s+", "").toLowerCase(); int length = clean.length(); int forward = 0; int backward = length - 1; while (backward > forward) { char forwardChar = clean.charAt(forward++); char backwardChar = clean.charAt(backward--); if (forwardChar != backwardChar) return false; } return true; } boolean isPalindrome(String text); boolean isPalindromeReverseTheString(String text); boolean isPalindromeUsingStringBuilder(String text); boolean isPalindromeUsingStringBuffer(String text); boolean isPalindromeRecursive(String text); boolean isPalindromeUsingIntStream(String text); }### Answer: @Test public void whenWord_shouldBePalindrome() { for (String word : words) assertTrue(palindrome.isPalindrome(word)); } @Test public void whenSentence_shouldBePalindrome() { for (String sentence : sentences) assertTrue(palindrome.isPalindrome(sentence)); }
### Question: Palindrome { public boolean isPalindromeReverseTheString(String text) { StringBuilder reverse = new StringBuilder(); String clean = text.replaceAll("\\s+", "").toLowerCase(); char[] plain = clean.toCharArray(); for (int i = plain.length - 1; i >= 0; i--) reverse.append(plain[i]); return (reverse.toString()).equals(clean); } boolean isPalindrome(String text); boolean isPalindromeReverseTheString(String text); boolean isPalindromeUsingStringBuilder(String text); boolean isPalindromeUsingStringBuffer(String text); boolean isPalindromeRecursive(String text); boolean isPalindromeUsingIntStream(String text); }### Answer: @Test public void whenReverseWord_shouldBePalindrome() { for (String word : words) assertTrue(palindrome.isPalindromeReverseTheString(word)); } @Test public void whenReverseSentence_shouldBePalindrome() { for (String sentence : sentences) assertTrue(palindrome.isPalindromeReverseTheString(sentence)); }
### Question: Palindrome { public boolean isPalindromeUsingStringBuilder(String text) { String clean = text.replaceAll("\\s+", "").toLowerCase(); StringBuilder plain = new StringBuilder(clean); StringBuilder reverse = plain.reverse(); return (reverse.toString()).equals(clean); } boolean isPalindrome(String text); boolean isPalindromeReverseTheString(String text); boolean isPalindromeUsingStringBuilder(String text); boolean isPalindromeUsingStringBuffer(String text); boolean isPalindromeRecursive(String text); boolean isPalindromeUsingIntStream(String text); }### Answer: @Test public void whenStringBuilderWord_shouldBePalindrome() { for (String word : words) assertTrue(palindrome.isPalindromeUsingStringBuilder(word)); } @Test public void whenStringBuilderSentence_shouldBePalindrome() { for (String sentence : sentences) assertTrue(palindrome.isPalindromeUsingStringBuilder(sentence)); }
### Question: Palindrome { public boolean isPalindromeUsingStringBuffer(String text) { String clean = text.replaceAll("\\s+", "").toLowerCase(); StringBuffer plain = new StringBuffer(clean); StringBuffer reverse = plain.reverse(); return (reverse.toString()).equals(clean); } boolean isPalindrome(String text); boolean isPalindromeReverseTheString(String text); boolean isPalindromeUsingStringBuilder(String text); boolean isPalindromeUsingStringBuffer(String text); boolean isPalindromeRecursive(String text); boolean isPalindromeUsingIntStream(String text); }### Answer: @Test public void whenStringBufferWord_shouldBePalindrome() { for (String word : words) assertTrue(palindrome.isPalindromeUsingStringBuffer(word)); } @Test public void whenStringBufferSentence_shouldBePalindrome() { for (String sentence : sentences) assertTrue(palindrome.isPalindromeUsingStringBuffer(sentence)); }
### Question: Palindrome { public boolean isPalindromeRecursive(String text) { String clean = text.replaceAll("\\s+", "").toLowerCase(); return recursivePalindrome(clean, 0, clean.length() - 1); } boolean isPalindrome(String text); boolean isPalindromeReverseTheString(String text); boolean isPalindromeUsingStringBuilder(String text); boolean isPalindromeUsingStringBuffer(String text); boolean isPalindromeRecursive(String text); boolean isPalindromeUsingIntStream(String text); }### Answer: @Test public void whenPalindromeRecursive_wordShouldBePalindrome() { for (String word : words) assertTrue(palindrome.isPalindromeRecursive(word)); } @Test public void whenPalindromeRecursive_sentenceShouldBePalindrome() { for (String sentence : sentences) assertTrue(palindrome.isPalindromeRecursive(sentence)); }
### Question: Palindrome { public boolean isPalindromeUsingIntStream(String text) { String temp = text.replaceAll("\\s+", "").toLowerCase(); return IntStream.range(0, temp.length() / 2) .noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1)); } boolean isPalindrome(String text); boolean isPalindromeReverseTheString(String text); boolean isPalindromeUsingStringBuilder(String text); boolean isPalindromeUsingStringBuffer(String text); boolean isPalindromeRecursive(String text); boolean isPalindromeUsingIntStream(String text); }### Answer: @Test public void whenPalindromeStreams_wordShouldBePalindrome() { for (String word : words) assertTrue(palindrome.isPalindromeUsingIntStream(word)); } @Test public void whenPalindromeStreams_sentenceShouldBePalindrome() { for (String sentence : sentences) assertTrue(palindrome.isPalindromeUsingIntStream(sentence)); }
### Question: Trie { public boolean isEmpty() { return root == null; } Trie(); void insert(String word); boolean delete(String word); boolean containsNode(String word); boolean isEmpty(); }### Answer: @Test public void whenEmptyTrie_thenNoElements() { Trie trie = new Trie(); assertFalse(trie.isEmpty()); } @Test public void givenATrie_whenAddingElements_thenTrieNotEmpty() { Trie trie = createExampleTrie(); assertFalse(trie.isEmpty()); }
### Question: Trie { public boolean containsNode(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); TrieNode node = current.getChildren().get(ch); if (node == null) { return false; } current = node; } return current.isEndOfWord(); } Trie(); void insert(String word); boolean delete(String word); boolean containsNode(String word); boolean isEmpty(); }### Answer: @Test public void givenATrie_whenAddingElements_thenTrieHasThoseElements() { Trie trie = createExampleTrie(); assertFalse(trie.containsNode("3")); assertFalse(trie.containsNode("vida")); assertTrue(trie.containsNode("Programming")); assertTrue(trie.containsNode("is")); assertTrue(trie.containsNode("a")); assertTrue(trie.containsNode("way")); assertTrue(trie.containsNode("of")); assertTrue(trie.containsNode("life")); } @Test public void givenATrie_whenLookingForNonExistingElement_thenReturnsFalse() { Trie trie = createExampleTrie(); assertFalse(trie.containsNode("99")); }
### Question: PrintClassLoader { public void printClassLoaders() throws ClassNotFoundException { System.out.println("Classloader of this class:" + PrintClassLoader.class.getClassLoader()); System.out.println("Classloader of Logging:" + Logging.class.getClassLoader()); System.out.println("Classloader of ArrayList:" + ArrayList.class.getClassLoader()); } void printClassLoaders(); }### Answer: @Test(expected = ClassNotFoundException.class) public void givenAppClassLoader_whenParentClassLoader_thenClassNotFoundException() throws Exception { PrintClassLoader sampleClassLoader = (PrintClassLoader) Class.forName(PrintClassLoader.class.getName()).newInstance(); sampleClassLoader.printClassLoaders(); Class.forName(PrintClassLoader.class.getName(), true, PrintClassLoader.class.getClassLoader().getParent()); }
### Question: CustomClassLoader extends ClassLoader { public Class getClass(String name) throws ClassNotFoundException { byte[] b = loadClassFromFile(name); return defineClass(name, b, 0, b.length); } Class getClass(String name); }### Answer: @Test public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { CustomClassLoader customClassLoader = new CustomClassLoader(); Class<?> c = customClassLoader.getClass(PrintClassLoader.class.getName()); Object ob = c.newInstance(); Method md = c.getMethod("printClassLoaders"); md.invoke(ob); }
### Question: BatchProcessing { public void useStatement(){ try { String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES ('%s','%s','%s');"; String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES ('%s','%s','%s');"; Statement statement = connection.createStatement(); for(int i = 0; i < EMPLOYEES.length; i++){ String employeeId = UUID.randomUUID().toString(); statement.addBatch(String.format(insertEmployeeSQL, employeeId, EMPLOYEES[i],DESIGNATIONS[i])); statement.addBatch(String.format(insertEmployeeAddrSQL, UUID.randomUUID().toString(),employeeId,ADDRESSES[i])); } statement.executeBatch(); connection.commit(); } catch (Exception e) { try { connection.rollback(); } catch (SQLException ex) { System.out.println("Error during rollback"); System.out.println(ex.getMessage()); } e.printStackTrace(System.out); } } void getConnection(); void createTables(); void useStatement(); void usePreparedStatement(); static void main(String[] args); }### Answer: @Test public void when_useStatement_thenInsertData_success() throws Exception { Mockito.when(connection.createStatement()).thenReturn(statement); target.useStatement(); } @Test public void when_useStatement_ifThrowException_thenCatchException() throws Exception { Mockito.when(connection.createStatement()).thenThrow(new RuntimeException()); target.useStatement(); }
### Question: ArrayInitializer { static int[] initializeArrayInLoop() { int array[] = new int[5]; for (int i = 0; i < array.length; i++) { array[i] = i + 2; } return array; } }### Answer: @Test public void whenInitializeArrayInLoop_thenCorrect() { assertArrayEquals(new int[] { 2, 3, 4, 5, 6 }, initializeArrayInLoop()); }
### Question: ArrayInitializer { static int[][] initializeMultiDimensionalArrayInLoop() { int array[][] = new int[2][5]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 5; j++) { array[i][j] = j + 1; } } return array; } }### Answer: @Test public void whenInitializeMultiDimensionalArrayInLoop_thenCorrect() { assertArrayEquals(new int[][] { { 1, 2, 3, 4, 5 }, { 1, 2, 3, 4, 5 } }, initializeMultiDimensionalArrayInLoop()); }
### Question: ArrayInitializer { static String[] initializeArrayAtTimeOfDeclarationMethod1() { String array[] = new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" }; return array; } }### Answer: @Test public void whenInitializeArrayAtTimeOfDeclarationMethod1_thenCorrect() { assertArrayEquals(new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" }, initializeArrayAtTimeOfDeclarationMethod1()); }
### Question: ArrayInitializer { static int[] initializeArrayAtTimeOfDeclarationMethod2() { int[] array = new int[] { 1, 2, 3, 4, 5 }; return array; } }### Answer: @Test public void whenInitializeArrayAtTimeOfDeclarationMethod2_thenCorrect() { assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod2()); }
### Question: ArrayInitializer { static int[] initializeArrayAtTimeOfDeclarationMethod3() { int array[] = { 1, 2, 3, 4, 5 }; return array; } }### Answer: @Test public void whenInitializeArrayAtTimeOfDeclarationMethod3_thenCorrect() { assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod3()); }
### Question: ArrayInitializer { static long[] initializeArrayUsingArraysFill() { long array[] = new long[5]; Arrays.fill(array, 30); return array; } }### Answer: @Test public void whenInitializeArrayUsingArraysFill_thenCorrect() { assertArrayEquals(new long[] { 30, 30, 30, 30, 30 }, initializeArrayUsingArraysFill()); }
### Question: ArrayInitializer { static int[] initializeArrayRangeUsingArraysFill() { int array[] = new int[5]; Arrays.fill(array, 0, 3, -50); return array; } }### Answer: @Test public void whenInitializeArrayRangeUsingArraysFill_thenCorrect() { assertArrayEquals(new int[] { -50, -50, -50, 0, 0 }, initializeArrayRangeUsingArraysFill()); }
### Question: ArrayInitializer { static int[] initializeArrayUsingArraysCopy() { int array[] = { 1, 2, 3, 4, 5 }; int[] copy = Arrays.copyOf(array, 5); return copy; } }### Answer: @Test public void whenInitializeArrayRangeUsingArraysCopy_thenCorrect() { assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayUsingArraysCopy()); }
### Question: ArrayInitializer { static int[] initializeLargerArrayUsingArraysCopy() { int array[] = { 1, 2, 3, 4, 5 }; int[] copy = Arrays.copyOf(array, 6); return copy; } }### Answer: @Test public void whenInitializeLargerArrayRangeUsingArraysCopy_thenCorrect() { assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 0 }, initializeLargerArrayUsingArraysCopy()); }
### Question: ArrayInitializer { static int[] initializeArrayUsingArraysSetAll() { int[] array = new int[20]; Arrays.setAll(array, p -> p > 9 ? 0 : p); return array; } }### Answer: @Test public void whenInitializeLargerArrayRangeUsingArraysSetAll_thenCorrect() { assertArrayEquals(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, initializeArrayUsingArraysSetAll()); }
### Question: ArrayInitializer { static char[] initializeArrayUsingArraysUtilClone() { char[] array = new char[] { 'a', 'b', 'c' }; return ArrayUtils.clone(array); } }### Answer: @Test public void whenInitializeArrayUsingArraysUtilClone_thenCorrect() { assertArrayEquals(new char[] { 'a', 'b', 'c' }, initializeArrayUsingArraysUtilClone()); }
### Question: BinaryTree { public boolean isEmpty() { return root == null; } void add(int value); boolean isEmpty(); int getSize(); boolean containsNode(int value); void delete(int value); void traverseInOrder(Node node); void traversePreOrder(Node node); void traversePostOrder(Node node); void traverseLevelOrder(); }### Answer: @Test public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { BinaryTree bt = createBinaryTree(); assertTrue(!bt.isEmpty()); }
### Question: BinaryTree { public boolean containsNode(int value) { return containsNodeRecursive(root, value); } void add(int value); boolean isEmpty(); int getSize(); boolean containsNode(int value); void delete(int value); void traverseInOrder(Node node); void traversePreOrder(Node node); void traversePostOrder(Node node); void traverseLevelOrder(); }### Answer: @Test public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { BinaryTree bt = createBinaryTree(); assertTrue(bt.containsNode(6)); assertTrue(bt.containsNode(4)); assertFalse(bt.containsNode(1)); } @Test public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() { BinaryTree bt = createBinaryTree(); assertFalse(bt.containsNode(99)); }
### Question: BinaryTree { public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); System.out.print(" " + node.value); traverseInOrder(node.right); } } void add(int value); boolean isEmpty(); int getSize(); boolean containsNode(int value); void delete(int value); void traverseInOrder(Node node); void traversePreOrder(Node node); void traversePostOrder(Node node); void traverseLevelOrder(); }### Answer: @Test public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traverseInOrder(bt.root); }
### Question: BinaryTree { public void traversePreOrder(Node node) { if (node != null) { System.out.print(" " + node.value); traversePreOrder(node.left); traversePreOrder(node.right); } } void add(int value); boolean isEmpty(); int getSize(); boolean containsNode(int value); void delete(int value); void traverseInOrder(Node node); void traversePreOrder(Node node); void traversePostOrder(Node node); void traverseLevelOrder(); }### Answer: @Test public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traversePreOrder(bt.root); }
### Question: BinaryTree { public void traversePostOrder(Node node) { if (node != null) { traversePostOrder(node.left); traversePostOrder(node.right); System.out.print(" " + node.value); } } void add(int value); boolean isEmpty(); int getSize(); boolean containsNode(int value); void delete(int value); void traverseInOrder(Node node); void traversePreOrder(Node node); void traversePostOrder(Node node); void traverseLevelOrder(); }### Answer: @Test public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traversePostOrder(bt.root); }
### Question: BinaryTree { public void traverseLevelOrder() { if (root == null) { return; } Queue<Node> nodes = new LinkedList<>(); nodes.add(root); while (!nodes.isEmpty()) { Node node = nodes.remove(); System.out.print(" " + node.value); if (node.left != null) { nodes.add(node.left); } if (node.left != null) { nodes.add(node.right); } } } void add(int value); boolean isEmpty(); int getSize(); boolean containsNode(int value); void delete(int value); void traverseInOrder(Node node); void traversePreOrder(Node node); void traversePostOrder(Node node); void traverseLevelOrder(); }### Answer: @Test public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); bt.traverseLevelOrder(); }
### Question: RecursionExample { public int powerOf10(int n){ if (n == 0){ return 1; } return powerOf10(n-1)*10; } int sum(int n); int tailSum(int currentSum, int n); int iterativeSum(int n); int powerOf10(int n); int fibonacci(int n); String toBinary(int n); int calculateTreeHeight(BinaryNode root); int max(int a,int b); }### Answer: @Test public void testPowerOf10() { int p0 = recursion.powerOf10(0); int p1 = recursion.powerOf10(1); int p4 = recursion.powerOf10(4); Assert.assertEquals(1, p0); Assert.assertEquals(10, p1); Assert.assertEquals(10000, p4); }