junit单元测试报错:java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

发布时间 2023-04-01 14:59:05作者: 戒爱学Java

今天在复习的时候对对一些知识点进行巩固,用到了junit-4.12.jar,手动导入jar包,然后运行然后报错:java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing。刚开始我以为代码错了,看了看发现不是代码的问题,是导包的问题。然后查询了百度,发现了是版本的问题:
然后说换个低版本的就可以了,说换成4.10就可以了。测试了一下果然

查官网:JUnit now uses the latest version of Hamcrest. Thus, you can use all the available matchers and benefit from an improved assertThat which will now print the mismatch description from the matcher when an assertion fails.

junit.jar: Includes the Hamcrest classes. The simple all-in-one solution to get started quickly.Starting with version 4.11, Hamcrest is no longer included in this jar.
junit-dep.jar: Only includes the JUnit classes but not Hamcrest. Lets you use a different Hamcrest version.
注意黑色加下划线的部分 意思是4.11以上版本不在包含hamcrest。
所以现在有两个办法解决:

  1. junit版本降到4.10
  2. 导入hamcrest-core-1.3.jar