I have a test class defined in src/handlers/MyHttpHandlerTest.java
(sorry, I know it's best practice to put tests in a tests
directory).
Here is my src/handlers/BUILD
file:
java_test(
name = "MyHttpHandlerTest",
srcs = [
"MyHttpHandler.java",
"MyHttpHandlerTest.java",
],
deps = [
"//:java_test_deps",
"//src/messages",
],
)
My test class is defined in src/handlers/MyHttpHandlerTest.java
as follows (It currently doesn't assert anything -- I'm just trying to test out my installation of junit and Mockito):
package src.handlers;
import com.sun.net.httpserver.HttpExchange;
import src.messages.Message;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
@ExtendWith(MockitoExtension.class)
public class MyHttpHandlerTest {
@Mock
Message message;
@Mock
HttpExchange exchange;
@Test
public void testGetMessage() throws IOException {
MyHttpHandler handler = new MyHttpHandler();
when(message.getMessage()).thenReturn("Hello world!");
handler.setMessage(message);
handler.handle(exchange);
}
}
When I run bazel test //src/handlers:MyHttpHandlerTest
, it successfully compiles the source files, but then returns the error:
Class not found: [handlers.MyHttpHandlerTest]
Why can't bazel find this class?
CodePudding user response:
Bazel guesses that the the root of the Java package hierarchy is the src
folder and therefore tries to load handlers.MyHttpHandlerTest
. So, either change the package to actually be handlers
or override Bazel's heuristic with the test_class
attribute:
java_test(
name = "MyHttpHandlerTest",
srcs = [
"MyHttpHandler.java",
"MyHttpHandlerTest.java",
],
deps = [
"//:java_test_deps",
"//src/messages",
],
test_class = "src.handlers.MyHttpHandlerTest",
)