How to use toString method of org.mockito.internal.stubbing.answers.AnswersWithDelay class

Best Mockito code snippet using org.mockito.internal.stubbing.answers.AnswersWithDelay.toString

Source:Xtn5250TerminalEmulatorIT.java Github

copy

Full Screen

...363 private int getMenuShortcutKeyMask() {364 return Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();365 }366 private String getFileContent(String file) throws IOException {367 return Resources.toString(getClass().getResource(file), Charsets.UTF_8);368 }369 @Test370 public void shouldShowUserMessageWhenUnsupportedAttentionKey() {371 setScreen("");372 sendKeyWithCursorUpdate(KeyEvent.VK_ESCAPE, 0, 0, 0);373 findOptionPane().requireMessage("ATTN not supported for current protocol");374 }375 private JOptionPaneFixture findOptionPane() {376 return JOptionPaneFinder.findOptionPane().using(frame.robot());377 }378 @Test379 public void shouldShowUserMessageWhenInputByLabelWithNonSelectedArea() {380 setScreen("");381 clickButton(INPUT_BY_LABEL_BUTTON);382 findOptionPane().requireMessage("Please select a part of the screen");383 }384 @Test385 public void shouldSendInputByLabelThroughListenerWhenInputByLabel() {386 setScreen("");387 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);388 selectArea(0, 0, 5, 1);389 clickButton(INPUT_BY_LABEL_BUTTON);390 String test = "t";391 sendKeyWithCursorUpdate(KeyEvent.VK_T, 0, 2, 1);392 sendKeyWithCursorUpdate(KeyEvent.VK_ENTER, 0, 2, 5);393 List<Input> inputs = new ArrayList<>();394 inputs.add(new LabelInput(CHUNK_OF_SCREEN, test));395 inputs.add(buildCoordInput(2, 5));396 verify(listener).onAttentionKey(AttentionKey.ENTER, inputs, "");397 }398 @Test399 public void shouldNotifyListenerOfMultipleInputByLabel() {400 setScreenWithUserNameAndPasswordFields();401 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);402 selectArea(0, 0, 11, 1);403 clickButton(INPUT_BY_LABEL_BUTTON);404 sendKeyWithCursorUpdate(KeyEvent.VK_T, 0, 1, 14);405 selectArea(0, 1, 15, 1);406 clickButton(INPUT_BY_LABEL_BUTTON);407 sendKeyWithCursorUpdate(KeyEvent.VK_Y, 0, 2, 18);408 sendKeyWithCursorUpdate(KeyEvent.VK_ENTER, 0, 2, 19);409 verify(listener)410 .onAttentionKey(AttentionKey.ENTER, buildExpectedInputListForMultipleInputsByLabel(), "");411 }412 private List<Input> buildExpectedInputListForMultipleInputsByLabel() {413 LabelInput userName = new LabelInput("Insert Name", "t");414 LabelInput password = new LabelInput("Insert Password", "y");415 return Arrays.asList(userName, password);416 }417 private void setScreenWithUserNameAndPasswordFields() {418 xtn5250TerminalEmulator.setScreen(buildLoginScreenWithUserNameAndPasswordFields());419 xtn5250TerminalEmulator.setScreenSize(COLUMNS, ROWS);420 frame = new FrameFixture(xtn5250TerminalEmulator);421 frame.show();422 }423 @Test424 public void shouldShowUserMessageWhenInputByLabelAndNoFieldAfterCurrentLabel() {425 setScreenWithUserNameAndPasswordFields();426 selectArea(0, 2, 28, 1);427 clickButton(INPUT_BY_LABEL_BUTTON);428 findOptionPane().requireMessage("No input fields found near to \"" + GOODBYE_TEXT + "\".");429 }430 @Test431 public void shouldShowUserMessageWhenInputByLabelAndBlankSelectedArea() {432 setScreenWithUserNameAndPasswordFields();433 selectArea(19, 3, 15, 1);434 clickButton(INPUT_BY_LABEL_BUTTON);435 findOptionPane().requireMessage("Please select a non empty or blank text \n"436 + "to be used as input by label");437 }438 @Test439 public void shouldShowUserMessageWhenInputByLabelAndMultipleRowsWereSelected() {440 setScreenWithUserNameAndPasswordFields();441 selectArea(19, 3, 15, 2);442 clickButton(INPUT_BY_LABEL_BUTTON);443 findOptionPane().requireMessage("Please try again selecting one row");444 }445 @Test446 public void shouldCallTheListenerWhenPressWaitForTextButton() {447 setScreen("");448 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);449 selectArea(1, 0, 5, 4);450 clickButton(WAIT_FOR_TEXT_BUTTON);451 verify(listener, timeout(PAUSE_TIMEOUT))452 .onWaitForText(CHUNK_OF_SCREEN + "\n " + " \n" + "EXTO \n" + "EXTO ");453 }454 @Test455 public void shouldCallTheListenerWhenAssertionScreen() {456 setScreen("TEST");457 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);458 selectArea(0, 1, 4, 1);459 clickButton(ASSERTION_BUTTON);460 JOptionPaneFixture popup = findOptionPane();461 popup.textBox().setText(ASSERTION_TEST_LITERAL);462 popup.okButton().click();463 verify(listener, timeout(PAUSE_TIMEOUT)).onAssertionScreen(ASSERTION_TEST_LITERAL, "TEST");464 }465 @Test466 public void shouldShowUserMessageWhenAssertionButtonWhitNonSelectedArea() {467 setScreen("");468 clickButton(ASSERTION_BUTTON);469 findOptionPane().requireMessage("Please select a part of the screen");470 }471 @Test472 public void shouldNotNotifyListenerWhenAssertionScreenAndCancelButtonPressed() {473 setScreen("");474 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);475 selectArea(0, 1, 4, 1);476 clickButton(ASSERTION_BUTTON);477 findOptionPane().textBox().setText(ASSERTION_TEST_LITERAL);478 findOptionPane().cancelButton().click();479 verify(listener, never()).onAssertionScreen(ASSERTION_TEST_LITERAL, "TEST");480 }481 @Test482 public void shouldNotifyListenerWhenInputInhibitedOnSampleName() {483 xtn5250TerminalEmulator.setKeyboardLock(true);484 setScreen("");485 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);486 xtn5250TerminalEmulator.setKeyboardLock(false);487 setSampleName(CONNECTING_LITERAL);488 sendKeyWithCursorUpdate(KeyEvent.VK_ENTER, 0, 2, 1);489 verify(listener).onAttentionKey(AttentionKey.ENTER,490 Collections.singletonList(buildCoordInput(2, 1)),491 CONNECTING_LITERAL);492 }493 private void setSampleName(String name) {494 JTextComponentFixture field = frame.textBox(SAMPLE_NAME_FIELD);495 // target needed in order to effectively iterations with `listener` mock.496 field.target().setText(name);497 }498 @Test499 public void shouldSetDefaultValueInFieldWhenOnAttentionKey() {500 xtn5250TerminalEmulator.setKeyboardLock(true);501 setScreen("", DEFAULT_SAMPLE_NAME_INPUT_VALUE);502 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);503 xtn5250TerminalEmulator.setKeyboardLock(false);504 sendKeyWithCursorUpdate(KeyEvent.VK_ENTER, 0, 2, 1);505 assertThat(frame.textBox(SAMPLE_NAME_FIELD).text()).isEqualTo(DEFAULT_SAMPLE_NAME_INPUT_VALUE);506 }507 @Test508 public void shouldSwitchCredentialVisibilityIconWhenClickIcon() {509 setScreen("");510 frame.label("showCredentials").click();511 Icon actual = frame.label("showCredentials").target().getIcon();512 ImageIcon expected = new ImageIcon("/light-theme/visible-credentials.png");513 assertThat(((ImageIcon) actual).getImage().equals(expected.getImage()));514 }515 @Test516 public void shouldSendTabInputWithoutRepetitionWhenCursorJumpsToNextField() throws Exception {517 setScreenWithUserNameAndPasswordFields();518 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);519 sendNavigationKey(KeyEvent.VK_TAB, 0);520 sendNavigationKey(KeyEvent.VK_T, 0);521 sendNavigationKey(KeyEvent.VK_T, 0);522 sendNavigationKey(KeyEvent.VK_ENTER, 0);523 verify(listener).onAttentionKey(AttentionKey.ENTER,524 Arrays.asList(new NavigationInput(0, NavigationType.TAB, "T"), new NavigationInput(0,525 NavigationType.TAB, "T"), buildCoordInput(1, 14)), "");526 }527 @Test528 public void shouldProperBuildInputsWithTabsWhenSendCredentialsUsingVT() {529 updateCharacterBasedWelcomeScreen();530 setupInteractiveCharacterEmulator();531 updateCharacterBasedWelcomeScreen("T ");532 setCurrentCursorPositionAndScreen(FIRST_VT_POS);533 when(characterBasedProtocolClient.getCursorPosition())534 .thenReturn(Optional.of(SECOND_VT_POS));535 sendKeyInCurrentPosition(KeyEvent.VK_T, 11, 42);536 updateCharacterBasedWelcomeScreen(DEVELOPER_ID);537 setCurrentCursorPositionAndScreen(new Position(11, 43));538 sendKeyInCurrentPosition(KeyEvent.VK_T, 11, 43);539 setCurrentCursorPositionAndScreen(new Position(13, 41));540 sendKeyInCurrentPosition(KeyEvent.VK_TAB, 13, 41);541 updateCharacterBasedWelcomeScreen(DEVELOPER_ID, "0 ");542 setCurrentCursorPositionAndScreen(new Position(13, 42));543 sendKeyInCurrentPosition(KeyEvent.VK_0, 13, 42);544 updateCharacterBasedWelcomeScreen(DEVELOPER_ID, WORKDATE_LITERAL_VALUE);545 setCurrentCursorPositionAndScreen(new Position(13, 43));546 sendKeyInCurrentPosition(KeyEvent.VK_0, 13, 43);547 assertThat(xtn5250TerminalEmulator.getInputs())548 .isEqualTo(buildExpectedTabulatorInput());549 }550 private List<Input> buildExpectedTabulatorInput() {551 return Arrays552 .asList(new NavigationInput(0, NavigationType.TAB, "tt"), new NavigationInput(1,553 NavigationType.TAB, WORKDATE_LITERAL_VALUE));554 }555 public void setCurrentCursorPositionAndScreen(Position cursor) {556 when(characterBasedProtocolClient.getScreen()).thenReturn(screen);557 when(characterBasedProtocolClient.getCursorPosition())558 .thenReturn(Optional.of(cursor));559 }560 private void updateCursorPos(int i, int i2) {561 GuiActionRunner.execute(() -> xtn5250TerminalEmulator.setCursor(i, i2));562 }563 private void sendKeyInCurrentPosition(int key, int r, int c) {564 Component focusedComponent = frame.robot().finder().find(Component::isFocusOwner);565 JComponentDriver driver = new JComponentDriver(frame.robot());566 driver.pressAndReleaseKey(focusedComponent, KeyPressInfo.keyCode(key).modifiers(0));567 GuiActionRunner.execute(() -> {568 xtn5250TerminalEmulator.setCursor(r, c);569 xtn5250TerminalEmulator.setScreen(screen);570 });571 characterBasedEmulator.screenChanged(screen.getText());572 }573 private void setupInteractiveCharacterEmulator() {574 setupCharacterEmulator(true);575 }576 private void setupCharacterEmulator(boolean interactive) {577 characterBasedEmulator = new CharacterBasedEmulator();578 xtn5250TerminalEmulator = new Xtn5250TerminalEmulator(characterBasedEmulator);579 xtn5250TerminalEmulator.setSupportedAttentionKeys(buildSupportedAttentionKeys());580 xtn5250TerminalEmulator.setProtocolClient(characterBasedProtocolClient);581 xtn5250TerminalEmulator.addTerminalEmulatorListener(listener);582 GuiActionRunner.execute(() -> {583 xtn5250TerminalEmulator.setScreenSize(COLUMNS, ROWS);584 xtn5250TerminalEmulator.setScreen(screen);585 });586 characterBasedEmulator.setKeyboardStatus(true);587 characterBasedEmulator.screenChanged(screen.getText());588 if (interactive) {589 setScreenChangeEventWhenSendingInputs();590 }591 frame = new FrameFixture(xtn5250TerminalEmulator);592 frame.show();593 }594 private void setScreenChangeEventWhenSendingInputs() {595 doAnswer(invocation -> {596 characterBasedEmulator.screenChanged(screen.getText());597 return null;598 }).when(characterBasedProtocolClient).send(anyString());599 }600 private void updateCharacterBasedWelcomeScreen(String... inputs) {601 updateCharacterBasedScreen(getWelcomeScreenText(inputs));602 }603 private void updateCharacterBasedScreen(List<String> screenText) {604 screen = new Screen(new Dimension(80, 24));605 AtomicInteger linearPosition = new AtomicInteger();606 screenText.forEach(l -> screen.addSegment(linearPosition.getAndAdd(80), l));607 }608 private List<String> getWelcomeScreenText(String... strings) {609 return Arrays.asList(610 " **W E L C O M E ** ",611 " ",612 " WARNING ",613 " ",614 " THIS MATERIAL IT IS JUST FOR TESTING PROPOUSES ",615 " ",616 " ",617 " ",618 " TESTER ID: 001 ",619 " ",620 " DEVELOPER ID:" + (strings.length > 0 ? strings[0] : " ")621 + " ",622 " ",623 " WORKDATE:" + (strings.length > 1 ? strings[1] : " ")624 + " ",625 " ",626 " PASSWORD: ",627 " ",628 " ",629 " ",630 " ",631 " ",632 " ENTER CANCEL ",633 " ",634 " ",635 " ");636 }637 @Test638 public void shouldNotCreateInputsWithInvalidCharacterWhenTypingInVT() {639 updateCharacterBasedWelcomeScreen();640 setupInteractiveCharacterEmulator();641 setCurrentCursorPositionAndScreen(SECOND_VT_POS);642 sendKeyInCurrentPosition(KeyEvent.VK_T, 11, 42);643 assertThat(xtn5250TerminalEmulator.getInputs().isEmpty());644 }645 @Test646 public void shouldLockAndUnlockKeyboardWhenSendInputAndScreenChanges() {647 updateCharacterBasedWelcomeScreen();648 setupInteractiveCharacterEmulator();649 updateCharacterBasedWelcomeScreen("T ");650 setCurrentCursorPositionAndScreen(FIRST_VT_POS);651 startSingleEventGenerator(buildScreenChangeListener());652 sendKeyWithCursorUpdate(KeyEvent.VK_T, 0, 11, 42);653 xtn5250TerminalEmulator.setScreen(screen);654 awaitKeyboardToBeUnlocked();655 }656 private Runnable buildScreenChangeListener() {657 return () -> characterBasedEmulator.screenChanged("");658 }659 private void startSingleEventGenerator(Runnable eventGenerator) {660 ScheduledExecutorService eventGeneratorExecutor = Executors.newSingleThreadScheduledExecutor();661 eventGeneratorExecutor.schedule(eventGenerator, (long) 500, TimeUnit.MILLISECONDS);662 }663 private void awaitKeyboardToBeUnlocked() {664 pause(new Condition("Keyboard to be unlocked") {665 @Override666 public boolean test() {667 return frame.label(KEYBOARD_LABEL).target().getIcon().equals(ThemedIcon668 .fromResourceName(KEYBOARD_UNLOCKED_RESOURCE_NAME));669 }670 }, PAUSE_TIMEOUT);671 }672 @Test673 public void shouldShowBlockedMouseIconWhenUsingVT() {674 updateCharacterBasedWelcomeScreen();675 setupInteractiveCharacterEmulator();676 Icon actual = frame.label(BLOCK_CURSOR_LABEL).target().getIcon();677 assertThat(actual.equals(ThemedIcon678 .fromResourceName(BLOCKED_CURSOR_RESOURCE_NAME)));679 }680 @Test681 public void shouldBlockedCursorStartBlinkingWhenClickingScreen() {682 updateCharacterBasedWelcomeScreen();683 setupInteractiveCharacterEmulator();684 frame.robot().click(xtn5250TerminalEmulator);685 awaitBlockedCursorToBlink();686 }687 private void awaitBlockedCursorToBlink() {688 pause(new Condition("Blocked cursor icon has blinked.") {689 @Override690 public boolean test() {691 return frame.label(BLOCK_CURSOR_LABEL).target().getIcon().equals(StatusPanelIT.CURSOR_ICON);692 }693 }, PAUSE_TIMEOUT);694 }695 @Test(expected = ComponentLookupException.class)696 public void shouldNotAppearBlockedCursorWhenUsingFiledBasedEmulator() {697 setScreen("");698 //will not find this component therefore, ComponentLookupException is thrown.699 frame.label(BLOCK_CURSOR_LABEL).isEnabled();700 }701 @Test702 public void shouldNotSendAnyCharacterWhenKeyboardLock() {703 updateCharacterBasedWelcomeScreen();704 setupInteractiveCharacterEmulator();705 xtn5250TerminalEmulator.setKeyboardLock(true);706 sendKeyWithCursorUpdate(KeyEvent.VK_Y, 0, 11, 42);707 verify(characterBasedProtocolClient, never()).send(anyString());708 }709 @Test710 public void shouldSendAttentionKeyWhenKeyboardLock() {711 updateCharacterBasedWelcomeScreen();712 setupInteractiveCharacterEmulator();713 xtn5250TerminalEmulator.setKeyboardLock(true);714 sendKeyWithCursorUpdate(KeyEvent.VK_F1, 0, 11, 42);715 verify(listener).onAttentionKey(any(AttentionKey.class), anyList(),716 anyString());717 }718 @Test719 public void shouldBuildExpectedInputsWhenUsingPaste() {720 updateCharacterBasedWelcomeScreen();721 setupInteractiveCharacterEmulator();722 setCursorPositionMock(11, 41);723 updateCharacterBasedWelcomeScreen("T ");724 addTextToClipboard(DEVELOPER_ID.toLowerCase());725 clickButton(PASTE_BUTTON);726 awaitForPasteAvailability();727 updateCharacterBasedWelcomeScreen(DEVELOPER_ID);728 xtn5250TerminalEmulator.setScreen(screen);729 setCursorPositionMock(12, 41);730 updateCharacterBasedWelcomeScreen("0 ");731 addTextToClipboard(WORKDATE_LITERAL_VALUE);732 clickButton(PASTE_BUTTON);733 awaitForPasteAvailability();734 updateCharacterBasedWelcomeScreen(DEVELOPER_ID, WORKDATE_LITERAL_VALUE);735 xtn5250TerminalEmulator.setScreen(screen);736 assertThat(xtn5250TerminalEmulator.getInputs())737 .isEqualTo(buildExpectedTabulatorInputsForCharacterBased());738 }739 private void setCursorPositionMock(int row, int column) {740 when(characterBasedProtocolClient.getCursorPosition()).thenReturn(Optional.of(new Position(row,741 column))).thenReturn(Optional.of(new Position(row,742 column + 1))).thenReturn(Optional.of(new Position(row,743 column + 1))).thenReturn(Optional.of(new Position(row,744 column + 2)));745 }746 private void awaitForPasteAvailability() {747 pause(new Condition(" waiting for paste button to be unlocked") {748 @Override749 public boolean test() {750 return frame.button(PASTE_BUTTON).isEnabled();751 }752 }, PAUSE_TIMEOUT);753 }754 private List<Input> buildExpectedTabulatorInputsForCharacterBased() {755 return Arrays.asList(new NavigationInput(0, NavigationType.TAB, DEVELOPER_ID.toLowerCase()),756 new NavigationInput(0, NavigationType.TAB, WORKDATE_LITERAL_VALUE));757 }758 @Test759 public void shouldCloseWindowWhenWaitingForServerAnswer() {760 updateCharacterBasedWelcomeScreen();761 setupManualCharacterEmulator();762 setLockWhenInputSent();763 AtomicBoolean isClosed = new AtomicBoolean();764 setupWindowListener(isClosed);765 sendKeyWithCursorUpdate(KeyEvent.VK_0, 0, 1, 1);766 sendKeyWithCursorUpdate(KeyEvent.VK_F, 0, 1, 1);767 verify(characterBasedProtocolClient, times(1)).send(anyString());768 frame.close();769 assertThat(isClosed);770 }771 private void setupWindowListener(AtomicBoolean isClosed) {772 frame.target().addWindowListener(new WindowAdapter() {773 @Override774 public void windowClosed(WindowEvent e) {775 isClosed.set(true);776 super.windowClosed(e);777 }778 });779 }780 private void setLockWhenInputSent() {781 doAnswer(new AnswersWithDelay(PAUSE_TIMEOUT, null))782 .when(characterBasedProtocolClient).send(anyString());783 }784 private void setupManualCharacterEmulator() {785 setupCharacterEmulator(false);786 }787 @Test788 public void shouldNotSetVisibleInputByLabelButtonWhenUsingCharacterBasedEmulator() {789 updateCharacterBasedWelcomeScreen();790 setupManualCharacterEmulator();791 assertThat(Arrays.stream(frame.target().getComponents())792 .filter(c -> c instanceof JButton)793 .anyMatch(c -> c.getName().equals("labelButton")));794 }795 @Test796 public void shouldBuildDownNavigationInputWhenSendingDownArrow() {797 updateArrowNavigationScreen();798 setupInteractiveCharacterEmulator();799 xtn5250TerminalEmulator.setCursor(1, 54);800 when(characterBasedProtocolClient.getCursorPosition())801 .thenReturn(Optional.of(new Position(1, 54)))802 .thenReturn(Optional.of(new Position(2, 47)))803 .thenReturn(Optional.of(new Position(2, 48)));804 updateArrowNavigationScreen(ArrowInput.ZERO);805 sendKeyInCurrentPosition(KeyEvent.VK_DOWN, 2, 47);806 sendKeyInCurrentPosition(KeyEvent.VK_0, 2, 26);807 assertThat(xtn5250TerminalEmulator.getInputs()).isEqualTo(ArrowInput.ZERO.inputs);808 }809 private void updateArrowNavigationScreen(ArrowInput... values) {810 String[] texts =811 Arrays.stream(values)812 .map(ArrowInput::toString)813 .collect(Collectors.toList())814 .toArray(new String[values.length]);815 updateCharacterBasedScreen(buildArrowScreenText(texts));816 }817 private List<String> buildArrowScreenText(String... text) {818 return Arrays.asList(819 " USER NAME: " + getIndex(text, 2) +820 " PERMISSIONS REQUIRED: " + getIndex(text, 3) + " ",821 " USER TYPE: " + getIndex(text, 1)822 + " INTERNAL CODE: " + getIndex(text, 0) + " ",823 " ",824 " ",825 " ",826 " ",827 " ",828 " ",829 " ",830 " ",831 " ",832 " ",833 " ",834 " ",835 " ",836 " ",837 " ",838 " ",839 " ",840 " ",841 " ",842 " ",843 " ",844 " ");845 }846 private String getIndex(String[] strings, int i) {847 return strings.length > i ? strings[i] : " ";848 }849 @Test850 public void shouldBuildLeftNavigationInputWhenSendingLeftArrow() {851 updateArrowNavigationScreen(ArrowInput.ZERO);852 setupInteractiveCharacterEmulator();853 xtn5250TerminalEmulator.setCursor(2, 48);854 when(characterBasedProtocolClient.getCursorPosition())855 .thenReturn(Optional.of(new Position(2, 48)))856 .thenReturn(Optional.of(new Position(2, 46)))857 .thenReturn(Optional.of(new Position(2, 46)))858 .thenReturn(Optional.of(new Position(2, 26)))859 .thenReturn(Optional.of(new Position(2, 26)))860 .thenReturn(Optional.of(new Position(2, 27)));861 sendKeyInCurrentPosition(KeyEvent.VK_LEFT, 2, 46);862 sendKeyInCurrentPosition(KeyEvent.VK_LEFT, 2, 26);863 sendKeyInCurrentPosition(KeyEvent.VK_1, 2, 27);864 updateArrowNavigationScreen(ArrowInput.ZERO, ArrowInput.ONE);865 assertThat(xtn5250TerminalEmulator.getInputs()).isEqualTo(ArrowInput.ONE.inputs);866 }867 @Test868 public void shouldBuildUpAndLeftNavigationInputWhenSendingUpAndLeftArrow() {869 updateArrowNavigationScreen(ArrowInput.ZERO, ArrowInput.ONE);870 setupInteractiveCharacterEmulator();871 xtn5250TerminalEmulator.setCursor(2, 27);872 when(characterBasedProtocolClient.getCursorPosition())873 .thenReturn(Optional.of(new Position(2, 27)))874 .thenReturn(Optional.of(new Position(1, 27)))875 .thenReturn(Optional.of(new Position(1, 27)))876 .thenReturn(Optional.of(new Position(1, 26)))877 .thenReturn(Optional.of(new Position(1, 26)))878 .thenReturn(Optional.of(new Position(1, 27)));879 sendKeyInCurrentPosition(KeyEvent.VK_UP, 1, 27);880 sendKeyInCurrentPosition(KeyEvent.VK_LEFT, 1, 26);881 updateArrowNavigationScreen(ArrowInput.ZERO, ArrowInput.ONE, ArrowInput.TWO);882 sendKeyInCurrentPosition(KeyEvent.VK_2, 1, 27);883 assertThat(xtn5250TerminalEmulator.getInputs()).isEqualTo(ArrowInput.TWO.inputs);884 }885 @Test886 public void shouldBuildRightNavigationInputWhenSendingRightArrow() {887 updateArrowNavigationScreen(ArrowInput.ZERO, ArrowInput.ONE, ArrowInput.TWO);888 setupInteractiveCharacterEmulator();889 xtn5250TerminalEmulator.setCursor(1, 27);890 when(characterBasedProtocolClient.getCursorPosition())891 .thenReturn(Optional.of(new Position(1, 27)))892 .thenReturn(Optional.of(new Position(1, 54)))893 .thenReturn(Optional.of(new Position(1, 54)))894 .thenReturn(Optional.of(new Position(1, 55)));895 sendKeyInCurrentPosition(KeyEvent.VK_RIGHT, 1, 54);896 updateArrowNavigationScreen(ArrowInput.ZERO, ArrowInput.ONE, ArrowInput.TWO, ArrowInput.THREE);897 sendKeyInCurrentPosition(KeyEvent.VK_3, 1, 55);898 assertThat(xtn5250TerminalEmulator.getInputs()).isEqualTo(ArrowInput.THREE.inputs);899 }900 @Test901 public void shouldProperBuildMixedInputsWhenFirstPositionIsMiddleField() throws Exception {902 setScreenWithUserNameAndPasswordFields();903 xtn5250TerminalEmulator.setCursor(2, 18);904 sendNavigationKey(KeyEvent.VK_TAB, 0);905 sendKeyWithCursorUpdate(KeyEvent.VK_T, 0, 1, 14);906 selectArea(0, 0, 11, 1);907 clickButton(INPUT_BY_LABEL_BUTTON);908 sendKeyWithCursorUpdate(KeyEvent.VK_Y, 0, 2, 18);909 assertThat(xtn5250TerminalEmulator.getInputs()).isEqualTo(Arrays.asList(new NavigationInput(0910 , NavigationType.TAB, "y"), new LabelInput("Insert Name", "t"),911 buildCoordInput(1, 14)));912 }913 private void sendNavigationKey(int key, int modifiers) {914 Component focusedComponent = frame.robot().finder().find(Component::isFocusOwner);915 JComponentDriver driver = new JComponentDriver(frame.robot());916 driver.pressAndReleaseKey(focusedComponent, KeyPressInfo.keyCode(key).modifiers(modifiers));917 }918 public enum ArrowInput {919 ZERO("0", Collections.singletonList(new NavigationInput(1, NavigationType.DOWN, "0"))),920 ONE("1", Collections.singletonList(new NavigationInput(2, NavigationType.LEFT, "1"))),921 TWO("2", Arrays.asList(new NavigationInput(1, NavigationType.UP, ""),922 new NavigationInput(1, NavigationType.LEFT, "2"))),923 THREE("3", Collections.singletonList(new NavigationInput(1, NavigationType.RIGHT, "3")));924 public String value;925 public List<NavigationInput> inputs;926 ArrowInput(String value, List<NavigationInput> inputs) {927 this.value = value;928 this.inputs = inputs;929 }930 @Override931 public String toString() {932 return value;933 }934 }935 @Test936 public void shouldRecoverFocusOnScreenWhenClickingBackFromSampleNameField() throws Exception {937 updateCharacterBasedWelcomeScreen();938 setupInteractiveCharacterEmulator();939 frame.textBox(SAMPLE_NAME_FIELD).click();940 frame.robot().click(characterBasedEmulator);941 assertTrue(characterBasedEmulator.isFocusOwner());942 }943 @Test944 public void shouldKeepSampleNameWhenSendingInputs() throws Exception {945 updateCharacterBasedWelcomeScreen();...

Full Screen

Full Screen

Source:EventProcessorTest.java Github

copy

Full Screen

...270 eventProcessor.handleEvent(event);271 return event.getRelatedCustomResourceID();272 }273 private ResourceEvent prepareCREvent() {274 return prepareCREvent(new ResourceID(UUID.randomUUID().toString(), TEST_NAMESPACE));275 }276 private ResourceEvent prepareCREvent(HasMetadata hasMetadata) {277 when(controllerResourceEventSourceMock.get(eq(ResourceID.fromResource(hasMetadata))))278 .thenReturn(Optional.of(hasMetadata));279 return new ResourceEvent(ResourceAction.UPDATED,280 ResourceID.fromResource(hasMetadata), hasMetadata);281 }282 private ResourceEvent prepareCREvent(ResourceID resourceID) {283 TestCustomResource customResource = testCustomResource(resourceID);284 when(controllerResourceEventSourceMock.get(eq(resourceID)))285 .thenReturn(Optional.of(customResource));286 return new ResourceEvent(ResourceAction.UPDATED,287 ResourceID.fromResource(customResource), customResource);288 }...

