I have the following method, which truncates a string to a certain size in bytes:
public class Utils {
public static String trimStringToBytesSize(String s, int length) {
if (s == null || length < 0) return null;
int trimLength = Math.min(length, s.length());
String trimmedString = s;
while (trimmedString.getBytes().length > length && trimLength >= 0) {
trimmedString = s.substring(0, trimLength);
trimLength--;
}
return trimmedString;
}
}
I wrote some tests for it:
@Test
public void trimStringToBytesSize() {
[...]
trimStringToBytesSizeTestLogic("Шалом",
6,
"Шал"
);
[...]
}
private void trimStringToBytesSizeTestLogic(final String input, final int
stringLength, final String expectedResult) {
final String actRes = Utils.trimStringToBytesSize(input, stringLength);
Assert.assertEquals(expectedResult, actRes);
}
This test runs fine inside IntelliJ Idea. However, it fails when I run it in Gradle. The error is this:
org.junit.ComparisonFailure: expected:<Шал[]> but was:<Шал[ом]>
Obviously, it has something to do with the byte sizes.
I tried to reproduce the problem in a minimal project , which contains the method and the test. The code is the same, but the problem, which appears in the original code does not appear in this minimal project.
I tried to find out the difference between them and compared the encodings in the minimal and the original project. The are the same according to Notepad++ (UTF-8).
What else could cause this test failure? How can I fix it?
Notes: I'm using Java 1.8 and Gradle 2.14 (I can't upgrade to a more recent version due to the requirements of the customer).