Created
February 2, 2018 19:09
-
-
Save pslusarz/04bdf8d7c8e5a001388157239ccefd16 to your computer and use it in GitHub Desktop.
Mulththreading problems using Spock's mocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grab('org.spockframework:spock-core:1.1-groovy-2.4') | |
@Grab('cglib:cglib:2.2') | |
import spock.lang.Specification | |
import java.util.concurrent.ExecutorService | |
import java.util.concurrent.Executors | |
import java.util.concurrent.TimeUnit | |
class DemoThreading extends Specification { | |
def "mocking with spock"() { | |
given: | |
Shared shared = Mock(Shared) | |
def numberOfThreads = 22 | |
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads) | |
(1..numberOfThreads).each { | |
executor.execute(new Threaded(shared: shared)) | |
} | |
when: | |
executor.shutdown() | |
executor.awaitTermination(20, TimeUnit.SECONDS) | |
then: | |
executor.terminated | |
numberOfThreads * shared.share() | |
} | |
def "mocking with coersion"() { | |
given: | |
def numberOfInvocations = 0 | |
Shared shared = [share: {synchronized(Shared){numberOfInvocations++}}] as Shared | |
def numberOfThreads = 22 | |
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads) | |
(1..numberOfThreads).each { | |
executor.execute(new Threaded(shared: shared)) | |
} | |
when: | |
executor.shutdown() | |
executor.awaitTermination(20, TimeUnit.SECONDS) | |
then: | |
executor.terminated | |
numberOfThreads * numberOfInvocations | |
} | |
} | |
class Shared { | |
def share() { | |
} | |
} | |
class Threaded implements Runnable { | |
Shared shared | |
@Override | |
void run() { | |
shared.share() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment