0

I am currently using JUnit 4.x with AssertJ. I would like to ensure that no usages of Hamcrest sneak it. However, Hamcrest Core is a required dependency at runtime for JUnit, see Junit issue #1429: A Exception for junit4.12 about org/hamcrest/SelfDescribing #1429 , so excluding the dependency from the pom.xml outright or adjusting the maven-surefire-plugin classpath would not work.

What I am looking for is a way to adjust the test compiler classpath, but I did not find such an option in the maven-compiler-plugin.

How can I make sure that my tests do not use Hamcrest assertions? I would like to enforce this at build time, using Maven.

Robert Munteanu
  • 67,031
  • 36
  • 206
  • 278

2 Answers2

4

Based on the thing that you can't exclude the transitive dependency of Hamcrest from JUnit 4 cause it's used by JUnit itself there only a few options:

  • Migrate to JUnit Jupiter (aka JUnit 5) and remove hamcrest completely and ban dependency via maven-enforcer-rule
  • Using Arch Unit to prevent the usage
  • Create SonarQube Rule
  • As Robert already suggest Checkstyle rule..
  • Also you could think of writing a custom enforcer rule?
  • Another option could be to use JQAssistant
khmarbaise
  • 92,914
  • 28
  • 189
  • 235
2

Maven is missing a scope. It has test, but it is used for both test-compile and test-runtime. Ideally you would have set the scope of hamcrest to test-runtime. JUnit 5 already made clear Maven is missing this scope, but it is hard to introduce a new scope.

So I think the best option you have is the Checkstyle Rule IllegalType or similar rules to prevent it.

Robert Scholte
  • 11,889
  • 2
  • 35
  • 44
  • Would the test-runtime not allow the usage of Hamcrest in your test code? If I correctly understand it would not which will not solve the problem. Maybe we should think about an enforcer rule to check for imports in code? – khmarbaise Jan 31 '20 at 09:12
  • Suppose you could change the scope of hamcrest to the non existing test-runtime, then it won't be on the classpath while compiling your tests. Hence if you are using hamcrest classes, the build would fail. I don't like the idea of enforcer-rule, because you need to analyze the (source)code. There are already frameworks that can do that, let's not reinvent that wheel. – Robert Scholte Jan 31 '20 at 09:21