Skip to content

Commit 36eafc3

Browse files
feat(tests): Add unit test for client connect function
1 parent 52f61e1 commit 36eafc3

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client/Client.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ public open class Client(
102102
} catch (error: Throwable) {
103103
close()
104104
if (error !is CancellationException) {
105-
throw IllegalStateException("Error connecting to transport", error)
105+
throw IllegalStateException("Error connecting to transport: ${error.message}")
106106
} else {
107107
throw error
108108
}

src/jvmTest/kotlin/client/ClientTest.kt

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import io.modelcontextprotocol.kotlin.sdk.CreateMessageResult
66
import io.modelcontextprotocol.kotlin.sdk.EmptyJsonObject
77
import io.modelcontextprotocol.kotlin.sdk.Implementation
88
import InMemoryTransport
9+
import io.mockk.coEvery
10+
import io.mockk.spyk
911
import io.modelcontextprotocol.kotlin.sdk.InitializeRequest
1012
import io.modelcontextprotocol.kotlin.sdk.InitializeResult
1113
import io.modelcontextprotocol.kotlin.sdk.JSONRPCMessage
@@ -189,6 +191,61 @@ class ClientTest {
189191
assertTrue(closed)
190192
}
191193

194+
@Test
195+
fun `should reject due to non cancellation exception`() = runTest {
196+
var closed = false
197+
val clientTransport = object : AbstractTransport() {
198+
override suspend fun start() {}
199+
200+
override suspend fun send(message: JSONRPCMessage) {
201+
if (message !is JSONRPCRequest) return
202+
check(message.method == Method.Defined.Initialize.value)
203+
204+
val result = InitializeResult(
205+
protocolVersion = LATEST_PROTOCOL_VERSION,
206+
capabilities = ServerCapabilities(),
207+
serverInfo = Implementation(
208+
name = "test",
209+
version = "1.0"
210+
)
211+
)
212+
213+
val response = JSONRPCResponse(
214+
id = message.id,
215+
result = result
216+
)
217+
218+
_onMessage.invoke(response)
219+
}
220+
221+
override suspend fun close() {
222+
closed = true
223+
}
224+
}
225+
226+
val mockClient = spyk(
227+
Client(
228+
clientInfo = Implementation(
229+
name = "test client",
230+
version = "1.0"
231+
),
232+
options = ClientOptions()
233+
)
234+
)
235+
236+
coEvery{
237+
mockClient.request<InitializeResult>(any())
238+
} throws IllegalStateException("Test error")
239+
240+
val exception = assertFailsWith<IllegalStateException> {
241+
mockClient.connect(clientTransport)
242+
}
243+
244+
assertEquals("Error connecting to transport: Test error", exception.message)
245+
246+
assertTrue(closed)
247+
}
248+
192249
@Test
193250
fun `should respect server capabilities`() = runTest {
194251
val serverOptions = ServerOptions(

0 commit comments

Comments
 (0)