method2testcases
stringlengths
118
3.08k
### Question: DefaultValidator extends AbstractValidator { @Override public Validator add(Message message) { message.setBundle(bundle); messages.add(message); return this; } protected DefaultValidator(); @Inject DefaultValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier, ResourceBundle bundle, javax.validation.Validator bvalidator, MessageInterpolator interpolator, Locale locale, Messages messages); @Override Validator check(boolean condition, Message message); @Override Validator ensure(boolean expression, Message message); @Override Validator addIf(boolean expression, Message message); @Override Validator validate(Object object, Class<?>... groups); @Override Validator validate(String alias, Object object, Class<?>... groups); @Override Validator add(Message message); @Override Validator addAll(Collection<? extends Message> messages); @Override Validator addAll(Set<ConstraintViolation<T>> errors); @Override Validator addAll(String alias, Set<ConstraintViolation<T>> errors); @Override T onErrorUse(Class<T> view); @Override boolean hasErrors(); @Override List<Message> getErrors(); }### Answer: @Test public void outjectsTheRequestParameters() { try { validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); } catch (ValidationException e) { } verify(outjector).outjectRequestMap(); } @Test public void addsTheErrorsOnTheResult() { try { validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); } catch (ValidationException e) { } verify(result).include(eq("errors"), argThat(is(not(empty())))); } @Test public void forwardToCustomOnErrorPage() { try { when(logicResult.forwardTo(MyComponent.class)).thenReturn(instance); validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); fail("should stop flow"); } catch (ValidationException e) { verify(instance).logic(); } }
### Question: DefaultValidator extends AbstractValidator { @Override public List<Message> getErrors() { return messages.getErrors(); } protected DefaultValidator(); @Inject DefaultValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier, ResourceBundle bundle, javax.validation.Validator bvalidator, MessageInterpolator interpolator, Locale locale, Messages messages); @Override Validator check(boolean condition, Message message); @Override Validator ensure(boolean expression, Message message); @Override Validator addIf(boolean expression, Message message); @Override Validator validate(Object object, Class<?>... groups); @Override Validator validate(String alias, Object object, Class<?>... groups); @Override Validator add(Message message); @Override Validator addAll(Collection<? extends Message> messages); @Override Validator addAll(Set<ConstraintViolation<T>> errors); @Override Validator addAll(String alias, Set<ConstraintViolation<T>> errors); @Override T onErrorUse(Class<T> view); @Override boolean hasErrors(); @Override List<Message> getErrors(); }### Answer: @Test public void shouldNotRedirectIfHasNotErrors() { try { validator.onErrorRedirectTo(MyComponent.class).logic(); assertThat(validator.getErrors(), hasSize(0)); verify(outjector, never()).outjectRequestMap(); } catch (ValidationException e) { fail("no error occurs"); } }
### Question: DefaultValidator extends AbstractValidator { @Override public Validator addAll(Collection<? extends Message> messages) { for (Message message : messages) { add(message); } return this; } protected DefaultValidator(); @Inject DefaultValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier, ResourceBundle bundle, javax.validation.Validator bvalidator, MessageInterpolator interpolator, Locale locale, Messages messages); @Override Validator check(boolean condition, Message message); @Override Validator ensure(boolean expression, Message message); @Override Validator addIf(boolean expression, Message message); @Override Validator validate(Object object, Class<?>... groups); @Override Validator validate(String alias, Object object, Class<?>... groups); @Override Validator add(Message message); @Override Validator addAll(Collection<? extends Message> messages); @Override Validator addAll(Set<ConstraintViolation<T>> errors); @Override Validator addAll(String alias, Set<ConstraintViolation<T>> errors); @Override T onErrorUse(Class<T> view); @Override boolean hasErrors(); @Override List<Message> getErrors(); }### Answer: @Test public void testThatValidatorGoToRedirectsToTheErrorPageImmediatellyAndNotBeforeThis() { try { validator.addAll(Arrays.asList(new SimpleMessage("test", "test"))); when(pageResult.of(MyComponent.class)).thenReturn(instance); validator.onErrorUsePageOf(MyComponent.class).logic(); fail("should stop flow"); } catch (ValidationException e) { verify(instance).logic(); } }
### Question: Messages implements Serializable { public void assertAbsenceOfErrors() { if (hasUnhandledErrors()) { log.debug("Some validation errors occured: {}", getErrors()); throw new ValidationFailedException( "There are validation errors and you forgot to specify where to go. Please add in your method " + "something like:\n" + "validator.onErrorUse(page()).of(AnyController.class).anyMethod();\n" + "or any view that you like.\n" + "If you didn't add any validation error, it is possible that a conversion error had happened."); } } Messages add(Message message); List<Message> getErrors(); List<Message> getInfo(); List<Message> getWarnings(); List<Message> getSuccess(); List<Message> getAll(); List<Message> handleErrors(); boolean hasUnhandledErrors(); void assertAbsenceOfErrors(); }### Answer: @Test public void shouldNotThrowExceptionIfMessagesHasNoErrors() { messages.assertAbsenceOfErrors(); }
### Question: Messages implements Serializable { public Messages add(Message message) { get(message.getSeverity()).add(message); if(Severity.ERROR.equals(message.getSeverity())) { unhandledErrors = true; } return this; } Messages add(Message message); List<Message> getErrors(); List<Message> getInfo(); List<Message> getWarnings(); List<Message> getSuccess(); List<Message> getAll(); List<Message> handleErrors(); boolean hasUnhandledErrors(); void assertAbsenceOfErrors(); }### Answer: @Test public void testElExpressionGettingMessagesByCaegory() { messages.add(new SimpleMessage("client.id", "will generated", Severity.INFO)); messages.add(new SimpleMessage("client.name", "not null")); messages.add(new SimpleMessage("client.name", "not empty")); ELProcessor el = new ELProcessor(); el.defineBean("messages", messages); String result = el.eval("messages.errors.from('client.name')").toString(); assertThat(result, is("not null, not empty")); result = el.eval("messages.errors.from('client.name').join(' - ')").toString(); assertThat(result, is("not null - not empty")); result = el.eval("messages.errors.from('client.id')").toString(); assertThat(result, isEmptyString()); result = el.eval("messages.info.from('client.id')").toString(); assertThat(result, is("will generated")); }
### Question: DateConverter implements Converter<Date> { @Override public Date convert(String value, Class<? extends Date> type) { if (isNullOrEmpty(value)) { return null; } try { return getDateFormat().parse(value); } catch (ParseException pe) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected DateConverter(); @Inject DateConverter(Locale locale); @Override Date convert(String value, Class<? extends Date> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvert() throws ParseException { assertThat(converter.convert("10/06/2008", Date.class), is(equalTo(new SimpleDateFormat("dd/MM/yyyy") .parse("10/06/2008")))); } @Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Date.class), is(nullValue())); } @Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Date.class), is(nullValue())); } @Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("a,10/06/2008/a/b/c is not a valid date.")); converter.convert("a,10/06/2008/a/b/c", Date.class); }
### Question: PrimitiveLongConverter implements Converter<Long> { @Override public Long convert(String value, Class<? extends Long> type) { if (isNullOrEmpty(value)) { return 0L; } try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Long convert(String value, Class<? extends Long> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", long.class), is(equalTo(2L))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", long.class); } @Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, long.class), is(equalTo(0L))); } @Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", long.class), is(equalTo(0L))); }
### Question: CalendarConverter implements Converter<Calendar> { @Override public Calendar convert(String value, Class<? extends Calendar> type) { if (isNullOrEmpty(value)) { return null; } try { Date date = getDateFormat().parse(value); Calendar calendar = Calendar.getInstance(locale); calendar.setTime(date); return calendar; } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected CalendarConverter(); @Inject CalendarConverter(Locale locale); @Override Calendar convert(String value, Class<? extends Calendar> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvert() { Calendar expected = Calendar.getInstance(new Locale("pt", "BR")); expected.set(2008, 5, 10, 0, 0, 0); expected.set(Calendar.MILLISECOND, 0); assertThat(converter.convert("10/06/2008", Calendar.class), is(equalTo(expected))); } @Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Calendar.class), is(nullValue())); } @Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Calendar.class), is(nullValue())); } @Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("a,10/06/2008/a/b/c is not a valid date.")); converter.convert("a,10/06/2008/a/b/c", Calendar.class); }
### Question: PrimitiveByteConverter implements Converter<Byte> { @Override public Byte convert(String value, Class<? extends Byte> type) { if (isNullOrEmpty(value)) { return (byte) 0; } try { return Byte.parseByte(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Byte convert(String value, Class<? extends Byte> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("7", byte.class), is(equalTo((byte) 7))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", byte.class); } @Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, byte.class), is(equalTo((byte) 0))); } @Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", byte.class), is(equalTo((byte) 0))); }
### Question: LongConverter implements Converter<Long> { @Override public Long convert(String value, Class<? extends Long> type) { if (isNullOrEmpty(value)) { return null; } try { return Long.valueOf(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Long convert(String value, Class<? extends Long> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers(){ assertThat(converter.convert("2", long.class), is(equalTo(2L))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", long.class); } @Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, long.class), is(nullValue())); } @Test public void shouldNotComplainAboutEmpty() { assertThat(converter.convert("", long.class), is(nullValue())); }
### Question: PrimitiveFloatConverter implements Converter<Float> { @Override public Float convert(String value, Class<? extends Float> type) { if (isNullOrEmpty(value)) { return 0f; } try { return getNumberFormat().parse(value).floatValue(); } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected PrimitiveFloatConverter(); @Inject PrimitiveFloatConverter(Locale locale); @Override Float convert(String value, Class<? extends Float> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertWithPTBR() { assertThat(converter.convert("10,00", float.class), is(equalTo(Float.parseFloat("10.00")))); assertThat(converter.convert("10,01", float.class), is(equalTo(Float.parseFloat("10.01")))); } @Test public void shouldBeAbleToConvertWithENUS() { converter = new PrimitiveFloatConverter(new Locale("en", "US")); assertThat(converter.convert("10.00", float.class), is(equalTo(Float.parseFloat("10.00")))); assertThat(converter.convert("10.01", float.class), is(equalTo(Float.parseFloat("10.01")))); } @Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", float.class), is(equalTo(0f))); } @Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, float.class), is(equalTo(0f))); } @Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("vr3.9 is not a valid number.")); converter.convert("vr3.9", float.class); }
### Question: CharacterConverter implements Converter<Character> { @Override public Character convert(String value, Class<? extends Character> type) { if (isNullOrEmpty(value)) { return null; } if (value.length() != 1) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } return value.charAt(0); } @Override Character convert(String value, Class<? extends Character> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertCharacters() { assertThat(converter.convert("Z", Character.class), is(equalTo('Z'))); } @Test public void shouldComplainAboutStringTooBig() { exception.expect(hasConversionException("--- is not a valid character.")); converter.convert("---", Character.class); } @Test public void shouldNotComplainAboutNullAndEmpty() { assertThat(converter.convert(null, Character.class), is(nullValue())); assertThat(converter.convert("", Character.class), is(nullValue())); }
### Question: PrimitiveShortConverter implements Converter<Short> { @Override public Short convert(String value, Class<? extends Short> type) { if (isNullOrEmpty(value)) { return (short) 0; } try { return Short.parseShort(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Short convert(String value, Class<? extends Short> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers(){ assertThat(converter.convert("5", short.class), is(equalTo((short) 5))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", short.class); } @Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, short.class), is(equalTo((short) 0))); } @Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", short.class), is(equalTo((short) 0))); }
### Question: PrimitiveIntConverter implements Converter<Integer> { @Override public Integer convert(String value, Class<? extends Integer> type) { if (isNullOrEmpty(value)) { return 0; } try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Integer convert(String value, Class<? extends Integer> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", int.class), is(equalTo(2))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", int.class); } @Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, int.class), is(equalTo(0))); } @Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", int.class), is(equalTo(0))); }
### Question: ByteConverter implements Converter<Byte> { @Override public Byte convert(String value, Class<? extends Byte> type) { if (isNullOrEmpty(value)) { return null; } try { return Byte.valueOf(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Byte convert(String value, Class<? extends Byte> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", Byte.class), is(equalTo((byte) 2))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", Byte.class); } @Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, Byte.class), is(nullValue())); } @Test public void shouldNotComplainAboutEmpty() { assertThat(converter.convert("", Byte.class), is(nullValue())); }
### Question: PrimitiveCharConverter implements Converter<Character> { @Override public Character convert(String value, Class<? extends Character> type) { if (isNullOrEmpty(value)) { return '\u0000'; } if (value.length() != 1) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } return value.charAt(0); } @Override Character convert(String value, Class<? extends Character> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("r", char.class), is(equalTo('r'))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid character.")); converter.convert("---", char.class); } @Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, char.class), is(equalTo('\u0000'))); } @Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", char.class), is(equalTo('\u0000'))); }
### Question: BigDecimalConverter implements Converter<BigDecimal> { @Override public BigDecimal convert(String value, Class<? extends BigDecimal> type) { if (isNullOrEmpty(value)) { return null; } try { return (BigDecimal) getNumberFormat().parse(value); } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected BigDecimalConverter(); @Inject BigDecimalConverter(Locale locale); @Override BigDecimal convert(String value, Class<? extends BigDecimal> type); }### Answer: @Test public void shouldBeAbleToConvertWithPTBR() { assertThat(converter.convert("10,00", BigDecimal.class), is(equalTo(new BigDecimal("10.00")))); assertThat(converter.convert("10,01", BigDecimal.class), is(equalTo(new BigDecimal("10.01")))); } @Test public void shouldBeAbleToConvertWithENUS() { converter = new BigDecimalConverter(new Locale("en", "US")); assertThat(converter.convert("10.00", BigDecimal.class), is(equalTo(new BigDecimal("10.00")))); assertThat(converter.convert("10.01", BigDecimal.class), is(equalTo(new BigDecimal("10.01")))); } @Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", BigDecimal.class), is(nullValue())); } @Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, BigDecimal.class), is(nullValue())); } @Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("vr3.9 is not a valid number.")); converter.convert("vr3.9", BigDecimal.class); }
### Question: IntegerConverter implements Converter<Integer> { @Override public Integer convert(String value, Class<? extends Integer> type) { if (isNullOrEmpty(value)) { return null; } try { return Integer.valueOf(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Integer convert(String value, Class<? extends Integer> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", Integer.class), is(equalTo(2))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", Integer.class); } @Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, Integer.class), is(nullValue())); } @Test public void shouldNotComplainAboutEmpty() { assertThat(converter.convert("", Integer.class), is(nullValue())); }
### Question: BigIntegerConverter implements Converter<BigInteger> { @Override public BigInteger convert(String value, Class<? extends BigInteger> type) { if (isNullOrEmpty(value)) { return null; } try { return new BigInteger(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override BigInteger convert(String value, Class<? extends BigInteger> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertIntegerNumbers() { assertThat(converter.convert("3", BigInteger.class), is(equalTo(new BigInteger("3")))); } @Test public void shouldComplainAboutNonIntegerNumbers() { exception.expect(hasConversionException("2.3 is not a valid number.")); converter.convert("2.3", BigInteger.class); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", BigInteger.class); } @Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, BigInteger.class), is(nullValue())); } @Test public void shouldNotComplainAboutEmpty() { assertThat(converter.convert("", BigInteger.class), is(nullValue())); }
### Question: FloatConverter implements Converter<Float> { @Override public Float convert(String value, Class<? extends Float> type) { if (isNullOrEmpty(value)) { return null; } try { return getNumberFormat().parse(value).floatValue(); } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected FloatConverter(); @Inject FloatConverter(Locale locale); @Override Float convert(String value, Class<? extends Float> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertWithPTBR() { assertThat(converter.convert("10,00", Float.class), is(equalTo(new Float("10.00")))); assertThat(converter.convert("10,01", Float.class), is(equalTo(new Float("10.01")))); } @Test public void shouldBeAbleToConvertWithENUS() { converter = new FloatConverter(new Locale("en", "US")); assertThat(converter.convert("10.00", Float.class), is(equalTo(new Float("10.00")))); assertThat(converter.convert("10.01", Float.class), is(equalTo(new Float("10.01")))); } @Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Float.class), is(nullValue())); } @Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Float.class), is(nullValue())); } @Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("vr3.9 is not a valid number.")); converter.convert("vr3.9", Float.class); }
### Question: ShortConverter implements Converter<Short> { @Override public Short convert(String value, Class<? extends Short> type) { if (isNullOrEmpty(value)) { return null; } try { return Short.valueOf(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Short convert(String value, Class<? extends Short> type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", Short.class), is(equalTo((short) 2))); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", Short.class); } @Test public void shouldComplainAboutNull() { assertThat(converter.convert(null, Short.class), is(nullValue())); } @Test public void shouldComplainAboutEmpty() { assertThat(converter.convert("", Short.class), is(nullValue())); }
### Question: EnumConverter implements Converter { @Override public Object convert(String value, Class type) { if (isNullOrEmpty(value)) { return null; } if (Character.isDigit(value.charAt(0))) { return resolveByOrdinal(value, type); } else { return resolveByName(value, type); } } @Override Object convert(String value, Class type); static final String INVALID_MESSAGE_KEY; }### Answer: @Test public void shouldBeAbleToConvertByOrdinal() { Enum value = converter.convert("1", MyCustomEnum.class); MyCustomEnum second = MyCustomEnum.SECOND; assertEquals(value, second); } @Test public void shouldBeAbleToConvertByName() { Enum value = converter.convert("FIRST", MyCustomEnum.class); MyCustomEnum first = MyCustomEnum.FIRST; assertEquals(value, first); } @Test public void shouldConvertEmptyToNull() { assertThat(converter.convert("", MyCustomEnum.class), is(nullValue())); } @Test public void shouldComplainAboutInvalidIndex() { exception.expect(hasConversionException("3200 is not a valid option.")); converter.convert("3200", MyCustomEnum.class); } @Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("32a00 is not a valid option.")); converter.convert("32a00", MyCustomEnum.class); } @Test public void shouldComplainAboutInvalidOrdinal() { exception.expect(hasConversionException("THIRD is not a valid option.")); converter.convert("THIRD", MyCustomEnum.class); } @Test public void shouldAcceptNull() { assertThat(converter.convert(null, MyCustomEnum.class), is(nullValue())); }
### Question: HomeController { @Post @Public public void login(String login, String password) { final User currentUser = dao.find(login, password); validator.check(currentUser != null, new SimpleMessage("login", "invalid_login_or_password")); validator.onErrorUsePageOf(this).login(); userInfo.login(currentUser); result.redirectTo(UsersController.class).home(); } protected HomeController(); @Inject HomeController(UserDao dao, UserInfo userInfo, Result result, Validator validator); @Post @Public void login(String login, String password); void logout(); @Public @Get void login(); @Public @Get void about(); }### Answer: @Test public void shouldLoginWhenUserExists() { when(dao.find(user.getLogin(), user.getPassword())).thenReturn(user); controller.login(user.getLogin(), user.getPassword()); assertThat(validator.getErrors(), empty()); } @Test(expected=ValidationException.class) public void shouldNotLoginWhenUserDoesNotExists() { when(dao.find(user.getLogin(), user.getPassword())).thenReturn(null); controller.login(user.getLogin(), user.getPassword()); } @Test public void shouldNotLoginWhenUserDoesNotExistsAndHasOneError() { when(dao.find(user.getLogin(), user.getPassword())).thenReturn(null); try { controller.login(user.getLogin(), user.getPassword()); fail("Should throw an exception."); } catch (ValidationException e) { List<Message> errors = e.getErrors(); assertThat(errors, hasSize(1)); assertTrue(errors.contains(new SimpleMessage("login", "invalid_login_or_password"))); } }
### Question: HomeController { public void logout() { userInfo.logout(); result.redirectTo(this).login(); } protected HomeController(); @Inject HomeController(UserDao dao, UserInfo userInfo, Result result, Validator validator); @Post @Public void login(String login, String password); void logout(); @Public @Get void login(); @Public @Get void about(); }### Answer: @Test public void shouldLogoutUser() { controller.logout(); verify(userInfo).logout(); }
### Question: UsersController { @Get("/") public void home() { result.include("musicTypes", MusicType.values()); } protected UsersController(); @Inject UsersController(UserDao dao, Result result, Validator validator, UserInfo userInfo, MusicDao musicDao); @Get("/") void home(); @Get("/users") void list(); @Path("/users") @Post @Public void add(@Valid @LoginAvailable User user); @Path("/users/{user.login}") @Get void show(User user); @Path("/users/{user.login}/musics/{music.id}") @Put void addToMyList(User user, Music music); }### Answer: @Test public void shouldOpenHomeWithMusicTypes() { controller.home(); MusicType[] musicsType = (MusicType[]) result.included().get("musicTypes"); assertThat(Arrays.asList(musicsType), hasSize(MusicType.values().length)); }
### Question: UsersController { @Get("/users") public void list() { result.include("users", userDao.listAll()); } protected UsersController(); @Inject UsersController(UserDao dao, Result result, Validator validator, UserInfo userInfo, MusicDao musicDao); @Get("/") void home(); @Get("/users") void list(); @Path("/users") @Post @Public void add(@Valid @LoginAvailable User user); @Path("/users/{user.login}") @Get void show(User user); @Path("/users/{user.login}/musics/{music.id}") @Put void addToMyList(User user, Music music); }### Answer: @SuppressWarnings("unchecked") @Test public void shouldListAllUsers() { when(userDao.listAll()).thenReturn(Arrays.asList(user, anotherUser)); controller.list(); assertThat((List<User>)result.included().get("users"), contains(user, anotherUser)); }
### Question: UsersController { @Path("/users") @Post @Public public void add(@Valid @LoginAvailable User user) { validator.onErrorUsePageOf(HomeController.class).login(); userDao.add(user); result.include("notice", "User " + user.getName() + " successfully added"); result.redirectTo(HomeController.class).login(); } protected UsersController(); @Inject UsersController(UserDao dao, Result result, Validator validator, UserInfo userInfo, MusicDao musicDao); @Get("/") void home(); @Get("/users") void list(); @Path("/users") @Post @Public void add(@Valid @LoginAvailable User user); @Path("/users/{user.login}") @Get void show(User user); @Path("/users/{user.login}/musics/{music.id}") @Put void addToMyList(User user, Music music); }### Answer: @Test public void shouldAddUser() { controller.add(user); verify(userDao).add(user); assertThat(result.included().get("notice").toString(), is("User " + user.getName() + " successfully added")); }
### Question: UsersController { @Path("/users/{user.login}") @Get public void show(User user) { result.include("user", userDao.find(user.getLogin())); result.forwardTo("/WEB-INF/jsp/users/view.jsp"); } protected UsersController(); @Inject UsersController(UserDao dao, Result result, Validator validator, UserInfo userInfo, MusicDao musicDao); @Get("/") void home(); @Get("/users") void list(); @Path("/users") @Post @Public void add(@Valid @LoginAvailable User user); @Path("/users/{user.login}") @Get void show(User user); @Path("/users/{user.login}/musics/{music.id}") @Put void addToMyList(User user, Music music); }### Answer: @Test public void shouldShowUser() { when(userDao.find(user.getLogin())).thenReturn(user); controller.show(user); assertThat((User) result.included().get("user"), is(user)); }
### Question: MusicController { @Path("/musics") @Post public void add(final @NotNull @Valid Music music, UploadedFile file) { validator.onErrorForwardTo(UsersController.class).home(); musicDao.add(music); User currentUser = userInfo.getUser(); userDao.refresh(currentUser); currentUser.add(music); if (file != null) { musics.save(file, music); logger.info("Uploaded file: {}", file.getFileName()); } result.include("notice", music.getTitle() + " music added"); result.redirectTo(UsersController.class).home(); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo, Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer: @Test public void shouldAddMusic() { when(userInfo.getUser()).thenReturn(user); controller.add(music, uploadFile); verify(dao).add(music); verify(musics).save(uploadFile, music); assertThat(result.included().get("notice").toString(), is(music.getTitle() + " music added")); }
### Question: MusicController { @Path("/musics/{music.id}") @Get public void show(Music music) { result.include("music", musicDao.load(music)); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo, Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer: @Test public void shouldShowMusicWhenExists() { when(dao.load(music)).thenReturn(music); controller.show(music); assertNotNull(result.included().get("music")); assertThat((Music) result.included().get("music"), is(music)); } @Test public void shouldNotShowMusicWhenDoesNotExists() { when(dao.load(music)).thenReturn(null); controller.show(music); assertNull(result.included().get("music")); }
### Question: VRaptorRequest extends HttpServletRequestWrapper implements MutableRequest { @Override public String getRequestedUri() { if (getAttribute(INCLUDE_REQUEST_URI) != null) { return (String) getAttribute(INCLUDE_REQUEST_URI); } String uri = getRelativeRequestURI(this); return uri.replaceFirst("(?i);jsessionid=.*$", ""); } VRaptorRequest(HttpServletRequest request); @Override String getParameter(String name); @Override Enumeration<String> getParameterNames(); @Override String[] getParameterValues(String name); @Override Map<String, String[]> getParameterMap(); @Override void setParameter(String key, String... value); @Override String getRequestedUri(); static String getRelativeRequestURI(HttpServletRequest request); @Override String toString(); }### Answer: @Test public void strippsContextPath() { when(request.getContextPath()).thenReturn("/myapp"); when(request.getRequestURI()).thenReturn("/myapp/somepage"); assertThat(vraptor.getRequestedUri(), is(equalTo("/somepage"))); } @Test public void strippsRootContextPath() { when(request.getContextPath()).thenReturn("/"); when(request.getRequestURI()).thenReturn("/somepage"); assertThat(vraptor.getRequestedUri(), is(equalTo("/somepage"))); }
### Question: MusicController { @Get("/musics/search") public void search(Music music) { String title = MoreObjects.firstNonNull(music.getTitle(), ""); result.include("musics", this.musicDao.searchSimilarTitle(title)); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo, Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer: @SuppressWarnings("unchecked") @Test public void shouldReturnMusicList() { when(dao.searchSimilarTitle(music.getTitle())).thenReturn(Arrays.asList(music)); controller.search(music); assertThat((List<Music>) result.included().get("musics"), contains(music)); } @SuppressWarnings("unchecked") @Test public void shouldReturnEmptyList() { when(dao.searchSimilarTitle(music.getTitle())).thenReturn(new ArrayList<Music>()); controller.search(music); List<Music> musics = (List<Music>) result.included().get("musics"); assertThat(musics, empty()); }
### Question: MusicController { @Path("/musics/download/{m.id}") @Get public Download download(Music m) throws FileNotFoundException { Music music = musicDao.load(m); File file = musics.getFile(music); String contentType = "audio/mpeg"; String filename = music.getTitle() + ".mp3"; return new FileDownload(file, contentType, filename); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo, Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer: @Test public void shouldNotDownloadMusicWhenDoesNotExist() { when(dao.load(music)).thenReturn(music); when(musics.getFile(music)).thenReturn(new File("/tmp/uploads/Music_" + music.getId() + ".mp3")); try { controller.download(music); fail("Should throw an exception."); } catch (FileNotFoundException e) { verify(musics).getFile(music); } }
### Question: MusicController { @Public @Path("/musics/list/json") public void showAllMusicsAsJSON() { result.use(json()).from(musicDao.listAll()).serialize(); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo, Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer: @Test public void shouldShowAllMusicsAsJSON() throws Exception { when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsJSON(); assertThat(result.serializedResult(), is("{\"list\":[{\"id\":1,\"title\":\"Some Music\"," + "\"description\":\"Some description\",\"type\":\"ROCK\"}]}")); }
### Question: MusicController { @Public @Path("/musics/list/xml") public void showAllMusicsAsXML() { result.use(xml()).from(musicDao.listAll()).serialize(); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo, Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer: @Test public void shouldShowAllMusicsAsXML() throws Exception { when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsXML(); assertThat(result.serializedResult(), is("<list><music><id>1</id><title>Some Music</title><description>Some description</description><type>ROCK</type></music></list>")); }
### Question: MusicController { @Public @Path("/musics/list/http") public void showAllMusicsAsHTTP() { result.use(http()).body("<p class=\"content\">"+ musicDao.listAll().toString()+"</p>"); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo, Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer: @Test public void shouldShowAllMusicsAsHTTP() { MockHttpResult mockHttpResult = new MockHttpResult(); controller = new MusicController(dao, userInfo, mockHttpResult, validator, musics, userDao); when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsHTTP(); assertThat(mockHttpResult.getBody(), is("<p class=\"content\">"+ Arrays.asList(music).toString()+"</p>")); }
### Question: MusicController { @Public @Path("musics/listAs") public void listAs() { result.use(representation()) .from(musicDao.listAll()).serialize(); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo, Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer: @Test public void shouldListAs() throws Exception { when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.listAs(); assertThat(result.serializedResult(), is("<list><music><id>1</id><title>Some Music</title><description>Some description</description><type>ROCK</type></music></list>")); }
### Question: Rules { protected final RouteBuilder routeFor(String uri) { RouteBuilder rule = router.builderFor(uri); rule.withPriority(Integer.MIN_VALUE); this.routesToBuild.add(rule); return rule; } Rules(Router router); abstract void routes(); }### Answer: @Test public void allowsAdditionOfRouteBuildersByDefaultWithNoStrategy() { exception.expect(IllegalRouteException.class); new Rules(router) { @Override public void routes() { routeFor(""); } }; }
### Question: DefaultRouter implements Router { @Override public <T> String urlFor(final Class<T> type, final Method method, Object... params) { final Class<?> rawtype = proxifier.isProxyType(type) ? type.getSuperclass() : type; final Invocation invocation = new Invocation(rawtype, method); Route route = cache.fetch(invocation, new Supplier<Route>() { @Override public Route get() { return FluentIterable.from(routes).filter(canHandle(rawtype, method)) .first().or(NULL); } }); logger.debug("Selected route for {} is {}", method, route); String url = route.urlFor(type, method, params); logger.debug("Returning URL {} for {}", url, route); return url; } protected DefaultRouter(); @Inject DefaultRouter(Proxifier proxifier, TypeFinder finder, Converters converters, ParameterNameProvider nameProvider, Evaluator evaluator, EncodingHandler encodingHandler, CacheStore<Invocation, Route> cache); @Override RouteBuilder builderFor(String uri); @Override void add(Route r); @Override ControllerMethod parse(String uri, HttpMethod method, MutableRequest request); @Override EnumSet<HttpMethod> allowedMethodsFor(String uri); @Override String urlFor(final Class<T> type, final Method method, Object... params); @Override List<Route> allRoutes(); }### Answer: @Test public void shouldReturnTheFirstRouteFound() throws Exception { Method method = MyController.class.getDeclaredMethod("listDogs", Integer.class); registerRulesFor(MyController.class); assertEquals("/dogs/1", router.urlFor(MyController.class, method, new Object[] { "1" })); } @Test public void canFindUrlForProxyClasses() throws Exception { registerRulesFor(MyController.class); MyController proxy = proxifier.proxify(MyController.class, null); Class<? extends MyController> type = proxy.getClass(); Method method = type.getMethod("notAnnotated"); assertEquals("/my/notAnnotated", router.urlFor(type, method)); }
### Question: AVSessionCacheHelper { static synchronized SessionTagCache getTagCacheInstance() { if (null == tagCacheInstance) { tagCacheInstance = new SessionTagCache(); } return tagCacheInstance; } }### Answer: @Test public void testRemoveNotExistTag() { AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, testClientTag); AVSessionCacheHelper.getTagCacheInstance().removeSession("test11"); Map<String, String> map = AVSessionCacheHelper.getTagCacheInstance().getAllSession(); Assert.assertTrue(map.size() == 1); Assert.assertTrue(testClientTag.equals(map.get(testClientId))); } @Test public void testRemoveExistTag() { AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, testClientTag); AVSessionCacheHelper.getTagCacheInstance().removeSession(testClientId); Map<String, String> map = AVSessionCacheHelper.getTagCacheInstance().getAllSession(); Assert.assertTrue(map.size() == 0); } @Test public void testTagCacheAdd() { AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, testClientTag); Map<String, String> clientMap = AVSessionCacheHelper.getTagCacheInstance().getAllSession(); Assert.assertTrue(clientMap.size() == 1); Assert.assertTrue(testClientTag.equals(clientMap.get(testClientId))); } @Test public void testUpdateTag() { String updateTag = "updateTag"; AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, testClientTag); AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, updateTag); Map<String, String> clientMap = AVSessionCacheHelper.getTagCacheInstance().getAllSession(); Assert.assertTrue(clientMap.size() == 1); Assert.assertTrue(updateTag.equals(clientMap.get(testClientId))); }
### Question: AVSMS { public static void requestSMSCode(String phone, AVSMSOption smsOption) throws AVException { requestSMSCodeInBackground(phone, smsOption, true, new RequestMobileCodeCallback() { @Override public void done(AVException e) { if (e != null) { AVExceptionHolder.add(e); } } @Override public boolean mustRunOnUIThread() { return false; } }); if (AVExceptionHolder.exists()) { throw AVExceptionHolder.remove(); } } static void requestSMSCode(String phone, AVSMSOption smsOption); static void requestSMSCodeInBackground(String phone, AVSMSOption option, RequestMobileCodeCallback callback); static void verifySMSCode(String code, String mobilePhoneNumber); static void verifySMSCodeInBackground(String code, String phoneNumber, AVMobilePhoneVerifyCallback callback); }### Answer: @Test public void testRequestSMSCode() throws AVException { AVOSCloud.requestSMSCode(PHONE); } @Test public void testRequestSMSCode1() throws AVException { AVOSCloud.requestSMSCode(PHONE, APPLICATION_NAME, OPERATION, TTL); } @Test public void testRequestSMSCode2() throws AVException { AVOSCloud.requestSMSCode(PHONE, TEMPLATE_NAME, ENV_MAP); } @Test public void testRequestSMSCode3() throws AVException { AVOSCloud.requestSMSCode(PHONE, TEMPLATE_NAME, SIGNATURE_NAME, ENV_MAP); }
### Question: AVSMS { public static void verifySMSCode(String code, String mobilePhoneNumber) throws AVException { verifySMSCodeInBackground(code, mobilePhoneNumber, true, new AVMobilePhoneVerifyCallback() { @Override public void done(AVException e) { if (e != null) { AVExceptionHolder.add(e); } } @Override public boolean mustRunOnUIThread() { return false; } }); if (AVExceptionHolder.exists()) { throw AVExceptionHolder.remove(); } } static void requestSMSCode(String phone, AVSMSOption smsOption); static void requestSMSCodeInBackground(String phone, AVSMSOption option, RequestMobileCodeCallback callback); static void verifySMSCode(String code, String mobilePhoneNumber); static void verifySMSCodeInBackground(String code, String phoneNumber, AVMobilePhoneVerifyCallback callback); }### Answer: @Test public void testVerifySMSCode() throws AVException { AVOSCloud.verifySMSCode(CODE, PHONE); }
### Question: AVSMS { public static void verifySMSCodeInBackground(String code, String phoneNumber, AVMobilePhoneVerifyCallback callback) { verifySMSCodeInBackground(code, phoneNumber, false, callback); } static void requestSMSCode(String phone, AVSMSOption smsOption); static void requestSMSCodeInBackground(String phone, AVSMSOption option, RequestMobileCodeCallback callback); static void verifySMSCode(String code, String mobilePhoneNumber); static void verifySMSCodeInBackground(String code, String phoneNumber, AVMobilePhoneVerifyCallback callback); }### Answer: @Test public void testVerifySMSCodeInBackground() throws AVException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); AVOSCloud.verifySMSCodeInBackground(CODE, PHONE, new AVMobilePhoneVerifyCallback() { @Override public void done(AVException e) { latch.countDown(); } }); latch.await(); }
### Question: SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { public boolean isEmpty() { return mSnackbarViews == null || mSnackbarViews.size() == 0; } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer: @Test public void testZeroAdapterSize(){ Assert.assertTrue(mAdapter.isEmpty()); }
### Question: SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int position) { View view = mSnackbarViews.get(position).onCreateView(parent); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer: @Test public void testOnCreateViewHolder() throws Exception { mAdapter.addItem(viewMock); PowerMockito.whenNew(SnackbarAdapter.ViewHolder.class).withAnyArguments().thenReturn(mViewHolder); mAdapter.onCreateViewHolder(null, 0); Mockito.verify(viewMock, Mockito.times(1)).onCreateView(null); }
### Question: SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { @Override public void onBindViewHolder(ViewHolder holder, int position) { SnackbarView snackbarView = mSnackbarViews.get(position); if (snackbarView != null) { snackbarView.onBindView(); } } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer: @Test public void testOnBindViewHolder() throws Exception{ mAdapter.addItem(viewMock); PowerMockito.whenNew(SnackbarAdapter.ViewHolder.class).withAnyArguments().thenReturn(mViewHolder); mAdapter.onCreateViewHolder(null, 0); mAdapter.onBindViewHolder(mViewHolder,0); Mockito.verify(viewMock, Mockito.times(1)).onBindView(); }
### Question: SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { public synchronized void addItem(SnackbarView item) { mSnackbarViews.add(item); int position = mSnackbarViews.indexOf(item); notifyItemInserted(position); } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer: @Test public void testAddItem(){ mAdapter.addItem(viewMock); Assert.assertEquals(mAdapter.getItemCount(),1); }
### Question: SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { public synchronized void removeItem(SnackbarView view) { int position = mSnackbarViews.indexOf(view); if (position > -1) { mSnackbarViews.remove(position); notifyItemRemoved(position); } } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer: @Test public void testRemoveItem(){ mAdapter.addItem(viewMock); Assert.assertEquals(mAdapter.getItemCount(),1); mAdapter.removeItem(viewMock); Assert.assertEquals(mAdapter.getItemCount(),0); }
### Question: NumberInterval { @Override public boolean equals(Object obj) { if (!(obj instanceof NumberInterval)) { return false; } NumberInterval rhs = (NumberInterval) obj; return Objects.equals(low, rhs.low) && Objects.equals(high, rhs.high); } NumberInterval(); NumberInterval(NumberIntervalBoundary low, NumberIntervalBoundary high); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); void validate(); boolean overlaps(NumberInterval rhs); boolean doesNotOverlap(NumberInterval rhs); boolean contains(Double value); NumberIntervalBoundary getLow(); void setLow(NumberIntervalBoundary low); NumberIntervalBoundary getHigh(); void setHigh(NumberIntervalBoundary high); }### Answer: @Test public void testEqualsNotEqualToNull() { Object rhs = null; NumberInterval instance = new NumberInterval(); assertFalse(instance.equals(rhs)); } @Test public void testEqualsNotEqualToOtherClasses() { Object rhs = new Object(); NumberInterval instance = new NumberInterval(); assertFalse(instance.equals(rhs)); } @Test public void testEquals() { NumberInterval rhs = new NumberInterval(); rhs.setLow(new NumberIntervalBoundary(0.0)); rhs.setHigh(new NumberIntervalBoundary(10.0)); NumberInterval instance = new NumberInterval(); instance.setLow(new NumberIntervalBoundary(0.0)); instance.setHigh(new NumberIntervalBoundary(10.0)); assertTrue(instance.equals(rhs)); }
### Question: StringAttributeDomainDto extends AttributeDomainDto { @Override public void validate() throws BadValueException { if (regex == null) { return; } try { Pattern.compile(regex); } catch (PatternSyntaxException ex) { throw new BadValueException("Invalid regex: " + ex.getMessage(), ex); } } StringAttributeDomainDto(); StringAttributeDomainDto(String regex); @Override AttributeType getType(); @Override void accept(AttributeDomainDtoVisitor visitor); @Override void validate(); String getRegex(); void setRegex(String regex); }### Answer: @Test public void testValidateNoRegex() throws BadValueException { StringAttributeDomainDto instance = new StringAttributeDomainDto(); instance.validate(); } @Test public void testValidateEmptyRegex() throws BadValueException { StringAttributeDomainDto instance = new StringAttributeDomainDto(""); instance.validate(); } @Test(expected = PatternSyntaxException.class) public void testValidateBadRegex() throws BadValueException, Throwable { StringAttributeDomainDto instance = new StringAttributeDomainDto("["); try { instance.validate(); } catch (BadValueException ex) { if (ex.getCause() instanceof PatternSyntaxException) { throw ex.getCause(); } throw ex; } } @Test public void testValidateRegex() throws BadValueException { StringAttributeDomainDto instance = new StringAttributeDomainDto("prefix-[0-9]+"); instance.validate(); }
### Question: NumberIntervalBoundary { @Override public int hashCode() { return Objects.hash(this.boundary, isInclusive() ? Boolean.TRUE : Boolean.FALSE); } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer: @Test public void testHashCodeForEqualInstances() { int lhs = new NumberIntervalBoundary(1.1, Boolean.FALSE).hashCode(); int rhs = new NumberIntervalBoundary(1.1, Boolean.FALSE).hashCode(); assertEquals(lhs, rhs); }
### Question: NumberIntervalBoundary { @JsonIgnore public boolean isInclusive() { return inclusive != null && inclusive; } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer: @Test public void testNotIsInclusiveByDefault() { NumberIntervalBoundary instance = new NumberIntervalBoundary(); assertFalse(instance.isInclusive()); } @Test public void testNotIsInclusiveWhenConstructedWithFalse() { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0, false); assertFalse(instance.isInclusive()); } @Test public void testNotIsInclusiveWhenConstructedWithNull() { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0, null); assertFalse(instance.isInclusive()); } @Test public void testIsInclusiveWhenConstructedWithTrue() { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0, true); assertTrue(instance.isInclusive()); }
### Question: NumberIntervalBoundary { public int compareBoundaryTo(NumberIntervalBoundary rhs) { return boundary.compareTo(rhs.getBoundary()); } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer: @Test public void testCompareBoundaryTo() { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0); assertThat(instance.compareBoundaryTo(new NumberIntervalBoundary(0.0)), comparesEqualTo(0)); assertThat(instance.compareBoundaryTo(new NumberIntervalBoundary(-5.0)), greaterThan(0)); assertThat(instance.compareBoundaryTo(NumberIntervalBoundary.NEGATIVE_INFINITY), greaterThan(0)); assertThat(instance.compareBoundaryTo(new NumberIntervalBoundary(5.0)), lessThan(0)); assertThat(instance.compareBoundaryTo(NumberIntervalBoundary.POSITIVE_INFINITY), lessThan(0)); }
### Question: NumberInterval { @Override public String toString() { return lowToString() + ", " + highToString(); } NumberInterval(); NumberInterval(NumberIntervalBoundary low, NumberIntervalBoundary high); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); void validate(); boolean overlaps(NumberInterval rhs); boolean doesNotOverlap(NumberInterval rhs); boolean contains(Double value); NumberIntervalBoundary getLow(); void setLow(NumberIntervalBoundary low); NumberIntervalBoundary getHigh(); void setHigh(NumberIntervalBoundary high); }### Answer: @Test public void testToString() { NumberInterval instance; instance = new NumberInterval(); assertEquals("null, null", instance.toString()); instance = new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, NumberIntervalBoundary.POSITIVE_INFINITY); assertEquals("(-Infinity, Infinity)", instance.toString()); instance = new NumberInterval( new NumberIntervalBoundary(0.0, true), new NumberIntervalBoundary(10.3, false)); assertEquals("[0.0, 10.3)", instance.toString()); instance = new NumberInterval( new NumberIntervalBoundary(0.0, null), new NumberIntervalBoundary(10.3, true)); assertEquals("(0.0, 10.3]", instance.toString()); }
### Question: NumberIntervalBoundary { public void validate() throws BadValueException { if (boundary == null) { throw new BadValueException("NumberIntervalBoundary.boundary is required"); } } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer: @Test public void testValidateValid() throws Exception { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0); instance.validate(); } @Test(expected = BadValueException.class) public void testValidateInvalid() throws Exception { NumberIntervalBoundary instance = new NumberIntervalBoundary(); instance.validate(); }
### Question: AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public ApiObjectRef create(CreateAgentArg createArg, String routerRef) throws CommsRouterException { return post(createArg, routerRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer: @Test public void create() throws Exception { String agentRef = UUID.randomUUID().toString(); stubFor(post(urlEqualTo("/api/routers/" + routerRef + "/agents")) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(201) .withHeader("Content-Type", "application/json") .withBody("{\"ref\":\"" + agentRef + "\"}"))); CreateAgentArg createArg = new CreateAgentArg(); createArg.setAddress("sip:[email protected]"); ApiObjectRef apiObjectId = serviceClient.create(createArg, routerRef); LOGGER.debug("apiObjectId: {}", apiObjectId); assertEquals("agentRef", agentRef, apiObjectId.getRef()); }
### Question: AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef) throws CommsRouterException { return put(createArg, objectRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer: @Test public void createWithId() throws Exception { String agentRef = UUID.randomUUID().toString(); stubFor(put(urlEqualTo("/api/routers/" + routerRef + "/agents/" + agentRef)) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(201) .withHeader("Content-Type", "application/json") .withBody("{\"ref\":\"" + agentRef + "\"}"))); CreateAgentArg createArg = new CreateAgentArg(); createArg.setAddress("sip:[email protected]"); ApiObjectRef apiObjectRef = serviceClient.replace(createArg, new RouterObjectRef(agentRef, routerRef)); LOGGER.debug("apiObjectId: {}", apiObjectRef); assertEquals("agentRef", agentRef, apiObjectRef.getRef()); }
### Question: AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public void update(UpdateAgentArg updateArg, RouterObjectRef objectRef) throws CommsRouterException { post(updateArg, objectRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer: @Test public void update() throws Exception { String agentId = UUID.randomUUID().toString(); stubFor(put(urlEqualTo("/api/routers/" + routerRef + "/agents/" + agentId)) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); UpdateAgentArg updateAgentArg = new UpdateAgentArg(); updateAgentArg.setAddress("sip:[email protected]"); serviceClient.update(updateAgentArg, new RouterObjectRef(agentId, routerRef)); }
### Question: AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public AgentDto get(RouterObjectRef routerObjectRef) throws CommsRouterException { return getItem(routerObjectRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer: @Test public void get() throws Exception { String agentId = UUID.randomUUID().toString(); AgentDto agent = new AgentDto(); agent.setAddress("sip:[email protected]"); stubFor(WireMock.get(urlEqualTo("/api/routers/" + routerRef + "/agents/" + agentId)) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(objectMapper.writeValueAsString(agent)))); AgentDto agentDto = serviceClient.get(new RouterObjectRef(agentId, routerRef)); assertNotNull("agent is found", agentDto); assertEquals("address matches", agent.getAddress(), agentDto.getAddress()); }
### Question: AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public PaginatedList<AgentDto> list(PagingRequest request) throws CommsRouterException { PagingRequest pagingRequest = new PagingRequest( routerRef, request.getToken(), request.getPerPage(), request.getSort(), request.getQuery()); return getList(pagingRequest, new GenericType<List<AgentDto>>() {}); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer: @Test public void list() throws Exception { }
### Question: AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public void delete(RouterObjectRef routerObjectRef) { routerObjectRef.setRouterRef(routerRef); deleteRequest(routerObjectRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer: @Test public void delete() throws Exception { String agentRef = UUID.randomUUID().toString(); stubFor(WireMock.delete(urlEqualTo("/api/routers/" + routerRef + "/agents/" + agentRef)) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); serviceClient.delete(new RouterObjectRef(agentRef, routerRef)); }
### Question: ConfigurationImpl implements Configuration { @Override public JWTAuthMethod getJwtAuthMethod() { return jwtAuthMethod; } @Inject ConfigurationImpl(ConfigurationProperties properties); @Override JWTAuthMethod getJwtAuthMethod(); @Override Endpoint getAssociatedPhone(); @Override String getCallbackBaseUrl(); @Override String getNexmoCallbackBaseUrl(); @Override String getCommsApiEndpoint(); @Override String getCommsRouterId(); @Override String getMusicOnHoldUrl(); @Override String getCommsQueueId(); @Override String getCommsPlanId(); }### Answer: @Test public void getJwtAuthMethod() throws Exception { assertNotNull("JWT is not null", configuration.getJwtAuthMethod()); }
### Question: ConfigurationImpl implements Configuration { @Override public Endpoint getAssociatedPhone() { return phoneEndpoint; } @Inject ConfigurationImpl(ConfigurationProperties properties); @Override JWTAuthMethod getJwtAuthMethod(); @Override Endpoint getAssociatedPhone(); @Override String getCallbackBaseUrl(); @Override String getNexmoCallbackBaseUrl(); @Override String getCommsApiEndpoint(); @Override String getCommsRouterId(); @Override String getMusicOnHoldUrl(); @Override String getCommsQueueId(); @Override String getCommsPlanId(); }### Answer: @Test public void getAssociatedPhone() throws Exception { assertEquals("Phone equals", "17072158889", configuration.getAssociatedPhone().toLog()); }
### Question: ConfigurationImpl implements Configuration { @Override public String getCallbackBaseUrl() { return callbackBaseUrl; } @Inject ConfigurationImpl(ConfigurationProperties properties); @Override JWTAuthMethod getJwtAuthMethod(); @Override Endpoint getAssociatedPhone(); @Override String getCallbackBaseUrl(); @Override String getNexmoCallbackBaseUrl(); @Override String getCommsApiEndpoint(); @Override String getCommsRouterId(); @Override String getMusicOnHoldUrl(); @Override String getCommsQueueId(); @Override String getCommsPlanId(); }### Answer: @Test public void getCallbackBaseUrl() throws Exception { assertEquals("Url equals", "https: }
### Question: Cfg4jConfiguration implements ConfigurationProperties { @Override public String callbackBaseUrl() { return provider.getProperty("app.callbackBaseUrl", String.class); } Cfg4jConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer: @Test public void getCallbackBaseUrl() throws Exception { assertEquals("Url equals", "https: }
### Question: Cfg4jConfiguration implements ConfigurationProperties { @Override public String phone() { return provider.getProperty("app.phone", String.class); } Cfg4jConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer: @Test public void getPhone() throws Exception { assertEquals("Phone equals", "17072158889", configuration.phone()); }
### Question: Cfg4jConfiguration implements ConfigurationProperties { @Override public String appId() { return provider.getProperty("nexmo.appId", String.class); } Cfg4jConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer: @Test public void getAppId() throws Exception { assertEquals("App Id equals", "some-app-id", configuration.appId()); }
### Question: Cfg4jConfiguration implements ConfigurationProperties { @Override public String appPrivateKey() { return provider.getProperty("nexmo.appPrivateKey", String.class); } Cfg4jConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer: @Test public void getPrivateKey() throws Exception { assertNotNull("JWT is not null", configuration.appPrivateKey()); }
### Question: PropertiesConfiguration implements ConfigurationProperties { @Override public String callbackBaseUrl() { return properties.getProperty(CALLBACK_BASE_URL); } PropertiesConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer: @Test public void getCallbackBaseUrl() throws Exception { assertEquals("Url equals", "https: }
### Question: PropertiesConfiguration implements ConfigurationProperties { @Override public String phone() { return properties.getProperty(APP_PHONE); } PropertiesConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer: @Test public void getPhone() throws Exception { assertEquals("Phone equals", "17072158889", configuration.phone()); }
### Question: PropertiesConfiguration implements ConfigurationProperties { @Override public String appId() { return properties.getProperty(NEXMO_APP_ID); } PropertiesConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer: @Test public void getAppId() throws Exception { assertEquals("App Id equals", "some-app-id", configuration.appId()); }
### Question: PropertiesConfiguration implements ConfigurationProperties { @Override public String appPrivateKey() { return properties.getProperty(NEXMO_APP_PRIVATE_KEY); } PropertiesConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer: @Test public void getPrivateKey() throws Exception { assertNotNull("JWT is not null", configuration.appPrivateKey()); }
### Question: JEvalEvaluator implements CommsRouterEvaluator { @Override public void validate() throws ExpressionException { long millis = System.currentTimeMillis(); evaluator.validateImpl(); LOGGER.trace("Predicate expression validation time is: {}", (System.currentTimeMillis() - millis)); } JEvalEvaluator(CommsRouterEvaluatorFactory factory, String predicate); @Override CommsRouterEvaluator changeExpression(String expression, String routerRef); @Override void validate(); @Override boolean evaluate(AttributeGroup attributesGroup); }### Answer: @Test public void testValidate() throws Exception { System.out.println("evaluate"); CommsRouterEvaluatorFactory ef = new CommsRouterEvaluatorFactory(); try { ef.provide("HAS(#{allowedBools}, true) && IN(true, #{allowedBools}) && #{~bool}", null).validate(); assertTrue(false); } catch (ExpressionException ex) { } try { ef.provide("#{boolTrue} && #{price}>10 && #{$price}^10", null).validate(); assertTrue(false); } catch (ExpressionException ex) { } try { ef.provide("#{color}$'red'", null).validate(); assertTrue(false); } catch (ExpressionException ex) { } try { ef.provide("true", null).validate(); } catch (ExpressionException ex) { assertTrue(false); } try { ef.provide(predicateOK3, null).validate(); } catch (ExpressionException ex) { assertTrue(false); } try { ef.provide("CONTAINS([10, 20, 30], 20)", null).validate(); } catch (ExpressionException ex) { assertTrue(false); } try { ef.provide("IN('fr', ['en','fr'])", null).validate(); } catch (ExpressionException ex) { assertTrue(false); } }
### Question: RsqlEvaluatorFactory { public boolean evaluate(String expression, AttributeGroup attributeGroup, String routerRef) throws ExpressionException { return create(expression, routerRef).evaluate(attributeGroup); } RsqlEvaluatorFactory(CommsRouterEvaluatorFactory factory); Node parse(String expression); void validate(String expression); RsqlEvaluator create(String expression, String routerRef); boolean evaluate(String expression, AttributeGroup attributeGroup, String routerRef); }### Answer: @Test(expected = ExpressionException.class) public void evaluateExpressionInvalidAttributesNumber() throws Exception { String predicate = "languages=gt=en"; rsqlEvaluatorFactory.evaluate(predicate, attributeGroupe, "routerRef"); }
### Question: RsqlEvaluatorFactory { public void validate(String expression) throws ExpressionException { try { parse(expression); } catch (RSQLParserException ex) { throw new ExpressionException("Invalid expression: " + ex.getMessage()); } } RsqlEvaluatorFactory(CommsRouterEvaluatorFactory factory); Node parse(String expression); void validate(String expression); RsqlEvaluator create(String expression, String routerRef); boolean evaluate(String expression, AttributeGroup attributeGroup, String routerRef); }### Answer: @Test public void validateExpressionValid() throws Exception { String predicateOK1 = "language==en;price=in=(20,30,40);price=gt=10;boolTrue==true"; String predicateOK2 = "language==bg,price<100;boolFalse==false"; String predicateOK3 = "language=in=(en,fr,es);prices==30,color==blue"; rsqlEvaluatorFactory.validate(predicateOK1); rsqlEvaluatorFactory.validate(predicateOK2); rsqlEvaluatorFactory.validate(predicateOK3); } @Test(expected = ExpressionException.class) public void validateExpressionInalid1() throws Exception { String predicateNOK1 = "language===en"; rsqlEvaluatorFactory.validate(predicateNOK1); } @Test(expected = ExpressionException.class) public void validateExpressionInalid2() throws Exception { String predicateNOK2 = "language==bg:boolFalse==true"; rsqlEvaluatorFactory.validate(predicateNOK2); } @Test(expected = ExpressionException.class) public void validateExpressionInalid3() throws Exception { String predicateNOK3 = "language==in=(bg,fr,es)"; rsqlEvaluatorFactory.validate(predicateNOK3); }
### Question: AttributeDomainMapper { public static AttributeType getAttributeType(AttributeDomainDefinition jpa) { if (jpa.getEnumValue() != null) { assert jpa.getBoundary() == null && jpa.getInclusive() == null && jpa.getRegex() == null; return AttributeType.enumeration; } if (jpa.getBoundary() != null) { assert jpa.getEnumValue() == null && jpa.getRegex() == null; return AttributeType.number; } if (jpa.getRegex() != null) { assert jpa.getEnumValue() == null && jpa.getBoundary() == null && jpa.getInclusive() == null; return AttributeType.string; } throw new RuntimeException("AttributeDomainDefinition with no value: " + jpa.getId()); } static AttributeType getAttributeType(AttributeDomainDefinition jpa); AttributeDomainDto toDto(AttributeDomain jpa); AttributeDomain fromDto(AttributeDomainDto dto); }### Answer: @Test public void testGetAttributeType() { AttributeType actual; AttributeDomainDefinition def; def = new AttributeDomainDefinition(); def.setEnumValue("enum-value"); actual = AttributeDomainMapper.getAttributeType(def); assertEquals(AttributeType.enumeration, actual); def = new AttributeDomainDefinition(); def.setBoundary(Double.POSITIVE_INFINITY); actual = AttributeDomainMapper.getAttributeType(def); assertEquals(AttributeType.number, actual); def = new AttributeDomainDefinition(); def.setRegex("regex-value"); actual = AttributeDomainMapper.getAttributeType(def); assertEquals(AttributeType.string, actual); }
### Question: RouterObject extends ApiObject { @Override public boolean equals(Object object) { boolean equals = super.equals(object); if (equals) { RouterObject routerObject = (RouterObject) object; return Objects.equals(getRouter(), routerObject.getRouter()); } return false; } RouterObject(); RouterObject(RouterObject rhs); RouterObject(String id); Router getRouter(); void setRouter(Router router); @Override String toString(); @Override boolean equals(Object object); @Override int hashCode(); }### Answer: @Test public void equalsTest() throws Exception { assertTrue("The same object", planP1R1.equals(planP1R1)); assertTrue("Diff object", planP1R1.equals(planP1R1new)); assertFalse("Should not equals", planP1R1.equals(planP1R2)); assertFalse("Diff class", planP1R1.equals(task)); assertFalse("Diff class", planP1R1.equals(new Rule())); }
### Question: RouterObject extends ApiObject { @Override public int hashCode() { return Objects.hash(getRef(), getRouter(), getVersion(), getClass()); } RouterObject(); RouterObject(RouterObject rhs); RouterObject(String id); Router getRouter(); void setRouter(Router router); @Override String toString(); @Override boolean equals(Object object); @Override int hashCode(); }### Answer: @Test public void hashCodeTest() throws Exception { assertEquals("The same object", planP1R1.hashCode(), planP1R1.hashCode()); assertEquals("Diff object", planP1R1.hashCode(), planP1R1new.hashCode()); assertNotEquals("Should not equals", planP1R1.hashCode(), planP1R2.hashCode()); assertNotEquals("Diff class", planP1R1.hashCode(), task.hashCode()); }
### Question: AdjustableSemaphore extends Semaphore { public synchronized void setMaxPermits(int maxPermits) { if (maxPermits < 1) { throw new IllegalArgumentException("Semaphore size(" + maxPermits + ") must be at least 1"); } int delta = maxPermits - this.maxPermits; if (delta == 0) { return; } else if (delta > 0) { super.release(delta); } else { delta *= -1; super.reducePermits(delta); } this.maxPermits = maxPermits; } AdjustableSemaphore(); AdjustableSemaphore(int permits); AdjustableSemaphore(int permits, boolean fair); synchronized void setMaxPermits(int maxPermits); }### Answer: @Test public void semaphoreTest() throws Exception { AdjustableSemaphore semaphore = new AdjustableSemaphore(5); for (int i = 0; i < 20; i++) { semaphore.tryAcquire(); } Assert.assertEquals(0, semaphore.availablePermits()); semaphore.setMaxPermits(2); Assert.assertEquals(-3, semaphore.availablePermits()); semaphore.setMaxPermits(20); Assert.assertEquals(15, semaphore.availablePermits()); semaphore.setMaxPermits(3); Assert.assertEquals(-2, semaphore.availablePermits()); semaphore.setMaxPermits(1); Assert.assertEquals(-4, semaphore.availablePermits()); semaphore.setMaxPermits(10); Assert.assertEquals(5, semaphore.availablePermits()); for (int i = 0; i < 7; i++) { semaphore.release(); } Assert.assertEquals(12, semaphore.availablePermits()); }
### Question: RetryerBuilder { public RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy) throws IllegalStateException { Preconditions.checkNotNull(waitStrategy, "waitStrategy may not be null"); Preconditions.checkState(this.waitStrategy == null, "a wait strategy has already been set %s", this.waitStrategy); this.waitStrategy = waitStrategy; return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer: @Test public void testWithWaitStrategy() throws ExecutionException, RetryException { Callable<Boolean> callable = notNullAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .withWaitStrategy(WaitStrategies.fixedWait(50L, TimeUnit.MILLISECONDS)) .retryIfResult(Predicates.<Boolean>isNull()) .build(); long start = System.currentTimeMillis(); boolean result = retryer.call(callable); assertTrue(System.currentTimeMillis() - start >= 250L); assertTrue(result); }
### Question: RetryerBuilder { public RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy) throws IllegalStateException { Preconditions.checkNotNull(stopStrategy, "stopStrategy may not be null"); Preconditions.checkState(this.stopStrategy == null, "a stop strategy has already been set %s", this.stopStrategy); this.stopStrategy = stopStrategy; return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer: @Test public void testWithStopStrategy() throws ExecutionException { Callable<Boolean> callable = notNullAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .retryIfResult(Predicates.<Boolean>isNull()) .build(); try { retryer.call(callable); fail("RetryException expected"); } catch (RetryException e) { assertEquals(3, e.getNumberOfFailedAttempts()); } }
### Question: RetryerBuilder { public RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy) throws IllegalStateException { Preconditions.checkNotNull(blockStrategy, "blockStrategy may not be null"); Preconditions.checkState(this.blockStrategy == null, "a block strategy has already been set %s", this.blockStrategy); this.blockStrategy = blockStrategy; return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer: @Test public void testWithBlockStrategy() throws ExecutionException, RetryException { Callable<Boolean> callable = notNullAfter5Attempts(); final AtomicInteger counter = new AtomicInteger(); BlockStrategy blockStrategy = new BlockStrategy() { @Override public void block(long sleepTime) throws InterruptedException { counter.incrementAndGet(); } }; Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .withBlockStrategy(blockStrategy) .retryIfResult(Predicates.<Boolean>isNull()) .build(); final int retryCount = 5; boolean result = retryer.call(callable); assertTrue(result); assertEquals(counter.get(), retryCount); }
### Question: RetryerBuilder { public RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate) { Preconditions.checkNotNull(resultPredicate, "resultPredicate may not be null"); rejectionPredicate = Predicates.or(rejectionPredicate, new ResultPredicate<V>(resultPredicate)); return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer: @Test public void testRetryIfResult() throws ExecutionException, RetryException { Callable<Boolean> callable = notNullAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfResult(Predicates.<Boolean>isNull()) .build(); assertTrue(retryer.call(callable)); callable = notNullAfter5Attempts(); retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfResult(Predicates.<Boolean>isNull()) .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); try { retryer.call(callable); fail("RetryException expected"); } catch (RetryException e) { assertEquals(3, e.getNumberOfFailedAttempts()); assertTrue(e.getLastFailedAttempt().hasResult()); assertNull(e.getLastFailedAttempt().getResult()); assertNull(e.getCause()); } }
### Question: AttemptTimeLimiters { public static <V> AttemptTimeLimiter<V> fixedTimeLimit(long duration, TimeUnit timeUnit) { Preconditions.checkNotNull(timeUnit); return new FixedAttemptTimeLimit<V>(duration, timeUnit); } private AttemptTimeLimiters(); static AttemptTimeLimiter<V> noTimeLimit(); static AttemptTimeLimiter<V> fixedTimeLimit(long duration, TimeUnit timeUnit); static AttemptTimeLimiter<V> fixedTimeLimit(long duration, TimeUnit timeUnit, ExecutorService executorService); }### Answer: @Test public void fixedTimeLimitTest() { try { AttemptTimeLimiters.fixedTimeLimit(3000, TimeUnit.MILLISECONDS).call(new Callable<Object>() { @Override public Object call() throws Exception { Thread.sleep(2000); return null; } }); } catch (Exception e) { e.printStackTrace(); } }
### Question: CircuitBreaker { public void open() { lastOpenedTime = System.currentTimeMillis(); state = CircuitBreakerState.OPEN; logger.debug("circuit open,key:{}", name); } CircuitBreaker(String name, CircuitBreakerConfig config); boolean isOpen(); boolean isHalfOpen(); boolean isClosed(); void open(); void openHalf(); void close(); boolean isOpen2HalfOpenTimeout(); boolean isCloseFailThresholdReached(); boolean isConsecutiveSuccessThresholdReached(); void incrFailCount(); AtomicInteger getConsecutiveSuccCount(); CircuitBreakerState getState(); }### Answer: @Test(expected = CircuitBreakerOpenException.class) public void testOpen() { for (int i = 0; i < 6; i++) { try { demoService.getUuid(2); } catch (Exception e) { } } demoService.getUuid(1); }
### Question: JavaVersion { static Version parseVersion(String version) { if (version.startsWith("1.")) { String[] versions = version.split("\\."); if (versions.length <= 1) { throw new IllegalStateException("Invalid Java version: " + version); } return new Version(1, Integer.parseInt(versions[1])); } else { final Matcher matcher = JDK9_AND_HIGHER.matcher(version); if (matcher.matches()) { int major = Integer.parseInt(matcher.group(1)); String minorGroup = matcher.group(3); int minor = minorGroup != null && !minorGroup.isEmpty() ? Integer.parseInt(minorGroup) : 0; return new Version(major, minor); } else { throw new IllegalStateException("Invalid Java version: " + version); } } } static final int getMajorVersion(); static final int getMinorVersion(); static boolean isJava8OrLater(); static final int MAJOR_VERSION; static final int MINOR_VERSION; }### Answer: @Test public void parseJavaVersion() { JavaVersion.Version parsedVersion = JavaVersion.parseVersion(version); assertEquals("Major version mismatch", expected.major, parsedVersion.major); assertEquals("Minor version mismatch", expected.minor, parsedVersion.minor); }
### Question: FileStringBinding extends AbstractStringBinding<File> implements Binding<File, String> { @Override public File unmarshal(String object) { return new File(object); } @Override File unmarshal(String object); Class<File> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals(new File("/tmp/Atomic"), BINDING.unmarshal("/tmp/Atomic")); }
### Question: StringBuilderStringBinding extends AbstractStringBinding<StringBuilder> implements Binding<StringBuilder, String> { @Override public StringBuilder unmarshal(String object) { return new StringBuilder(object); } @Override StringBuilder unmarshal(String object); Class<StringBuilder> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals(new StringBuilder("Hello World").toString(), BINDING.unmarshal("Hello World").toString()); }
### Question: StringBufferStringBinding extends AbstractStringBinding<StringBuffer> implements Binding<StringBuffer, String> { @Override public StringBuffer unmarshal(String object) { return new StringBuffer(object); } @Override StringBuffer unmarshal(String object); Class<StringBuffer> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals(new StringBuffer("Hello World").toString(), BINDING.unmarshal("Hello World").toString()); }
### Question: URIStringBinding extends AbstractStringBinding<URI> implements Binding<URI, String> { @Override public URI unmarshal(String object) { return URI.create(object); } @Override URI unmarshal(String object); Class<URI> getBoundClass(); }### Answer: @Test public void testUnmarshal(){ assertEquals(URI.create("www.example.com"), BINDING.unmarshal("www.example.com")); }
### Question: URLStringBinding extends AbstractStringBinding<URL> implements Binding<URL, String> { @Override public URL unmarshal(String object) { try { return new URL(object); } catch (MalformedURLException ex) { throw new IllegalArgumentException(object + " is not a valid URL"); } } @Override URL unmarshal(String object); Class<URL> getBoundClass(); }### Answer: @Test public void testUnmarshal() throws MalformedURLException{ assertEquals(new URL("http: }
### Question: BooleanStringBinding extends AbstractStringBinding<Boolean> implements Binding<Boolean, String> { @Override public Boolean unmarshal(String object) { return Boolean.valueOf(object); } @Override Boolean unmarshal(String object); Class<Boolean> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals(Boolean.TRUE.toString(), BINDING.unmarshal("true").toString()); assertEquals(Boolean.FALSE.toString(), BINDING.unmarshal("false").toString()); }
### Question: LocaleStringBinding extends AbstractStringBinding<Locale> implements Binding<Locale, String> { @Override public Locale unmarshal(String object) { String[] components = object.split("_", 3); final Locale result; if (components.length == 1) { result = new Locale(components[0]); } else if (components.length == 2) { result = new Locale(components[0], components[1]); } else if (components.length == 3) { result = new Locale(components[0], components[1], components[2]); } else { throw new IllegalArgumentException("Unable to unmarshall String to Locale: " + object); } return result; } @Override Locale unmarshal(String object); Class<Locale> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals(new Locale("en"), BINDING.unmarshal("en")); assertEquals(new Locale("en","GB"), BINDING.unmarshal("en_GB")); assertEquals(new Locale("en","GB","ck"), BINDING.unmarshal("en_gb_ck")); }
### Question: StringStringBinding extends AbstractStringBinding<String> implements Binding<String, String> { @Override public String unmarshal(String object) { return object; } @Override String unmarshal(String object); Class<String> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals("Hello World", BINDING.unmarshal("Hello World")); }
### Question: IntervalBisection implements CompositeFunction<Double, QuantitativeFunction<Double, Double>> { public IntervalBisection(double lowerBound, double higherBound) { this(lowerBound, higherBound, 20); } IntervalBisection(double lowerBound, double higherBound); IntervalBisection(double lowerBound, double higherBound, int iterations); IntervalBisection(double lowerBound, double higherBound, int iterations, double precision, PrecisionStrategy precisionStrategy); double getLowerBound(); double getHigherBound(); int getIterations(); double getPrecision(); @Override Double apply(QuantitativeFunction<Double, Double> computeFunction); }### Answer: @Test public void testIntervalBisection() { IntervalBisection bisection = new IntervalBisection(0D, 2D); Double result = bisection.apply(new QuantitativeFunction<Double, Double>() { @Override public Double apply(Double value) { return 2 - Math.pow(Math.E, value); } }); assertEquals(0.693359375D, result, 0.0000000001D); }
### Question: PackageStringBinding extends AbstractStringBinding<Package> implements Binding<Package, String> { @Override public Package unmarshal(String object) { return Package.getPackage(object); } @Override String marshal(Package object); @Override Package unmarshal(String object); Class<Package> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals(Package.getPackage("org.jadira.bindings.core.jdk"), BINDING.unmarshal("org.jadira.bindings.core.jdk")); }
### Question: PackageStringBinding extends AbstractStringBinding<Package> implements Binding<Package, String> { @Override public String marshal(Package object) { return ((Package) object).getName(); } @Override String marshal(Package object); @Override Package unmarshal(String object); Class<Package> getBoundClass(); }### Answer: @Test public void testMarshal() { assertEquals("org.jadira.bindings.core.jdk", BINDING.marshal(Package.getPackage("org.jadira.bindings.core.jdk"))); }
### Question: IntegerStringBinding extends AbstractStringBinding<Integer> implements Binding<Integer, String> { @Override public Integer unmarshal(String object) { return Integer.valueOf(Integer.parseInt(object)); } @Override Integer unmarshal(String object); Class<Integer> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals(new Integer(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new Integer(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new Integer(2147483647).toString(), BINDING.unmarshal("" + Integer.MAX_VALUE).toString()); assertEquals(new Integer(-2147483648).toString(), BINDING.unmarshal("" + Integer.MIN_VALUE).toString()); }
### Question: BigIntegerStringBinding extends AbstractStringBinding<BigInteger> implements Binding<BigInteger, String> { @Override public BigInteger unmarshal(String object) { return new BigInteger(object); } @Override BigInteger unmarshal(String object); Class<BigInteger> getBoundClass(); }### Answer: @Test public void testUnmarshal() { assertEquals(BigInteger.valueOf(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(BigInteger.valueOf(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(BigInteger.valueOf(9223372036854775807L).toString(), BINDING.unmarshal("" + Long.MAX_VALUE).toString()); assertEquals(BigInteger.valueOf(-9223372036854775808L).toString(), BINDING.unmarshal("" + Long.MIN_VALUE).toString()); assertEquals(new BigInteger("9223372036854775808").toString(), BINDING.unmarshal("9223372036854775808").toString()); assertEquals(new BigInteger("-9223372036854775809").toString(), BINDING.unmarshal("-9223372036854775809").toString()); }
### Question: UUIDStringBinding extends AbstractStringBinding<UUID> implements Binding<UUID, String> { @Override public UUID unmarshal(String object) { return java.util.UUID.fromString(object); } @Override UUID unmarshal(String object); Class<UUID> getBoundClass(); }### Answer: @Test public void testUnmarshal(){ assertEquals(RND, BINDING.unmarshal(RND.toString())); }