~ read.

How to run Java TestNG tests with sbt

Recently i published my first version of fabricator library to central maven repository and bintray . While i was checking published library, i found out that in Java projects there are some minor discrepancies and problems with methods naming and default arguments of methods parameters, which work fine in scala project. To avoid this problems in the future, i decided to add Java tests to my project and make sbt run both java and scala tests. While sbt automatically runs tests from the usual Scala test frameworks (specs, ScalaCheck, ScalaTest) it won’t run your Java tests per defaut.

Building Java sources with sbt is no problem, though. It comes for free, given the following project structure:

src  
  |
  |-- main
  |      |
  |      |-- java
  |      |
  |      |-- scala
  |
  |-- test
  |      |
  |      |-- java
  |      |
  |      |-- scala

Note: This is the default project structure expected by SBT, which is configurable, though.

SBT will pick up Java sources and compile them, but won't run them by default. To make it "see" Java tests, you need to make a small modification in your project. Let's assume that :

  • SBT version is >= 0.1
  • You use ScalaTest or TestNG for Scala tests
  • You use TestNG for Java tests

You need to do following :

  1. In test/java you need to create a package, something like : my.java.tests
  2. Create JavaBaseTest class that will extend TestNG
  3. In test/scala create a new JavaTests Scala class with next code :
package my.scala.tests

import my.java.tests.JavaBaseTest  
import org.scalatest.testng.{TestNGSuiteLike, TestNGSuite}

class JavaTests extends JavaBaseTest with TestNGSuiteLike {  
}

That's it. Now when you will run sbt test it will execute both Java and Scala test. New java tests you can just extend from JavaBaseTest and continue with them.

comments powered by Disqus
comments powered by Disqus