JUnit报错:未找到org.example.AppTest中的测试用例,求解决
解决JUnit测试类"No tests found"问题
问题场景
使用IntelliJ、Apache Maven 3.8、Selenium Server进行Web自动化测试,JDK版本为11。创建了homepage页面对象类和AppTest测试类,运行测试时抛出如下错误:
junit.framework.AssertionFailedError: No tests found in org.example.AppTest at junit.framework.Assert.fail(Assert.java:57) at junit.framework.TestCase.fail(TestCase.java:223) at junit.framework.TestSuite$1.runTest(TestSuite.java:96)
问题原因
AppTest类同时混用了JUnit 3和JUnit 4的API:
- 继承了JUnit 3的
junit.framework.TestCase类 - 使用了JUnit 4的
@Test注解
JUnit 3通过方法名以test开头识别测试方法,而JUnit 4依赖@Test注解,混合使用会导致测试运行器无法正确识别测试方法,从而抛出"No tests found"错误。
解决方案
方案1:切换为纯JUnit 4注解体系(推荐)
移除对TestCase的继承,使用JUnit 4的完整注解体系,同时调整断言方式为JUnit 4的API:
修改后的AppTest.java:
package org.example; import org.example.page.homepage; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import static org.junit.Assert.assertEquals; /** * Unit test for simple App. */ public class AppTest { WebDriver webDriver; @Before public void initiate(){ ChromeOptions options = new ChromeOptions(); options.addArguments("start-maximized"); // 参数改为小写规范写法 webDriver = new ChromeDriver(options); } @Test public void openHomePage() throws InterruptedException { homepage homepage = new homepage(webDriver); webDriver.get("https://www.seleniumeasy.com/"); homepage.assertOpenHomePage(); } @After public void tearDown(){ // 测试结束后关闭浏览器,避免资源泄漏 if(webDriver != null){ webDriver.quit(); } } }
同时建议把homepage.java中的断言也切换为JUnit 4的API:
package org.example.page; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import static org.junit.Assert.assertEquals; public class homepage { private WebDriver webDriver; public homepage(WebDriver driver) { this.webDriver = driver; } public void assertOpenHomePage() throws InterruptedException { Thread.sleep(3000); String welcomeHomePage = webDriver.findElement(By.xpath ("//strong[contains(text(),'Selenium Easy!')]")).getText(); assertEquals("Selenium Easy!", welcomeHomePage); } }
方案2:保留JUnit 3风格
如果要继续使用JUnit 3的TestCase,则需要:
- 移除
@Test注解 - 测试方法名改为以
test开头
修改后的测试方法示例:
// 移除@Test注解 public void testOpenHomePage() throws InterruptedException { homepage homepage = new homepage(webDriver); webDriver.get("https://www.seleniumeasy.com/"); homepage.assertOpenHomePage(); }
额外建议
- Maven依赖中确保JUnit版本统一,避免同时引入JUnit 3和JUnit 4的依赖
- 尽量避免使用
Thread.sleep(),改用Selenium的显式等待(WebDriverWait)来提升测试稳定性
内容的提问来源于stack exchange,提问作者helm.proyek_
相关产品推荐
相关产品推荐

