1

我有这段代码,我想测试我是否会设置 Handler 并使用 outputstream 和 inputstream 调用方法运行该类是否可以正常工作。我的意思是我会在输入流上收到一些东西,然后将其更改为其他东西并在输出流上发送,然后检查 Handler 发送的消息是否正确。我该怎么做或者我可以模拟输出输入流和处理程序?

我想测试的TestClass。

import android.os.Handler;
import android.util.Log;

public class TestClass {

protected String description;

protected String responce;
protected String valueResponce;
protected int done;
protected Handler listener;
protected int identifier;
protected int target;

public static final int STATE_GOOD = 0;
public static final int STATE_FAILED = 1;
public static final int STATE_ATDPN = 2;

public void addListener(Handler listener) {
    this.listener = listener;       
}

protected void preparation() {
    identifier = Integer.parseInt(this.getRequest(), 16);
    target = HandlerLabels.MESSAGE_DATA;
}

protected void send(OutputStream outStream) {
    String mes = this.getRequest() + '\r';
    byte[] send = mes.getBytes();
    try {
        outStream.write(send);
    } catch (IOException e) {
        done = STATE_FAILED;
    }
}

protected void read(InputStream inStream) {
    try {

        int data = inStream.read();
        String output = "";
        while (data != 62) {
            if (data != 10) {
                if (data != 13) {
                    output += (char) data;
                }
            }
            data = inStream.read();

        }
        responce = output;

    } catch (IOException e) {
        done = STATE_FAILED;
    }

}

protected void noticeListener() {
    if (listener == null) {
        Log.d(tag, "listener null");
    } else {
        listener.obtainMessage(target, identifier, -1, valueResponce)
                .sendToTarget();

    }
}

protected boolean control(String value){
    if(value.length() == 0){
        done = STATE_FAILED;
        return false;
    }
    return true;
}

public int run(InputStream inStream, OutputStream outStream) {
    preparation();

    if (done == STATE_GOOD)
        send(outStream);

    if (done == STATE_GOOD)
        read(inStream);

    if (control(responce))
        valueResponce = calculateValue(responce);

    if (done == STATE_GOOD)
        noticeListener();

    return done;
}

protected String calculateValue(String value) {
    String[] arr = value.split(" ");
    int A = Integer.parseInt(arr[2], 16);
    return String.valueOf(((A*100)/255));   
}

public String getRequest() {
    return "01041";
}

public String getDescription() {
    return description;
}

public int isDone() {
    return done;
}

public void setDone(int done) {
    this.done = done;
}

public String getResponce() {
    return responce;
}

public void setResponce(String responce) {
    this.responce = responce;
}
}
4

0 回答 0