Full Screen

Full Screen

Source:TestTimelineCollector.java Github

copy

Full Screen

...249 TimelineCollector collector = new TimelineCollector("") {250 @Override251 public TimelineCollectorContext getTimelineEntityContext() {252 return new TimelineCollectorContext("cluster", "user", "flow", "1",253 1L, ApplicationId.newInstance(ts, 1).toString());254 }255 };256 collector.init(new Configuration());257 collector.setWriter(mock(TimelineWriter.class));258 // Put 5 entities with different metric values.259 TimelineEntities entities = new TimelineEntities();260 for (int i = 1; i <=5; i++) {261 TimelineEntity entity = createEntity("e" + i, "type");262 entity.addMetric(createDummyMetric(ts + i, Long.valueOf(i * 50)));263 entities.addEntity(entity);264 }265 collector.putEntities(entities, UserGroupInformation.getCurrentUser());266 TimelineCollectorContext currContext = collector.getTimelineEntityContext();267 // Aggregate the entities.268 Map<String, AggregationStatusTable> aggregationGroups269 = collector.getAggregationGroups();270 assertEquals(Sets.newHashSet("type"), aggregationGroups.keySet());271 TimelineEntity aggregatedEntity = TimelineCollector.272 aggregateWithoutGroupId(aggregationGroups, currContext.getAppId(),273 TimelineEntityType.YARN_APPLICATION.toString());274 TimelineMetric aggregatedMetric =275 aggregatedEntity.getMetrics().iterator().next();276 assertEquals(750L, aggregatedMetric.getValues().values().iterator().next());277 assertEquals(TimelineMetricOperation.SUM,278 aggregatedMetric.getRealtimeAggregationOp());279 // Aggregate entities.280 aggregatedEntity = TimelineCollector.281 aggregateWithoutGroupId(aggregationGroups, currContext.getAppId(),282 TimelineEntityType.YARN_APPLICATION.toString());283 aggregatedMetric = aggregatedEntity.getMetrics().iterator().next();284 // No values aggregated as no metrics put for an entity between this285 // aggregation and the previous one.286 assertTrue(aggregatedMetric.getValues().isEmpty());287 assertEquals(TimelineMetricOperation.NOP,288 aggregatedMetric.getRealtimeAggregationOp());289 // Put 3 entities.290 entities = new TimelineEntities();291 for (int i = 1; i <=3; i++) {292 TimelineEntity entity = createEntity("e" + i, "type");293 entity.addMetric(createDummyMetric(System.currentTimeMillis() + i, 50L));294 entities.addEntity(entity);295 }296 aggregationGroups = collector.getAggregationGroups();297 collector.putEntities(entities, UserGroupInformation.getCurrentUser());298 // Aggregate entities.299 aggregatedEntity = TimelineCollector.300 aggregateWithoutGroupId(aggregationGroups, currContext.getAppId(),301 TimelineEntityType.YARN_APPLICATION.toString());302 // Last 3 entities picked up for aggregation.303 aggregatedMetric = aggregatedEntity.getMetrics().iterator().next();304 assertEquals(150L, aggregatedMetric.getValues().values().iterator().next());305 assertEquals(TimelineMetricOperation.SUM,306 aggregatedMetric.getRealtimeAggregationOp());307 collector.close();308 }309}...

