我有一个 Android 服务,它通过在 TCP 上来回传递消息来处理与游戏同步服务器的通信。
我希望能够对该服务的行为进行单元测试。也就是说,当在线上看到数据时,数据被读取、解析并发出有效的相应意图,并且当服务接收到意图时,它正确地创建要发送到服务器的消息。
我对单元测试不是特别擅长,但我正试图让单元测试成为我实践的一部分。我不知道如何处理这样的事情。感觉好像我需要模拟套接字并伪造输入和输出流,但我真的不知道该怎么做,尤其是当它适用于 Android 时。
这是(为简洁起见,大幅缩减)服务:
public class GameSyncService extends Service {
Thread mInputThread = new Thread() {
/**
* Parse commands from a message string, broadcast the command intents, and
* return the remainder of the message
* @param message The message to parse for commands
* @returns the remaining characters
*/
private String parseCommands(String message) {
// Parse the command, Broadcast the Intent and return any remainder
}
@Override
public void run() {
String message = "";
int charsRead = 0;
char [] buffer = new char[BUFFER_SIZE];
while(!Thread.interrupted()) {
try {
while ((charsRead = mIn.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
message = parseCommands(message);
}
} catch (IOException e) {
Log.d(LOG_TAG, "Error receiving response: " + e.getLocalizedMessage());
disconnectFromServer();
connectToServer();
}
}
}
};
private BroadcastReceiver mMessageSender = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
sendMessage(message);
}
};
@Override
public IBinder onBind(Intent arg0) {
return null;
}
private void sendMessage(String message) {
new SendCommandMessageTask().execute(message);
}
/**
* Create a new connection to the server
*/
private void connectToServer() {
try {
if (mSocket == null) {
mSocket = new Socket(mHost, mPort);
mOut = new PrintWriter(mSocket.getOutputStream());
mIn = new BufferedReader(new InputStreamReader(mSocket.getInputStream()), BUFFER_SIZE);
sendMessage("Handshake:|" + pInfo.versionName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Disconnect from the server and reset the socket to null
*/
private void disconnectFromServer() {
if (mSocket != null) {
try {
mIn.close();
mOut.close();
mSocket.close();
mSocket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public int onStartCommand(Intent i, int flags, int startId) {
Log.d(LOG_TAG, "GameSyncService Started");
mHost = i.getStringExtra("host");
mPort = i.getIntExtra("port", 9000);
connectToServer();
mInputThread.start();
return START_STICKY;
}
@Override
public void onCreate() {
registerReceiver(mMessageSender, new IntentFilter(COMMAND_MESSAGE_SEND_ACTION));
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
super.onCreate();
}
@Override
public void onDestroy() {
unregisterReceiver(mMessageSender);
super.onDestroy();
}
}