Sameera De Silva
1 min readOct 5, 2021

How to get the copied string in Java and assert the copied text and pass to a Webdriver element .

In some test scenarios, automation engineers have to automate test scenarios where when clicking a button or link, text should be copied. Then verify the copied text using assertions and pass that text in to a text field .

Let’s see how to achieve this .

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
private void copiedTextVerification() throws IOException, UnsupportedFlavorException {

//Verify that text is copied when clicked on lnk_Copy_Permalink and stays on clipboard and not empty.
driver.findElement(By.id("button_To_copy_Text")).click();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Clipboard clipboard = toolkit.getSystemClipboard();
String actualCopedText = (String) clipboard.getData(DataFlavor.stringFlavor);
System.out.println("String from Clipboard:" + actualCopedText);
//Assert the copied text contains the expected text.
Assert.assertTrue(actualCopedText.startsWith("Expected Copied Text"));
//Send the copied text to an element.
driver.findElement(By.id("button_To_send_Text")).sendKeys(actualCopedText);

}

In remote webdriver this might not work (I saw this sporadically returns a wrong value for copied text . https://www.browserstack.com/question/489)

Below code is the same but with the try{ catch.

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
//Assume that text is already copied and using below code it could be extracted.private void getCopiedText(){String copiedText = null;
try {
copiedText = (String) clipboard.getData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Copied text is-"+copiedText);
}

No responses yet