Full Screen

Full Screen

Source:RepositoryMethodInvokerUnitTests.java Github

copy

Full Screen

1/*2 * Copyright 2020-2021 the original author or authors.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * https://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.springframework.data.repository.core.support;17import static org.assertj.core.api.Assertions.*;18import static org.mockito.Mockito.*;19import kotlin.coroutines.Continuation;20import kotlin.coroutines.CoroutineContext;21import kotlinx.coroutines.flow.Flow;22import kotlinx.coroutines.flow.FlowKt;23import kotlinx.coroutines.reactor.ReactorContext;24import lombok.AllArgsConstructor;25import lombok.NoArgsConstructor;26import lombok.ToString;27import reactor.core.publisher.Flux;28import reactor.core.publisher.Mono;29import reactor.test.StepVerifier;30import java.lang.reflect.Method;31import java.util.ArrayList;32import java.util.Iterator;33import java.util.List;34import java.util.Queue;35import java.util.Spliterator;36import java.util.concurrent.ArrayBlockingQueue;37import java.util.concurrent.TimeUnit;38import java.util.function.Consumer;39import java.util.stream.Stream;40import org.assertj.core.api.Assertions;41import org.assertj.core.data.Percentage;42import org.jetbrains.annotations.NotNull;43import org.junit.jupiter.api.BeforeEach;44import org.junit.jupiter.api.Test;45import org.junit.jupiter.api.extension.ExtendWith;46import org.mockito.Mock;47import org.mockito.internal.stubbing.answers.AnswersWithDelay;48import org.mockito.internal.stubbing.answers.Returns;49import org.mockito.junit.jupiter.MockitoExtension;50import org.reactivestreams.Subscription;51import org.springframework.data.repository.CrudRepository;52import org.springframework.data.repository.core.support.CoroutineRepositoryMetadataUnitTests.MyCoroutineRepository;53import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocation;54import org.springframework.data.repository.core.support.RepositoryMethodInvocationListener.RepositoryMethodInvocationResult.State;55import org.springframework.data.repository.query.RepositoryQuery;56import org.springframework.data.repository.reactive.ReactiveCrudRepository;57import org.springframework.lang.Nullable;58import org.springframework.util.CollectionUtils;59import org.springframework.util.ReflectionUtils;60/**61 * @author Christoph Strobl62 */63@ExtendWith(MockitoExtension.class)64class RepositoryMethodInvokerUnitTests {65 @Mock RepositoryQuery query;66 CapturingRepositoryInvocationMulticaster multicaster;67 @BeforeEach68 void beforeEach() {69 multicaster = new CapturingRepositoryInvocationMulticaster();70 }71 @Test // DATACMNS-176472 void usesRepositoryInterfaceNameForMethodsDefinedOnCrudRepository() throws Exception {73 when(query.execute(any())).thenReturn(new TestDummy());74 repositoryMethodInvoker("findAll").invoke();75 assertThat(multicaster.first().getMethod().getName()).isEqualTo("findAll");76 assertThat(multicaster.first().getRepositoryInterface()).isEqualTo(DummyRepository.class);77 }78 @Test // DATACMNS-176479 void usesRepositoryInterfaceNameForMethodsOnTheInterface() throws Exception {80 when(query.execute(any())).thenReturn(new TestDummy());81 repositoryMethodInvoker("findByName").invoke();82 assertThat(multicaster.first().getMethod().getName()).isEqualTo("findByName");83 assertThat(multicaster.first().getRepositoryInterface()).isEqualTo(DummyRepository.class);84 }85 @Test // DATACMNS-176486 void usesRepositoryInterfaceNameForMethodsDefinedOnReactiveCrudRepository() throws Exception {87 when(query.execute(any())).thenReturn(Flux.just(new TestDummy()));88 repositoryMethodInvokerForReactive("findAll").<Flux<TestDummy>> invoke().subscribe();89 assertThat(multicaster.first().getMethod().getName()).isEqualTo("findAll");90 assertThat(multicaster.first().getRepositoryInterface()).isEqualTo(ReactiveDummyRepository.class);91 }92 @Test // DATACMNS-176493 void capturesImperativeDurationCorrectly() throws Exception {94 when(query.execute(any())).thenAnswer(new AnswersWithDelay(250, new Returns(new TestDummy())));95 repositoryMethodInvoker("findAll").invoke();96 assertThat(multicaster.first().getDuration(TimeUnit.MILLISECONDS)).isCloseTo(250, Percentage.withPercentage(10));97 }98 @Test // DATACMNS-176499 void capturesReactiveDurationCorrectly() throws Exception {100 when(query.execute(any())).thenReturn(Flux.just(new TestDummy()).doOnSubscribe(delays(250)::delay));101 repositoryMethodInvokerForReactive("findAll").<Flux<TestDummy>> invoke().subscribe();102 assertThat(multicaster.first().getDuration(TimeUnit.MILLISECONDS)).isCloseTo(250, Percentage.withPercentage(10));103 }104 @Test // DATACMNS-1764105 void capturesReactiveExecutionOnSubscribe() throws Exception {106 when(query.execute(any())).thenReturn(Flux.just(new TestDummy()));107 Flux<TestDummy> findAll = repositoryMethodInvokerForReactive("findAll").invoke();108 assertThat(multicaster).isEmpty();109 findAll.subscribe();110 assertThat(multicaster).hasSize(1);111 }112 @Test // DATACMNS-1764113 void capturesReactiveDurationPerSubscriptionCorrectly() throws Exception {114 when(query.execute(any())).thenReturn(Flux.just(new TestDummy()).doOnSubscribe(delays(250, 100)::delay));115 Flux<TestDummy> findAll = repositoryMethodInvokerForReactive("findAll").invoke();116 findAll.subscribe();117 findAll.subscribe();118 assertThat(multicaster.first().getDuration(TimeUnit.MILLISECONDS)).isCloseTo(250, Percentage.withPercentage(10));119 assertThat(multicaster.last().getDuration(TimeUnit.MILLISECONDS)).isCloseTo(100, Percentage.withPercentage(10));120 }121 @Test // DATACMNS-1764122 void capturesStreamDurationOnClose() throws Exception {123 when(query.execute(any())).thenReturn(Stream.generate(TestDummy::new));124 Stream<TestDummy> stream = repositoryMethodInvoker("streamAll").invoke();125 assertThat(multicaster).isEmpty();126 stream.iterator().next();127 assertThat(multicaster).isEmpty();128 stream.close();129 assertThat(multicaster).hasSize(1);130 }131 @Test // DATACMNS-1764132 void capturesStreamDurationAsSumOfDelayTillCancel() throws Exception {133 Delays delays = delays(250, 100);134 when(query.execute(any())).thenReturn(Stream.generate(() -> {135 delays.delay();136 return new TestDummy();137 }));138 Stream<TestDummy> stream = repositoryMethodInvoker("streamAll").invoke();139 stream.limit(2).forEach(it -> {});140 stream.close();141 assertThat(multicaster.first().getDuration(TimeUnit.MILLISECONDS)).isCloseTo(350, Percentage.withPercentage(10));142 }143 @Test // DATACMNS-1764144 void capturesImperativeSuccessCorrectly() throws Exception {145 repositoryMethodInvoker("findAll").invoke();146 assertThat(multicaster.first().getResult().getState()).isEqualTo(State.SUCCESS);147 assertThat(multicaster.first().getResult().getError()).isNull();148 }149 @Test // DATACMNS-1764150 void capturesReactiveCompletionCorrectly() throws Exception {151 when(query.execute(any())).thenReturn(Mono.just(new TestDummy()));152 repositoryMethodInvokerForReactive("findByName").<Mono<TestDummy>> invoke().subscribe();153 assertThat(multicaster.first().getResult().getState()).isEqualTo(State.SUCCESS);154 assertThat(multicaster.first().getResult().getError()).isNull();155 }156 @Test // DATACMNS-1764157 void capturesImperativeErrorCorrectly() {158 when(query.execute(any())).thenThrow(new IllegalStateException("I'll be back!"));159 assertThatIllegalStateException().isThrownBy(() -> repositoryMethodInvoker("findAll").invoke());160 assertThat(multicaster.first().getResult().getState()).isEqualTo(State.ERROR);161 assertThat(multicaster.first().getResult().getError()).isInstanceOf(IllegalStateException.class);162 }163 @Test // DATACMNS-1764164 void capturesReactiveErrorCorrectly() throws Exception {165 when(query.execute(any())).thenReturn(Mono.fromSupplier(() -> {166 throw new IllegalStateException("I'll be back!");167 }));168 repositoryMethodInvokerForReactive("findByName").<Mono<TestDummy>> invoke().as(StepVerifier::create).verifyError();169 assertThat(multicaster.first().getResult().getState()).isEqualTo(State.ERROR);170 assertThat(multicaster.first().getResult().getError()).isInstanceOf(IllegalStateException.class);171 }172 @Test // DATACMNS-1764173 void capturesReactiveCancellationCorrectly() throws Exception {174 when(query.execute(any())).thenReturn(Flux.just(new TestDummy(), new TestDummy()));175 repositoryMethodInvokerForReactive("findAll").<Flux<TestDummy>> invoke().take(1).subscribe();176 assertThat(multicaster.first().getResult().getState()).isEqualTo(State.CANCELED);177 assertThat(multicaster.first().getResult().getError()).isNull();178 }179 @Test // DATACMNS-1764180 void capturesKotlinSuspendFunctionsCorrectly() throws Exception {181 Flux<TestDummy> result = Flux.just(new TestDummy());182 when(query.execute(any())).thenReturn(result);183 Flow<TestDummy> flow = new RepositoryMethodInvokerStub(MyCoroutineRepository.class, multicaster,184 "suspendedQueryMethod", query::execute).invoke(mock(Continuation.class));185 assertThat(multicaster).isEmpty();186 FlowKt.toCollection(flow, new ArrayList<>(), new Continuation<ArrayList<? extends Object>>() {187 ReactorContext ctx = new ReactorContext(reactor.util.context.Context.empty());188 @NotNull189 @Override190 public CoroutineContext getContext() {191 return ctx;192 }193 @Override194 public void resumeWith(@NotNull Object o) {195 }196 });197 assertThat(multicaster.first().getResult().getState()).isEqualTo(State.SUCCESS);198 assertThat(multicaster.first().getResult().getError()).isNull();199 }200 RepositoryMethodInvokerStub repositoryMethodInvoker(String methodName) {201 return new RepositoryMethodInvokerStub(DummyRepository.class, multicaster, methodName, query::execute);202 }203 RepositoryMethodInvokerStub repositoryMethodInvokerForReactive(String methodName) {204 return new RepositoryMethodInvokerStub(ReactiveDummyRepository.class, multicaster, methodName, query::execute);205 }206 static Delays delays(Integer... delays) {207 return new Delays(delays);208 }209 static class Delays {210 private final Queue<Integer> delays;211 Delays(Integer... delays) {212 this.delays = new ArrayBlockingQueue(delays.length);213 for (Integer delay : delays) {214 this.delays.add(delay);215 }216 }217 void delay() {218 delay(null);219 }220 void delay(Subscription it) {221 if (delays.isEmpty()) {222 return;223 }224 delayBy(delays.poll());225 }226 private static void delayBy(Integer ms) {227 if (ms == null) {228 return;229 }230 try {231 TimeUnit.MILLISECONDS.sleep(ms);232 } catch (InterruptedException e) {233 e.printStackTrace();234 }235 }236 }237 static class RepositoryMethodInvokerStub extends RepositoryMethodInvoker {238 private final Class<?> repositoryInterface;239 private final RepositoryInvocationMulticaster multicaster;240 RepositoryMethodInvokerStub(Class<?> repositoryInterface, RepositoryInvocationMulticaster multicaster,241 String methodName, Invokable invokable) {242 super(methodByName(repositoryInterface, methodName), invokable);243 this.repositoryInterface = repositoryInterface;244 this.multicaster = multicaster;245 }246 public <T> T invoke(Object... args) throws Exception {247 return (T) super.invoke(repositoryInterface, multicaster, args);248 }249 @Nullable250 public <T> T invoke(RepositoryInvocationMulticaster multicaster, Object... args) throws Exception {251 return (T) super.invoke(repositoryInterface, multicaster, args);252 }253 static Method methodByName(Class<?> repository, String name) {254 return ReflectionUtils.findMethod(repository, name, null);255 }256 }257 static class CapturingRepositoryInvocationMulticaster258 implements RepositoryInvocationMulticaster, Iterable<RepositoryMethodInvocation> {259 private final List<RepositoryMethodInvocation> invocations = new ArrayList<>();260 @Override261 public void notifyListeners(Method method, Object[] args, RepositoryMethodInvocation result) {262 invocations.add(result);263 }264 RepositoryMethodInvocation first() {265 Assertions.assertThat(invocations).isNotEmpty();266 return CollectionUtils.firstElement(invocations);267 }268 RepositoryMethodInvocation last() {269 Assertions.assertThat(invocations).isNotEmpty();270 return CollectionUtils.lastElement(invocations);271 }272 @NotNull273 @Override274 public Iterator<RepositoryMethodInvocation> iterator() {275 return invocations.iterator();276 }277 @Override278 public Spliterator<RepositoryMethodInvocation> spliterator() {279 return invocations.spliterator();280 }281 @Override282 public void forEach(Consumer<? super RepositoryMethodInvocation> action) {283 invocations.forEach(action);284 }285 }286 interface DummyRepository extends CrudRepository<TestDummy, String> {287 TestDummy findByName(String name);288 Stream<TestDummy> streamAll();289 }290 interface ReactiveDummyRepository extends ReactiveCrudRepository<TestDummy, String> {291 Mono<TestDummy> findByName(String name);292 }293 @ToString294 @AllArgsConstructor295 @NoArgsConstructor296 static class TestDummy {297 String id;298 String name;299 }300}...

Full Screen

Full Screen

Source:IdMappingJobServiceTest.java Github

copy

Full Screen

...222 Assertions.assertNotEquals(updated, job.getUpdated());223 Assertions.assertTrue((job.getUpdated().getTime() - updated.getTime()) > 0);224 }225 private IdMappingJobRequest createIdMappingRequest() {226 String random = UUID.randomUUID().toString();227 IdMappingJobRequest request = new IdMappingJobRequest();228 request.setFrom("from" + random);229 request.setTo("to" + random);230 request.setIds("ids" + random);231 return request;232 }233}...

