AbirHajAli
AbirHajAli

Reputation: 3

Optimize a keyword

I automate tests using SilkTest and Java. In this keyword, I get the list and I compare it to the one expected. Is there a way to optimize my code since I have declared each list multiple times.

public void vérification_des_listes(String listAttendu) {
    final String[] list1 = listAttendu.split(";", -1);
    final ArrayList<String> listExpected = new ArrayList<>();
    for (final String I : list1) {
        listExpected.add(I);
    }
    System.out.println(listExpected.toString());
    final Object[] list2 = desktop.<DomListBox>find("BrowserApplication.BrowserWindow.Personne.Titre_champ").getItems().toArray();
    final ArrayList<String> listFound = new ArrayList<>();
    for (final Object E : list2) {
        listFound.add(E.toString());
    }
    System.out.println(listFound.toString());
    assertTrue("", listExpected.equals(listFound));

} 

Upvotes: -2

Views: 55

Answers (2)

pringi
pringi

Reputation: 4652

  public static void vérification_des_listes(String listAttendu) {
    final String[] list1 = listAttendu.split(";", -1);
    final List<String> listExpected = Arrays.asList(list1);


    final Object[] list2 = desktop.<DomListBox>find("BrowserApplication.BrowserWindow.Personne.Titre_champ").getItems().toArray();

    final List<String> listFound = Arrays.stream(list2).map(Objects::toString).toList();

     Assertions.assertEquals(listExpected, listFound);
  }

You can take advantage of class Arrays, and also do some java stream processing for converting your objects to String. Also take a look at assertj to compare Collections in a more flexible way (can see an example here).

Upvotes: 0

redPanda
redPanda

Reputation: 86

Instead of

 final String[] list1 = listAttendu.split(";", -1);
 final ArrayList<String> listExpected = new ArrayList<>();
 for (final String I : list1) {
     listExpected.add(I);
 }

you could use

final String[] list1 = listAttendu.split(";", -1);
final List<String> listExpected = Arrays.asList(list1);

See https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#asList(T...)

Upvotes: 0

Related Questions