5

I am trying to write unit tests for some string-formatting code. Formatted output is likely in some cases to contain bidirectional text, i.e. a mixture of both left-to-right and right-to-left.

I have verified empirically that the output looks correct, for all combinations of LTR and RTL input and output, when run on an Android device or emulator. I am struggling to capture this in unit tests, though; I'm not sure how I can correctly specify, in my test cases, the expected output.

For example, I want to assert that the returned string will be rendered like this:

-د.ك.123,456.78

That is, the glyphs should appear in this order from left to right:

-

1

2

3

,

4

5

6

.

7

8

.

ك

.

د

(You have no idea how hard it was even editing that into the right sequence in the SO edit box!)

I have tried using standard string comparison methods in my test cases, like this:

assertEquals("-د.ك.123,456.78", formattedOutput);

but that fails because the expected-output string in the test code is having its text reordered. In fact it even appears differently in the source depending on which tool I use to view the source (Android Studio vs. Github-with-Chrome), so I have no confidence that it's testing the right thing.

I have also tried building up the expected-output value in steps, to avoid confusion in the editor, although it results in the same string literal being constructed under the hood:

assertEquals("-123,456.78" + SYMBOL, formattedOutput);

How can I compare the visual order of the glyphs, rather than the logical order? Will Android's BidiFormatter help me here?

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • Maybe this previous answer can help: http://stackoverflow.com/questions/9445133/string-utf8-encoding-issue – Peter Apr 09 '15 at 18:48
  • Can you show how you are building formattedOutput? – Luis Apr 11 '15 at 17:20
  • Also, can you show the output of the failed assertion? (i.e., show the value of formattedOutput that causes the assertion to fail) – Luis Apr 11 '15 at 17:22

1 Answers1

0

A typical assertEquals on that string and a method returning the same String (ie. a new String object) works fine for me, using IntelliJ 14.0.3 Ultimate, UTF-8 set for the actual text file.

What also works, and what you could try, is to get the bytes of the String you want to compare with (maybe manually specifying a specific encoding) and then compare the returned byte arrays with one another, using assertArrayEquals. I can't see why getting the bytes of a String using a manually set encoding wouldn't work, at least.

You could check this page for inspiration, if you like: https://docs.oracle.com/javase/tutorial/i18n/text/string.html

Birb
  • 866
  • 10
  • 23