简体   繁体   中英

Comparing String[] using Junit4

I am trying to perform test on method:

public  String[] getFooBar(int size) {
    String[] stringsArray = new String[100];
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i <= size; i++) {
        stringBuilder.append(String.format(i + " "));
        if (i % 3 == 0) {
            stringBuilder.append(String.format("Foo"));
        }
        if (i % 5 == 0) {
            stringBuilder.append(String.format("Bar"));
        }
        stringBuilder.append(System.lineSeparator());
        stringsArray[i] = stringBuilder.toString();
    }
    return stringsArray;
}

}

I've tried to use index on Array, convert it to Strings using Array.ToString and compare it with String value eg. "FooBar". What is happening when I try to look for one index eg. 50 I get all index from table starting with 0 - 50. I've tried to do ArrayList but result was the same. Anyone guide me how to test this method ?

The reason for your issue is that you are constantly appending the StringBuilder and then setting each index to that appended value. That means that each index will look like this:

index 0: 0
index 1: 0 1
index 2: 0 1 2
index 3: 0 1 2 3 foo
index 4: 0 1 2 3 foo 4
index 5: 0 1 2 3 foo 4 5 bar

I assume this is the same concept as FizzBuzz, which means you more than likely have another issue: you are appending the index each time regardless of if it's a multiple of 3 or 5. I'm pretty sure you don't want that. You probably want something closer to this:

public  String[] getFooBar(int size) {
    String[] stringsArray = new String[100];

    for (int i = 0; i <= size; i++) {
        StringBuilder stringBuilder = new StringBuilder();
        if (i % 3 == 0) {
            stringBuilder.append(String.format("Foo"));
        }
        if (i % 5 == 0) {
            stringBuilder.append(String.format("Bar"));
        }
        if(i % 5 != 0 && i % 3 != 0) {
            stringsArray[i] = Integer.toString(i);
        } else {
            stringsArray[i] = stringBuilder.toString();
        }
    }
    return stringsArray;
}

But there really isn't need for all of that. You can just do this:

public String[] getFooBar(int size) {
  String[] arr = new String[100];
  for(int i = 0; i <= size; i++) {
    String str = ""; // In situations like this the JVM turns this into a StringBuilder behind the scenes
    if(i % 3 == 0) {
      str += "Foo";
    }
    if(i % 5 == 0) {
      str += "Bar";
    }
    if(i % 3 != 0 && i % 5 != 0) {
      arr[i] = Integer.toString(i);
    } else {
      arr[i] = str;
    }
  }
  return arr;
}

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