Skip to content

Commit d07f392

Browse files
committed
Added a test and more synchronized logic
1 parent 705f986 commit d07f392

File tree

2 files changed

+55
-4
lines changed

2 files changed

+55
-4
lines changed

ParseLiveQuery/src/main/java/com/parse/OkHttp3SocketClientFactory.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,14 @@ public synchronized void open() {
9494

9595
@Override
9696
public synchronized void close() {
97-
setState(State.DISCONNECTING);
98-
if (webSocket != null) {
97+
if (State.NONE != state) {
98+
setState(State.DISCONNECTING);
9999
webSocket.close(STATUS_CODE, CLOSING_MSG);
100100
}
101101
}
102102

103103
@Override
104-
public void send(String message) {
104+
public synchronized void send(String message) {
105105
if (state == State.CONNECTED) {
106106
webSocket.send(message);
107107
}
@@ -113,7 +113,9 @@ public State getState() {
113113
}
114114

115115
private void setState(State newState) {
116-
this.state = newState;
116+
synchronized (this) {
117+
this.state = newState;
118+
}
117119
this.webSocketClientCallback.stateChanged();
118120
}
119121
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.parse;
2+
3+
import junit.framework.Assert;
4+
5+
import org.junit.After;
6+
import org.junit.Before;
7+
import org.junit.Test;
8+
import org.junit.runner.RunWith;
9+
import org.mockito.Mock;
10+
import org.mockito.runners.MockitoJUnitRunner;
11+
12+
import java.net.URI;
13+
14+
import okhttp3.OkHttpClient;
15+
16+
import static com.parse.WebSocketClient.State.NONE;
17+
18+
@RunWith(MockitoJUnitRunner.class)
19+
public class TestOkHttpClientFactory {
20+
21+
@Mock
22+
private OkHttpClient okHttpClientMock;
23+
24+
@Mock
25+
private WebSocketClient.WebSocketClientCallback webSocketClientCallbackMock;
26+
27+
private OkHttp3SocketClientFactory okHttp3SocketClientFactory;
28+
private WebSocketClient webSocketClient;
29+
30+
@Before
31+
public void setUp() throws Exception {
32+
okHttp3SocketClientFactory = new OkHttp3SocketClientFactory(okHttpClientMock);
33+
webSocketClient = okHttp3SocketClientFactory.createInstance(webSocketClientCallbackMock, new URI("http://www.test.com"));
34+
}
35+
36+
@After
37+
public void tearDown() {
38+
webSocketClient.close();
39+
}
40+
41+
@Test
42+
public void testClientCloseWithoutOpenShouldBeNoOp() {
43+
Assert.assertEquals(NONE, webSocketClient.getState());
44+
webSocketClient.close();
45+
webSocketClient.send("test");
46+
Assert.assertEquals(NONE, webSocketClient.getState());
47+
}
48+
49+
}

0 commit comments

Comments
 (0)