yegor256
yegor256

Reputation: 105043

How to mock an outgoing Socket connection?

In integration tests (JDK 6) I'm trying to catch all outgoing TCP connections and mock them. Looks like I should use java.net.Socket#setSocketImplFactory() method. Works fine at the moment, but I can't understand how I can get an access to original factory, in order to instantiate original JDK-provided SocketImpl class. I need this mostly because I want to let some connections to go out freely, without mocking. Can you suggest some manuals/guidelines/instructions about this problem?

Upvotes: 11

Views: 2599

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533452

Instead of mocking a Socket I would create a Socket service for the Socket to talk to. This can capture all the data written and reply in any manner you wish. It can be run in the same test and possibly in the same thread.

Upvotes: 2

Mark Rotteveel
Mark Rotteveel

Reputation: 108933

According to the javadoc, you should be able to use SocketFactory#getDefault() to get the default SocketFactory for your environment.

BTW: You might also want to look at this RFE/bug which declares that SocketImplFactory is basically a dead-end: https://bugs.java.com/bugdatabase/view_bug?bug_id=4245730

Upvotes: 0

Rich
Rich

Reputation: 15757

Looking at the source code of the Socket class, there is no original factory - the constructors check to see if factory is null, and if it is, they just assign impl to be a new PlainSocketImpl().

Upvotes: 0

Related Questions