Preventing partial publishing in multi project releases with Maven

Is it possible to ensure all modules in a multi module build are built and tests have run before the publishing to Maven?

I am struggling to see how this can be done, I have tried this.

project.gradle.taskGraph.whenReady {
    project.tasks.matching { it.getName().startsWith('publishMaven') }.each { task ->
        task.dependsOn {
            rootProject.subprojects.collect {
                it.tasks.getByName 'test'
            }
        }
    }
}