3

我在 UTF-8 编码文件中有以下 junit 测试。

public class EncodingTest {

 private static byte[] utf8Bytes;

 private static byte[] utf8Bytes2;

 private static byte[] utf8Bytes3;

 static {
try {
    utf8Bytes = "åæø".getBytes("UTF-8");
    utf8Bytes2 = new byte[] { (byte) 0xc3, (byte) 0xa5, (byte) 0xc3, (byte) 0xa6, (byte) 0xc3, (byte) 0xb8 };
    utf8Bytes3 = "\u00E5\u00E6\u00F8".getBytes("UTF-8");
} catch (final UnsupportedEncodingException e) {
    assertTrue(false);
}

 }

 @Test
 public void testUTF8Encoding1() throws UnsupportedEncodingException {
assertTrue(Arrays.equals(utf8Bytes, utf8Bytes2));
 }

 @Test
 public void testUTF8Encoding2() throws UnsupportedEncodingException {
 assertTrue(Arrays.equals(utf8Bytes2, utf8Bytes3));
 }

 @Test
 public void testUTF8Encoding3() throws UnsupportedEncodingException {
 assertEquals(new String(utf8Bytes), new String(utf8Bytes2));
 }

 @Test
 public void testUTF8Encoding4() throws UnsupportedEncodingException {
 assertEquals(new String(utf8Bytes2), new String(utf8Bytes3));
 }
}

测试在 ant 中失败,但在 eclipse 中有效。我正在使用的 ANT 任务如下:

<target
    name="test"
    depends="compile-tests"
    description="Test the full company tests" >

    <junit fork="yes" haltonfailure="yes" >
        <jvmarg value="-Dfile.encoding=UTF-8"/>
        <classpath>

            <path refid="test.classpath" />

            <fileset dir="war/WEB-INF/lib/" >

                <include name="*.jar" />
            </fileset>
        </classpath>

        <formatter
            type="plain"
            usefile="false" />
        <!-- to screen -->
        <!-- formatter type="plain" / -->
        <!-- to file -->

        <batchtest>

            <fileset
                dir="test/classes/"
                includes="**/*Test.class" />
        </batchtest>
    </junit>
</target>

输出如下:

test:
[junit] Testsuite: com.company.appengine.EncodingTest
[junit] Tests run: 4, Failures: 2, Errors: 0, Time elapsed: 0,028 sec
[junit]
[junit] Testcase: testUTF8Encoding1 took 0,004 sec
[junit]     FAILED
[junit]
[junit] junit.framework.AssertionFailedError:
[junit]     at com.company.appengine.EncodingTest.testUTF8Encoding1(EncodingTest.java:42)
[junit]
[junit] Testcase: testUTF8Encoding2 took 0 sec
[junit] Testcase: testUTF8Encoding3 took 0,001 sec
[junit]     FAILED
[junit] expected:<[åæø]> but was:<[åæø]>
[junit] junit.framework.AssertionFailedError: expected:<[åæø]> but was:<[åæø]>
[junit]     at com.company.appengine.EncodingTest.testUTF8Encoding3(EncodingTest.java:52)
[junit]
[junit] Testcase: testUTF8Encoding4 took 0 sec

任何的想法?

4

1 回答 1

2

请首先确保javac知道您的源文件是用 utf-8 编码的。如果您使用javac task进行编译,请提供encoding属性。

于 2012-10-30T14:40:54.757 回答