Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
928 views
in Technique[技术] by (71.8m points)

junit - How to configure Eclipse automatic static imports to prefer MatcherAssert.assertThat over Assert.assertThat?

We recently upgraded to JUnit 4.13 and my project was painted warning yellow because Assert.assertThat has now been deprecated in favour of MatcherAssert.assertThat.

Bulk changing my static imports is no big deal but I was hoping that going forward I could configure Eclipse to do the right thing in new code. But no matter what I do, the auto importer continues to pull in the deprecated Assert.assertThat instead of the MatcherAssert one.

Some things I've tried:

  • Add org.hamcrest.MatcherAssert.* to Preferences -> Java -> Editor -> Content Assist -> Favorites. Now I see MatcherAssert.assertThat as a quick fix suggestion when there is no import and I mouse over the code. But this doesn't affect the automatic imports at all.

    enter image description here

  • Add org.junit.Assert.assertThat to Preferences -> Java -> Appearance -> Type Filters. (I've also tried org.junit.Assert.* and even org.junit.*) This seems to have no effect on static imports. I can see the setting taking effect on regular imports when I experimented with org.junit.* but nothing on static imports.

So no matter what I do, when I hit save without explicitly pulling in MatcherAssert.assertThat, the auto import pulls Assert.assertThat instead.

Do you know if there is some way around this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A colleague of mine did some super sleuthing and discovered that as of Eclipse 2020-09, the Content Assist Favorites now influences automatic static imports:

Bug 283287 - [organize imports] Could use favorites for static imports

And since the Favorites configuration lets you specify specific class members, I was able to get around this problem by adding org.hamcrest.MatcherAssert.* and then changing my previous org.junit.Assert.* to a more specific set including all of the public members of that class except for assertThat.

In the end, I have something like this, which does the right thing both in the automatic imports and in the content assist quick-fix suggestions.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...