Let's connect
Let's connect

How to set up a Bazel testing configuration: The comprehensive guide for Scala and Java

Picture of Łukasz Wawrzyk, Tooling Expert

Łukasz Wawrzyk

Tooling Expert

15 minutes read

java

// example/src/test/java/com/example/ExampleTest.java

package com.example;
import org.junit.Test;
import org.junit.Assert;

public class ExampleTest {
	@Test public void example() {
		Assert.assertEquals(1, 1);
	}
}

console

# example/src/test/java/com/example/BUILD.bazel

java_test(
    name = "ExampleTest",
    srcs = ["ExampleTest.java"]
)

bash

bazel test //example/src/test/java/com/example:ExampleTest

java

// example/src/test/scala/com/example/ExampleTest.scala

package com.example

import org.scalatest.funsuite.AnyFunSuite

class ExampleTest extends AnyFunSuite {
  test("example") {
    assert(Set.empty.size == 0)
  }
}

console

# example/src/test/scala/com/example/BUILD.bazel

load("@io_bazel_rules_scala//scala:scala.bzl", "scala_test")

scala_test(
	name = "tests",
	srcs = ["ExampleTest.scala", "OtherExampleTest.scala"],
	deps = ["//example/src/main"]
)

bash

bazel test //example/src/test/scala/com/example:tests

Note: Unlike with java_test, you can use any name for the target. Also, Bazel will execute all tests specified in the srcs attribute.

console

# example/src/test/scala/com/example/BUILD.bazel

load("@io_bazel_rules_scala//scala:scala.bzl", "scala_test")

scala_test(
	name = "tests",
	srcs = ["ExampleTest.scala"],
	tags = ["unit"]
)

bash

$ bazel test //... --test_tag_filters=unit # run only unit tests
$ bazel test //... --test_tag_filters=unit,integration,lint,-external # run unit, integration and lint tests except those tagged as 'external'
$ bazel test //... --test_tag_filters=-stress # run all tests except the stress tests

bash

bazel test //... –test_tag_filters=lint

bash

bazel test //... –test_tag_filters=unit

bash

# setup environment here
bazel test //... –test_tag_filters=integration

bash

--test_timeout=30

bash

--test_timeout=5,60,180,600

console

# example/src/test/scala/com/example/BUILD.bazel

load("@io_bazel_rules_scala//scala:scala.bzl", "scala_test")

scala_test(
	name = "tests",
	srcs = ["ExampleTest.scala"],
	tags = ["unit"]
	size = "small"
	deps = ["//test-utils", "//example/src/main"]
)

console

# tools/build_rules/test_rules.bzl
load("@io_bazel_rules_scala//scala:scala.bzl", "scala_test")

def unit_test(**kwargs):
	if "size" not in kwargs:
		kwargs["size"] = "small"

	if "tags" not in kwargs:
		kwargs["tags"] = []
	if "unit" not in kwargs["tags"]:
		kwargs["tags"].append("unit")

	if "deps" not in kwargs:
		kwargs["deps"] = []
	if "//test-utils" not in kwargs["deps"]:
		kwargs["deps"].append("//test-utils")

	return scala_test(**kwargs)

console

# example/src/test/scala/com/example/BUILD.bazel

load("//tools/build_rules:test_rules.bzl", "unit_test")

unit_test(
	name = "tests",
	srcs = ["ExampleTest.scala"],
	deps = ["//example/src/main"]
)

console

# example/src/test/scala/com/example/BUILD.bazel

load("//tools/build_rules:test_rules.bzl", "unit_test")

unit_test(
	name = "tests",
	srcs = ["ExampleTest.scala"],
	deps = ["//example/src/main"],
	timeout = "moderate"
)

console

def default_target_name():
	_, _, target_name = native.package_name().rpartition("/")
	return target_name

console

# example/src/test/scala/com/example/BUILD.bazel

unit_test(
	srcs = ["ExampleTest.scala"],
	deps = ["//example/src/main"]
)

console

unit_test(
	srcs = ["ExampleTest.scala"],
	deps = ["//example/src/main"],
	flaky = True
)

console

build --sandbox_default_allow_network=false
test --sandbox_default_allow_network=false

console

// Path to the empty directory that Bazel prepared for this test target
var testWorkspace = Paths.get(System.getenv("TEST_TMPDIR"));
// Path to resources used in this test (as it is inside the jar file)
var resourcesPath = "/examples";
// Find URI of the resources directory inside the jar file
var uri = getClass().getResource(resourcesPath).toURI();
// Create a new file system for the jar file based on URI
var jarFs = FileSystems.newFileSystem(uri, new HashMap<>());
// Copy all files from the jar file to the test workspace
var paths = Files.list(jarFs.getPath(resourcesPath)).toList();
for (var source : paths) {
    // Note that Path objects determine the file system that they belong to
    var target = testWorkspace.resolve(source.getFileName().toString());
    Files.copy(source, target);
}
var copiedFiles = Files.list(testWorkspace).count();
Assert.assertEquals(copiedFiles, 3);

bash

$ bazel test //location/src/test --test_filter="*.InMemoryRepositorySpec" # tests with class named "InMemoryRepositorySpec"
$ bazel test //location/src/test --test_filter="*.oauth.*" # tests that contain "oauth" component in their package path

bash

$ bazel test //location/src/test --test_arg='-z' --test_arg='when popped' # run only tests with a name that contains 'when popped'

Liked the article?

Share it with others!

explore more on

Take the first step to a sustained competitive edge for your business

Get your free consultation

VirtusLab's work has met the mark several times over, and their latest project is no exception. The team is efficient, hard-working, and trustworthy. Customers can expect a proactive team that drives results.

Stephen Rooke
Stephen RookeDirector of Software Development @ Extreme Reach

VirtusLab's engineers are truly Strapi extensions experts. Their knowledge and expertise in the area of Strapi plugins gave us the opportunity to lift our multi-brand CMS implementation to a different level.

facile logo
Leonardo PoddaEngineering Manager @ Facile.it

VirtusLab has been an incredible partner since the early development of Scala 3, essential to a mature and stable Scala 3 ecosystem.

Martin_Odersky
Martin OderskyHead of Programming Research Group @ EPFL

The VirtusLab team's in-depth knowledge, understanding, and experience of technology have been invaluable to us in developing our product. The team is professional and delivers on time – we greatly appreciated this efficiency when working with them.

Michael_Grant
Michael GrantDirector of Development @ Cyber Sec Company