junit的问题No tests found matching
敲代码经常出现这个错误,自己有时候也不知道为什么,把遇到问题怎么解决总结一下吧
运行junit方法,报错:
TestMistake.getDocumentByName
initializationError(org.junit.runner.manipulation.Filter)
java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=getDocumentByName], {ExactMatcher:fDisplayName=getDocumentByName(TestMistake)], {LeadingIdentifierMatcher:fClassName=TestMistake,fLeadingIdentifier=getDocumentByName]] from org.junit.internal.requests.ClassRequest@23ab930d
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:40)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createFilteredTest(JUnit4TestLoader.java:77)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:68)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
1.代码一:使用了static关键字
@Test public void getDocumentByName() { Bson filters = Filters.eq("name", "qinqin"); FindIterable<Document> findIterable = dbCollection.find(filters); MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } System.out.println("查询成功"); } /** * 提供一个静态方法查询文档 * * @param name */ @Test public static List<Document> getDocumentByName(String name) { Bson filters = Filters.eq("name", name); FindIterable<Document> findIterable = dbCollection.find(filters); List<Document> list = findIterable.into(new ArrayList<Document>()); return list; }
自己误在static方法加上@Test,所以导致一直报这个错误。
去掉之后就运行正常了。
2.未导入org.hamcrest/hamcrest-core/1.3包,导入后正常
3.Junit4 测试方法必须用public void修饰
@Test private void test() { System.out.println(111); }
把private方法换成public运行良好
4.此处代码没有错,本类的其他测试代码有误
@Test public void testFields() { Field[] fields = User.class.getFields(); for (Field field : fields) { System.out.println(field); } } @Test protected void testDeclaredMethods() { Method[] dMethods = User.class.getDeclaredMethods(); for (Method method : dMethods) { System.out.println(method); } }
测试testFileds报错,改掉testDeclaredMethods前的protected为public就行了