Full Screen

Full Screen

Source:WidgetsServiceTest.java Github

copy

Full Screen

...108 WidgetEntity captured = saveWidgetCaptor.getValue();109 assertEquals(initialZ, captured.getZ());110 }111 private Future<Boolean> submitGetByIdTask() {112 String id = UUID.randomUUID().toString();113 return executor.submit(() -> widgetsService.findById(id).isEmpty());114 }115 private Future<Boolean> submitGetPageTask() {116 return executor.submit(() -> widgetsService.getPage(0, 10, new SearchArea()).isEmpty());117 }118}...

Full Screen

Full Screen

Source:OrderServiceTest.java Github

copy

Full Screen

...47 ArgumentCaptor<VoucherOrder> argumentCaptor = ArgumentCaptor.forClass(VoucherOrder.class);48 verify(orderRepository).save(argumentCaptor.capture());49 VoucherOrder actualOrder = argumentCaptor.getValue();50 assertThat(actualOrder).isNotNull();51 assertThat(actualOrder.getStatus().toString()).isEqualTo("PROCESSING");52 assertThat(actualOrder.getVoucherTelco()).isEqualTo("1234");53 assertThat(actualOrder.getPhoneNumber()).isEqualTo("12345");54 assertThat(actualOrder.getVoucherValue()).isEqualTo(123);55 }56 @Test57 public void processOrder_withInTimeLimit() {58 VoucherOrder order = new VoucherOrder();59 order.setVoucherTelco("test");60 order.setVoucherValue(1000);61 order.setPhoneNumber("123");62 doAnswer(new AnswersWithDelay(500, new Returns("test code")))63 .when(provisionClient).getVoucher("test", 1000);64 test.timeoutSeconds = 1;65 OrderResponse actualResponse = test.processOrder(order);...

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.internal.stubbing.answers.AnswersWithDelay;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5import java.util.concurrent.TimeUnit;6import java.util.concurrent.atomic.AtomicInteger;7import java.util.concurrent.atomic.AtomicLong;8public class Main {9 public static void main(String[] args) {10 AtomicInteger counter = new AtomicInteger();11 Answer answer = new AnswersWithDelay(1, TimeUnit.SECONDS, new Answer() {12 public Object answer(InvocationOnMock invocation) throws Throwable {13 return counter.incrementAndGet();14 }15 });16 Runnable runnable = Mockito.mock(Runnable.class, answer);17 runnable.run();18 System.out.println(runnable.toString());19 }20}21import org.mockito.Mockito;22import org.mockito.internal.stubbing.answers.CallsRealMethods;23import org.mockito.invocation.InvocationOnMock;24import org.mockito.stubbing.Answer;25import java.util.concurrent.TimeUnit;26import java.util.concurrent.atomic.AtomicInteger;27import java.util.concurrent.atomic.AtomicLong;28public class Main {29 public static void main(String[] args) {30 AtomicInteger counter = new AtomicInteger();31 Answer answer = new CallsRealMethods();32 Runnable runnable = Mockito.mock(Runnable.class, answer);33 runnable.run();34 System.out.println(runnable.toString());35 }36}37import org.mockito.Mockito;38import org.mockito.internal.stubbing.answers.DoesNothing;39import org.mockito.invocation.InvocationOnMock;40import org.mockito.stubbing.Answer;41import java.util.concurrent.TimeUnit;42import java.util.concurrent.atomic.AtomicInteger;43import java.util.concurrent.atomic.AtomicLong;44public class Main {45 public static void main(String[] args) {46 AtomicInteger counter = new AtomicInteger();47 Answer answer = new DoesNothing();48 Runnable runnable = Mockito.mock(Runnable.class, answer);49 runnable.run();50 System.out.println(runnable.toString());51 }52}

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1import java.lang.reflect.Method;2import org.mockito.internal.stubbing.answers.AnswersWithDelay;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5public class 1 {6 public static void main(String[] args) {7 AnswersWithDelay answer = new AnswersWithDelay(1);8 System.out.println(answer.toString());9 }10}11Your name to display (optional):

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.stubbing.answers.AnswersWithDelay;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4import org.mockito.stubbing.Stubber;5import java.util.concurrent.TimeUnit;6import static org.mockito.Mockito.mock;7import static org.mockito.Mockito.when;8public class Main {9 public static void main(String[] args) {10 Stubber stubber = when(mock(Answer.class).answer((InvocationOnMock invocation) -> null));11 Answer answer = new AnswersWithDelay(1, TimeUnit.MINUTES);12 System.out.println(answer.toString());13 }14}15import org.mockito.internal.stubbing.answers.AnswersWithDelay;16import org.mockito.invocation.InvocationOnMock;17import org.mockito.stubbing.Answer;18import org.mockito.stubbing.Stubber;19import java.util.concurrent.TimeUnit;20import static org.mockito.Mockito.mock;21import static org.mockito.Mockito.when;22public class Main {23 public static void main(String[] args) {24 Stubber stubber = when(mock(Answer.class).answer((InvocationOnMock invocation) -> null));25 Answer answer = new AnswersWithDelay(1, TimeUnit.MINUTES);26 System.out.println(answer.toString());27 }28}29import org.mockito.internal.stubbing.answers.AnswersWithDelay;30import org.mockito.invocation.InvocationOnMock;31import org.mockito.stubbing.Answer;32import org.mockito.stubbing.Stubber;33import java.util.concurrent.TimeUnit;34import static org.mockito.Mockito.mock;35import static org.mockito.Mockito.when;36public class Main {37 public static void main(String[] args) {38 Stubber stubber = when(mock(Answer.class).answer((InvocationOnMock invocation) -> null));39 Answer answer = new AnswersWithDelay(1, TimeUnit.MINUTES);40 System.out.println(answer.toString());41 }42}43import org.mockito.internal.stubbing.answers.AnswersWithDelay;44import org.mockito.invocation.InvocationOnMock;45import org.mockito.stubbing.Answer;46import org.mockito.stubbing.Stubber;47import java.util.concurrent.TimeUnit;48import static org.mockito.Mockito.mock;49import static org.mockito.Mockito.when;50public class Main {

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.stubbing.answers.AnswersWithDelay;2import java.util.concurrent.TimeUnit;3public class 1 {4 public static void main(String[] args) {5 AnswersWithDelay answer = new AnswersWithDelay(100, TimeUnit.MILLISECONDS);6 System.out.println(answer);7 }8}

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.stubbing.answers.AnswersWithDelay;2import java.util.concurrent.TimeUnit;3public class 1 {4 public static void main(String[] args) {5 AnswersWithDelay obj = new AnswersWithDelay(2, TimeUnit.SECONDS);6 System.out.println(obj.toString());7 }8}9import org.mockito.internal.stubbing.answers.CallsRealMethods;10public class 2 {11 public static void main(String[] args) {12 CallsRealMethods obj = new CallsRealMethods();13 System.out.println(obj.toString());14 }15}16import org.mockito.internal.stubbing.answers.DoesNothing;17public class 3 {18 public static void main(String[] args) {19 DoesNothing obj = new DoesNothing();20 System.out.println(obj.toString());21 }22}23import org.mockito.internal.stubbing.answers.Returns;24public class 4 {25 public static void main(String[] args) {26 Returns obj = new Returns("Hello");27 System.out.println(obj.toString());28 }29}30import org.mockito.internal.stubbing.answers.ReturnsArgumentAt;31public class 5 {32 public static void main(String[] args) {33 ReturnsArgumentAt obj = new ReturnsArgumentAt(2);34 System.out.println(obj.toString());35 }36}37import org.mockito.internal.stubbing.answers.ReturnsElementsOf;38import java.util.Arrays;

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.stubbing.answers.AnswersWithDelay;2public class Main {3 public static void main(String[] args) {4 AnswersWithDelay answersWithDelay = new AnswersWithDelay(1, "test");5 System.out.println(answersWithDelay.toString());6 }7}8AnswersWithDelay{delay=1, value=test}9About toString() method

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.stubbing.answers;2import org.mockito.internal.stubbing.answers.AnswersWithDelay;3public class Test {4 public static void main(String[] args) {5 AnswersWithDelay answersWithDelay = new AnswersWithDelay(0, null);6 answersWithDelay.toString();7 }8}9package org.mockito.internal.stubbing.answers;10public class Test {11 public static void main(String[] args) {12 AnswersWithDelay answersWithDelay = new AnswersWithDelay(0, null);13 answersWithDelay.toString();14 }15}

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1package com.puppycrawl.tools.checkstyle.checks.annotation.annotationlocation;2import java.lang.annotation.ElementType;3import java.lang.annotation.Target;4import java.util.concurrent.TimeUnit;5import org.mockito.internal.stubbing.answers.AnswersWithDelay;6@Target({ElementType.TYPE_USE})7@interface InputAnnotationLocationAnonInnerWithToString {8}9public class InputAnnotationLocationAnonInnerWithToString {10 void foo() {11 new AnswersWithDelay(1, TimeUnit.SECONDS) {12 public String toString() {13 return "test";14 }15 };16 }17 void bar() {18 new AnswersWithDelay(1, TimeUnit.SECONDS) {19 public String toString() {20 return "test";21 }22 };23 }24}

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.stubbing.answers;2import java.util.concurrent.TimeUnit;3public class AnswersWithDelay {4 public static void main(String[] args) {5 AnswersWithDelay answersWithDelay = new AnswersWithDelay(10, TimeUnit.SECONDS);6 String str = answersWithDelay.toString();7 System.out.println(str);8 }9}10package org.mockito.internal.stubbing.answers;11public class CallsRealMethods {12 public static void main(String[] args) {13 CallsRealMethods callsRealMethods = new CallsRealMethods();14 String str = callsRealMethods.toString();15 System.out.println(str);16 }17}18package org.mockito.internal.stubbing.answers;19public class DoesNothing {20 public static void main(String[] args) {21 DoesNothing doesNothing = new DoesNothing();22 String str = doesNothing.toString();23 System.out.println(str);24 }25}26package org.mockito.internal.stubbing.answers;27public class Returns {28 public static void main(String[] args) {29 Returns returns = new Returns("Hello");30 String str = returns.toString();31 System.out.println(str);32 }33}34package org.mockito.internal.stubbing.answers;35public class ReturnsEmptyValues {36 public static void main(String[] args) {37 ReturnsEmptyValues returnsEmptyValues = new ReturnsEmptyValues();

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.stubbing.answers;2import org.mockito.internal.stubbing.answers.AnswersWithDelay;3import org.mockito.internal.stubbing.answers.Returns;4import org.mockito.internal.stubbing.answers.ThrowsException;5import org.mockito.internal.stubbing.answers.DoesNothing;6import org.mockito.internal.stubbing.answers.CallsRealMethods;7import org.mockito.stubbing.Answer;8import org.mockito.stubbing.Stubber;9import org.mockito.invocation.InvocationOnMock;10import org.mockito.stubbing.OngoingStubbing;11import org.mockito.stubbing.Answer;12import org.mockito.stubbing.Stubber;13import org.mockito.invocation.InvocationOnMock;14import org.mockito.stubbing.OngoingStubbing;15import org.mockito.stubbing.Answer;16import org.mockito.stubbing.Stubber;17import org.mockito.invocation.InvocationOnMock;18import org.mockito.stubbing.OngoingStubbing;19import org.mockito.stubbing.Answer;20import org.mockito.stubbing.Stubber;21import org.mockito.invocation.InvocationOnMock;22import org.mockito.stubbing.OngoingStubbing;23import org.mockito.stubbing.Answer;24import org.mockito.stubbing.Stubber;25import org.mockito.invocation.InvocationOnMock;26import org.mockito.stubbing.OngoingStubbing;27import org.mockito.stubbing.Answer;28import org.mockito.stubbing.Stubber;29import org.mockito.invocation.InvocationOnMock;30import org.mockito.stubbing.OngoingStubbing;31import java.util.concurrent.TimeUnit;32import org.mockito.stubbing.Answer;33import org.mockito.stubbing.Stubber;34import org.mockito.invocation.InvocationOnMock;35import org.mockito.stubbing.OngoingStubbing;36public class AnswersWithDelayTest {37 public static void main(String[] args) {38 AnswersWithDelay answersWithDelay = new AnswersWithDelay(1, TimeUnit.SECONDS);39 String str = answersWithDelay.toString();40 System.out.println(str);41 }42}43package org.mockito.internal.stubbing.answers;44import org.mockito.internal.stubbing.answers.AnswersWithDelay;45import org.mockito.internal.stubbing.answers.Returns;46import org.mockito.internal.stubbing.answers.ThrowsException;47import org.mockito.internal.stubbing.answers.DoesNothing;48import org.mockito

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful