Scala命令行编译ScalaTest测试代码报错:object scalatest is not a member of package org
Hey there! I get that working with Scala directly via the binary package (no sbt) can feel a bit manual, but let's get your ScalaTest tests up and running. The error object scalatest is not a member of package org happens because your compiler can't find the ScalaTest libraries in its classpath—even if you downloaded the JAR, you need to explicitly tell scalac where to look for it (plus its dependencies). Here's how to fix it step by step:
1. Make Sure You Have the Right JARs
ScalaTest 3.2.x is fully compatible with Scala 2.13.4, so grab these two required JARs:
scalatest-funsuite_2.13-[version].jar(the FunSuite library you're using for tests)scalactic_2.13-[version].jar(a mandatory dependency for ScalaTest—you can't run ScalaTest without this)
Save both to a dedicated folder (like lib in your project directory) to keep things organized.
2. Compile Your Code with the Correct Classpath
When compiling your test file, you need to include three things in the classpath:
- The path to the ScalaTest/Scalactic JARs
- The path to your
Factorial.scalafile (so the test can access thefactmethod)
Assuming:
- Your
Factorial.scalaandFactTest.scalaare in the current directory - The JARs are stored in a
libsubfolder
Run this command in Command Prompt:
scalac -cp "lib\scalatest-funsuite_2.13-3.2.15.jar;lib\scalactic_2.13-3.2.15.jar;." Factorial.scala FactTest.scala
- The
;separates paths on Windows (use:on Linux/macOS) - The
.tells the compiler to include the current directory (where your source files live)
3. Run the Tests
Once compiled, execute the tests with the same classpath using this command:
scala -cp "lib\scalatest-funsuite_2.13-3.2.15.jar;lib\scalactic_2.13-3.2.15.jar;." org.scalatest.run FactTest
This will run your test suite and show you the full results—including that intentionally failing test you wrote!
Common Mistakes to Avoid
- Forgetting the Scalactic JAR: ScalaTest depends on this library, so omitting it will still cause errors even if you have the ScalaTest JAR.
- Incorrect Path Separator: Windows uses
;instead of:for classpath entries—mixing these up is a super common pitfall. - Not Including Your Own Code: If you don't add
.(current directory) to the classpath, the compiler won't find yourFactorialclass, leading to another error about missingFactorial.fact.
Bonus: Simplify with a Batch Script
To avoid typing the long classpath every time, create a .bat file (e.g., run-tests.bat) in your project directory with these lines:
@echo off scalac -cp "lib\scalatest-funsuite_2.13-3.2.15.jar;lib\scalactic_2.13-3.2.15.jar;." Factorial.scala FactTest.scala scala -cp "lib\scalatest-funsuite_2.13-3.2.15.jar;lib\scalactic_2.13-3.2.15.jar;." org.scalatest.run FactTest
Now you just double-click the script to compile and run your tests in one go!
内容的提问来源于stack exchange,提问作者Ben Solo

