Is it possible to stub or mock a SocketChannel with Spock?
<p>Essentially I have a Java class which performs a select on a socket channel, and I want to stub the channel such that I can test select works as expected.</p>

<p>For example, this is roughly what the class being tested does:</p>

<pre><code>class TestedClass {
    TestedClass(SocketChannel socket) { this.socket = socket }

    // ...
    SocketChannel socket;
    // ...
    void foo() {
        // Wait a while for far end to close as it will report an error 
        // if we do it.  But don't wait forever! 
        // A -1 read means the socket was closed by the other end.
        // If we select on a read, we can check that, or time out 
        // after a reasonable delay.

        Selector selector = Selector.open();
        socket.configureBlocking(false);
        socket.register(selector, SelectionKey.OP_READ);
        while(selector.select(1000) == 0) {
            Log.debug("waiting for far end to close socket...")
        }

        ByteBuffer buffer = ByteBuffer.allocate(1);
        if (socket.read(buffer) &gt;= 0) {
            Log.debug("far end didn't close");
            // The far end didn't close the connection, as we hoped
            abort(AbortCause.ServerClosed);
        }

        Log.debug("far end closed");
    }
}
</code></pre>

<p>I'd like to be able to test something like this:</p>

<pre><code>def "test we don't shut prematurely" () {
    when:
    boolean wasClosedPrematurely
    SocketChannel socket = Stub(@SocketChannel) {
        // insert stub methods here ....
    }

    TestedClass tc = new TestedClass(socket)
    tc.foo();

    then:
    wasClosedPrematurely == false
}
</code></pre>

<p>This based on a real example, but the details aren't important.  The general aim is how to stub SocketChannels which support selects, so that I don't have to create a real client to test against.</p>

<p>I also know it's more complicated than just stubbing SocketChannel: it seems like I need to intercept <code>Selector.open()</code> or somehow provide a custom system default SelectorProvider.  If I simply stub SocketChannel I get an IllegalSelectorException when I try to register the selector obtained via <code>Selection.open()</code> with my stub, and the base <code>AbstractSelectableChannel#register</code> method is unfortunately final.</p>

<p>But I cannot find any useful pointers on how or whether this is even possible with Spock Mocks, and it seems like it might be quite a common thing to want, so a good question to ask here.  Can anyone help?</p>