Remove dependency for unit test builds

I’m developing an Android module (I don’t think the Android part makes a difference, but just to note it), and it has its source, plus two more modules, let’s say :sdk:prod and :sdk:test, which expose the same API. :sdk:test should be used during unit tests and :sdk:prod in every other case. For this I have:

dependencies {
    ...
    compile project("sdk:prod")
    testCompile project("sdk:test")
}

And then I have this block:

configurations.all {
   configuration -> {
    if(configuration.name.contains("test")
        configuration.exclude module: ":sdk:prod"
   }
}

This works perfectly if I run my tests using the IDE, but if I run

./gradlew testDebug

the module in use is “:sdk:prod”.

I have tried some other ways I found on the internet but I never got it to work. What is the way?