29

I would like to be able to print in the logs a message for which intellij idea would present a nice way of comparing two objects (strings). This happens automatically for the error message logged by a failed junit assert:

assertEquals("some\nString", "another\nString");

=>
org.junit.ComparisonFailure:  <Click to see difference>
    at org.junit.Assert.assertEquals(Assert.java:123)
    at org.junit.Assert.assertEquals(Assert.java:145)
    at com.something.DummyTest.testDummy(DummyTest.java:89)

The <Click to see difference> entry is actually displayed as a link in the output window of the Intellij Idea. When you click on the link, a compare window opens which shows the two values (just like you would compare two files).

Simply throwing an exception is not acceptable because I would like to log multiple objects to compare. I already tried logging a text, but I wasn't able to convince idea to compare the two texts.

botismarius
  • 2,977
  • 2
  • 30
  • 29

2 Answers2

39

IntelliJ IDEA is using the hardcoded regular expression. If the text matches the pattern, it will suggest to click to view the difference.

The pattern is:

expected:<bla-blah> but was:<blah-blah-blah>

Output should match the format of assertEquals or assertThat.

The exact patterns are somewhat scattered around the code in IDEA, but some are e.g. here.

sschuberth
  • 28,386
  • 6
  • 101
  • 146
CrazyCoder
  • 389,263
  • 172
  • 990
  • 904
  • 2
    I think that both values need to be sourrunded by quotes as well. – yankee Mar 28 '15 at 22:52
  • @yankee Actually, when looking at the regex pattern, that does not seem to be necessary. – sschuberth Jul 10 '17 at 08:08
  • No quotes necessary, but I had to add a space after the : for this to work. So: `expected: but was: ` – Gustav Karlsson Jan 09 '18 at 08:05
  • 2
    Should this still work? I think I found [the new patterns](https://github.com/JetBrains/intellij-community/blob/ea2b2d7677106b8d7cdd26d499e5ddd57c73f7f5/plugins/junit_rt/src/com/intellij/junit4/ExpectedPatterns.java#L34) but I don't see any diff buttons. Do I also need to have a crash and/or run it via JUnit to see the diff links? – phant0m Oct 23 '18 at 09:21
  • @phant0m yes, it has to be an assertion in JUnit tests. – CrazyCoder Oct 23 '18 at 09:22
  • @CrazyCoder thanks, so multiple diffs in one output isn't possible then? – phant0m Oct 23 '18 at 10:33
4

I had the same Problem and found the solution in https://github.com/joel-costigliola/assertj-core/issues/1364#issuecomment-440800958

You should throw an org.junit.ComparisonFailure. Then IntelliJ will display the <Click to see difference>

Sim0rn
  • 632
  • 1
  • 6
  • 9