Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 /*
  * Copyright (c) 2015, nwillc@gmail.com
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
  * copyright notice and this permission notice appear in all copies.
  *
  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
package com.github.nwillc.contracts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown;

This contract checks:
  • compareTo with null argument throws NullPointerException
  • compareTo with argument that can't be cast to correct type throws ClassCastException
  • returns 0 on equality
  • returns less then zero on less then
  • returns greater then zero on greater
@SuppressWarnings("unchecked")
public abstract class ComparableContract {
	protected abstract Comparable getValue();
	protected abstract Comparable getEqualToValue();
	protected abstract Comparable getLessThanValue();
	protected abstract Comparable getGreaterThanValue();
	public void shouldThrowExceptionForNull() throws Exception {
		final Comparable value = getValue();
		try {
			value.compareTo(null);
catch (NullPointerException e) {}
	}
	public void shouldThrowExceptionForBadCast() throws Exception {
		final Comparable value = getValue();
		try {
			value.compareTo(new Object());
catch (ClassCastException e) {}
	}
	public void shouldReturnZeroOnEquality() throws Exception {
		final Comparable value = getValue();
		final Comparable equal = getEqualToValue();
		assertThat(value.compareTo(equal)).isEqualTo(0);
	}
	public void shouldReturnNegativeOnLessThan() throws Exception {
		final Comparable value = getValue();
		final Comparable lessThan = getGreaterThanValue();
		assertThat(lessThan).isNotNull();
		assertThat(value.compareTo(lessThan)).isLessThan(0);
	}
	public void shouldReturnPositiveOnGreaterThan() throws Exception {
		final Comparable value = getValue();
		final Comparable greaterThan = getLessThanValue();
		assertThat(greaterThan).isNotNull();
		assertThat(value.compareTo(greaterThan)).isGreaterThan(0);
	}
New to GrepCode? Check out our FAQ X