我怎样才能使测试有效? ,我没有在我的代码中遇到错误。我是新的学习JAVA。我知道问题出在阵列上,但我不知道如何解决它。
解压错误:“array lengths differed, expected.length=2 actual.length=5; arrays first different at element [2];”
压缩错误:“数组长度不同,expected.length=3 actual.length=2;数组首先在元素 [0] 处不同;”
代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class RLE {
public static void compress(InputStream is, OutputStream os) throws IOException {
int currentByte = is.read();
int count = 1;
while (currentByte != -1) {
int nextByte = is.read();
if (nextByte == currentByte && count < 255) {
count++;
} else {
os.write((byte) count);
os.write((byte) currentByte);
count = 1;
}
currentByte = nextByte;
}
os.flush();
is.close();
os.close();
}
public static void decompress(InputStream is, OutputStream os) throws IOException {
int currentByte = is.read();
while (currentByte != -1) {
int count = currentByte;
int value = is.read();
byte[] bytes = new byte[count];
for (int i = 0; i < count; i++) {
bytes[i] = (byte) value;
}
os.write(bytes);
currentByte = is.read();
}
os.flush();
is.close();
os.close();
}
}
测试:
import java.io.*;
import static org.junit.Assert.*;
public class RLETest {
private void test1(byte[] expected, byte[] input) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
RLE.compress(new ByteArrayInputStream(input), bos);
assertArrayEquals(expected, bos.toByteArray());
}
private void test2(byte[] expected, byte[] input) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
RLE.decompress(new ByteArrayInputStream(input), bos);
assertArrayEquals(expected, bos.toByteArray());
}
@org.junit.Test
public void compress() throws Exception {
test1(new byte[]{1,1,4}, new byte[]{1,1,1,1,1,1});
test1(new byte[]{1,1,0}, new byte[]{1,1});
test1(new byte[]{1,2,3}, new byte[]{1,2,3});
test1(new byte[]{1, 1, 0, 2, 2, 0, 3, 3, 0}, new byte[]{1, 1, 2, 2, 3, 3});
test1(new byte[]{1, 2, 3, 3, 1, 4}, new byte[]{1, 2, 3, 3, 3, 4});
test1(new byte[]{1,2,3,3,0}, new byte[]{1, 2, 3, 3});
byte[]ar;
ar = new byte[260];
for (int i = 0; i < ar.length; i++) {
ar[i] = 100;
}
test1(new byte[]{100,100,(byte) 255, 100, 100, 1}, ar);
ar = new byte[550];
for (int i = 0; i < ar.length; i++) {
ar[i] = 100;
}
test1(new byte[]{100,100,(byte) 255, 100, 100, (byte) 255, 100, 100, 34}, ar);
}
@org.junit.Test
public void decompress() throws Exception {
test2(new byte[]{5,5}, new byte[]{5,5,0});
test2(new byte[]{1,2,3}, new byte[]{1,2,3});
test2(new byte[]{1,2,2,3}, new byte[]{1,2,2,0,3});
test2(new byte[]{1,2,3,3,3,3}, new byte[]{1,2,3,3,2});
test2(new byte[]{5}, new byte[]{5});
test2(new byte[]{1,1,2,2,3,3,4,4}, new byte[]{1,1,0,2,2,0,3,3,0,4,4,0});
byte[]ar;
ar = new byte[202];
for (int i = 0; i < ar.length; i++) {
ar[i] = 55;
}
test2(ar, new byte[]{55,55,(byte)200});
ar = new byte[259];
for (int i = 0; i < ar.length; i++) {
ar[i] = 55;
}
test2(ar, new byte[]{55,55,(byte)255, 55, 55, 0});
}
}