简体   繁体   中英

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));

} 

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...)

  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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM