Testing with Google Truth


Truth makes your test assertions and failure messages more readable. Similar to AssertJ, it natively supports many JDK and Guava types, and it is extensible to others.

  • IDE auto complete, faster to type
  • actual is always on the left-hand side, the expected value is always on the right-hand side.
    • So readers knows what we are testing.
  • Detailed, meaningful, and easy-to-read error messages
  • Hamcrest doesn’t autocomplete statements in IDEs.
  • containsExactlyElementsIn
  • Use containsExactly insteadof isEqualTo(ImmutableMap.of(k1,v1,k2,v2))
  • containsExactly, containsAtLeast, etc are order-independent assertions; chain .inOrder() to check the order.
  • Use assertWithMessage to customize error message.
  • Writing your own custom subject

Truth Extensions

  • Truth8 for java8 types such as java.util.Optional
  • ProtoTruth for Message style protocol buffers and lite versions
  • Re2jSubjects for use with the RE2J library

Test Exception

  • Don’t use @Rule ExpectedException
    • Any statements after the throwing call will never be executed.
  • Don’t use @Test(expected = ExceptionExpectation.class)
    • The test passes if any statement throws ExceptionExpectation.
  • If the method should throw FooException, test for FooException, not generic RuntimeException or its parent class.
  • perform additional assertions on the exception: hasMessageThat etc if appropriate.
  • Use Throwables.getCauseAs instead of (MyExpectedCause) ex.getCause()
    • Throwables.getCauseAs includes the original exception in the failure if the cause is not of the expected type

Resource

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)