[Guava] Preconditions

Preconditions should be ideal for situations, where there is no specific business exceptions for checking arguments and performance is not an issue.

JavaDoc:

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/base/Preconditions.html

Example:

   /**
    * Returns the positive square root of the given value.
    *
    * @throws IllegalArgumentException if the value is negative
    */
   public static double sqrt(double value) {
     Preconditions.checkArgument(value >= 0.0, "negative value: %s", value);
     // calculate the square root
   }

 

Here is more about checking conditions:

https://github.com/google/guava/wiki/ConditionalFailuresExplained

Using Spock for testing code – getting started with syntax (1)

Getting started guide:
http://spockframework.org/spock/docs/1.0/spock_primer.html

Interesting things:

  • cool way to verify throwing exceptions:
    then: 
    EmptyStackException e = thrown() e.cause == null
  • instead of writing, “when-then”, just use “except”:
    expect:
    Math.max(1, 2) == 2
  • to parameterize test with different data, use “where” syntax:
    def "computing the maximum of two numbers"() {
    expect:
    Math.max(a, b) == c
    
    where:
    a << [5, 3]
    b << [1, 9]
    c << [5, 9]
    }
  • in helper method use “assert” keyword:
    assert pc.vendor == "Sunny"