NetBeans搭配Maven进行JUnit测试:我的配置哪里出错了?
解决方案与经验总结
- 修正了命名规范以适配Maven/JUnit的识别规则:需命名为
IngredientTest,而非Ingredient_Test。 - 删除了runner类(测试无需该类),此前一直不清楚无main方法时如何运行测试查看结果。
- 解决方案:在NetBeans中从原类(Ingredient)而非测试类(IngredientTest)运行测试文件。在原类(Ingredient)的代码体中右键,点击「Test file」,运行完成后会弹出输出和测试结果窗口。
问题根源为混用了JUnit 4与JUnit 5的API。
原需求与问题说明
需求
在NetBeans中为现有类编写并运行JUnit测试。
遇到的错误
Ingredient_Test中的@Before注解报“Cannot find symbol”错误Ingredient_TestRunner中的导入语句报“Package <> does not exist”错误
运行环境
- 产品版本:Apache NetBeans IDE 12.4
- Java版本:16;Java HotSpot(TM) 64-Bit Server VM 16+36-2231
- 运行时:Java(TM) SE Runtime Environment 16+36-2231
- 项目默认使用Maven构建,未修改过Maven XML配置文件,打算完成单元测试学习后再研究该部分。
背景说明
此前手写了临时测试类与src文件放在一起,打算“之后”再做规范的JUnit测试,现在已经写了好几个类,意识到应该尽早开展规范测试,目前正在将临时测试类改写为符合规范的JUnit测试类。
相关代码
业务类:Ingredient
package com.riverrat.recipebook; public class Ingredient{ String name; String amount; String unit; String form; // do stuff }
初始测试类:Ingredient_Test
package com.riverrat.recipebook; import com.riverrat.recipebook.Ingredient; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; public class Ingredient_Test { @Before public void buildIngredients(){ Ingredient beans = new Ingredient("beans"); Ingredient onions = new Ingredient("onions", "2", "cups", "chopped coarsley"); Ingredient water = new Ingredient("water", "3", "oz"); Ingredient bacon = new Ingredient("bacon", "", "slab"); } @Test public void testNames(){ assertEquals("beans", beans.name); } }
初始测试运行类:Ingredient_TestRunner
package com.riverrat.recipebook; import org.JUnit.runner.JUnitCore; import org.JUnit.runner.Result; import org.JUnit.runner.notification.Failure; public class Ingredient_TestRunner { public static void main(String[] args){ Result result = JUnitCore.runclasses(IngredientTest); for (Failure failure : result.getFailure()){ System.out.println(failure.toString()); } System.out.println("Result " + result.wasSuccessful()); } }
内容的提问来源于stack exchange,提问作者RiverRat
相关产品推荐
相关产品推荐

