Unit Testing Location Service

前端 未结 2 1093
星月不相逢
星月不相逢 2021-02-06 07:04

I\'ve got a location tracking service that I\'m trying to unit test. I\'m trying to use the locationManager.addTestProvider and setTestProviderLocation methods to achieve this.

相关标签:
2条回答
  • 2021-02-06 07:28

    I was able to get @ingsaurabh's example working in a unit test after making the following modifications:

    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public final class TestLocationProvider {
        static void sendLocation(double latitude, double longitude) {
            try {
                Socket socket = new Socket("10.0.2.2", 5554); // usually 5554
                socket.setKeepAlive(true);
                String str = "geo fix " + longitude + " " + latitude ;
                Writer w = new OutputStreamWriter(socket.getOutputStream());
                w.write(str + "\r\n");
                w.flush();
            }
            catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    

    The important detail is the IP address. The emulator does not recognize 'localhost' as a valid hostname.

    0 讨论(0)
  • 2021-02-06 07:45

    Hi in my first GPS based project I faced the same problem so I write a java code that will send GPS Fix to my android emulator below is the snippet.

    import java.io.IOException;
    import java.io.PrintStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class Main {
    
    static final int PAUSE = 4000; // ms
    static final float START_LONGITUDE = 51, START_LATITUDE = -1.3f;
    static final int NO_SAMPLE = 100;
    static final float DELTA_LONGITUDE = 0.000005f, DELTA_LADITUDE = 0.000005f;
    
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 5554); // usually 5554
    
            PrintStream out = new PrintStream(socket.getOutputStream());
            float longitude = START_LONGITUDE, latitude = START_LATITUDE;
            String str;
    
            for (int i = 0; i < NO_SAMPLE; i++) {
                str = "geo fix " + latitude + " " + longitude + "\n";
                out.print(str);
                System.out.print(str);
    
                Thread.sleep(PAUSE);
    
                longitude += DELTA_LONGITUDE;
                latitude += DELTA_LADITUDE;
            }
        } catch (UnknownHostException e) {
            System.exit(-1);
        } catch (IOException e) {
            System.exit(-1);
        } catch (InterruptedException e) {
            System.exit(-1);
        }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题