Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7939611
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T23:09:17+00:00 2026-06-03T23:09:17+00:00

I have an Android Service that handles communications with a game sync server by

  • 0

I have an Android Service that handles communications with a game sync server by passing messages over TCP back and forth.

I’d like to be able to unit test the behavior of this service. Namely that when data is seen on the wire that data is read, parsed, and sends out the valid corresponding intent and when the Service receives an Intent it correctly creates a message to be sent to the server.

I’m not particularly good about unit testing, but I’m trying to make unit testing part of my practice. I’m not sure how to approach something like this. It feels like somehow I would need to mock up socket and fake the Input and Output streams, but I really don’t know how to do that especially as it applies to Android.

Here is the (greatly trimmed down for breverity) service:

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();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T23:09:20+00:00Added an answer on June 3, 2026 at 11:09 pm

    Welcome to the world of mocking. What you need to do can be easily done with the help of Android Mock. You should read up on how Expectations work with Android Mock in the project’s Writing Tests using Android Mock wiki page.

    What I would do is implement a Socket service that encapsulates the underlying TCP/socket calls. Then using Android Mock, you mock your Socket service and using Expectations to verify the correct data is passed in by a higher level method (like GameSyncService )

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an Android Service that accesses the database about once per minute. Is
I have a php web service that takes the request from android/iphone app and
I have a comprehension question about Android Services. I have a Service that performs
I currently have a Service in Android that is a sample VOIP client so
I have a Web Service and an Android application that uses this web service.
I have a simple client-server app on android. the android service communicates with the
I have an Android service that runs in background. I need it to recieve
We have an Android app and a Web Service. We want to download part
I have accessed a web service from Android 2.2.It is perfectly OK.I changed my
Can we have multiple instance of a Service in Android ? I want a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.