Coder Social home page Coder Social logo

catch-exception's Introduction


catch-exception 1.4.4

Catch and verify exceptions in a single line of code

Build Status Coverage Status Maven Central Apache 2

This is maintenance version of famous catch-exception library created by Rod Woo.

This library catches exceptions in a single line of code and makes them available for further analysis.

Usage

The most basic usage is:

import static com.googlecode.catchexception.CatchException.*;

// given: an empty list
List myList = new ArrayList();

// when: we try to get the first element of the list
// then: catch the exception if any is thrown
catchException(myList).get(1);

// then: we expect an IndexOutOfBoundsException
assert caughtException() instanceof IndexOutOfBoundsException;

The last both lines of code can be combined in a single line of code if you like:

verifyException(myList, IndexOutOfBoundsException.class).get(1);

More information about the usage you find in the Javadoc documentation.

BDD-like

If you prefer a BDD-like approach, you can use BDDCatchException for another code style:

import static com.googlecode.catchexception.apis.BDDCatchException.*;

// given: an empty list
List myList = new ArrayList();

// when: we try to get the first element of the list
when(myList).get(1);

// then: we expect an IndexOutOfBoundsException
then(caughtException())
        .isInstanceOf(IndexOutOfBoundsException.class)
        .hasMessage("Index: 1, Size: 0")
        .hasNoCause();

The assertions used here are part of AssertJ.

Hamcrest

If you prefer Hamcrest matchers to express assertions, you can use CatchExceptionHamcrestMatchers with the following code style:

import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;

// given: an empty list
List myList = new ArrayList();

// when: we try to get the first element of the list
catchException(myList).get(1);

// then: we expect an IndexOutOfBoundsException with message "Index: 1, Size: 0"
assertThat(caughtException(),
  allOf(
    instanceOf(IndexOutOfBoundsException.class),
    hasMessage("Index: 1, Size: 0"),
    hasNoCause()
  )
);

Catch constructor exceptions

Catch-exception does not provide an API to to catch exceptions that are thrown by constructors. Use try-catch-blocks instead. Alternatively, you can use the builder pattern if this makes sense anyway for your application:

import com.google.common.base.Supplier; // Google Guava

Supplier<Thing> builder = new Supplier<Thing>() {
   @Override
    public Thing get() {
       return new Thing("baddata");
   }
};
verifyException(builder).get();

Thanks to the community for the example.

Catch throwables

If you want to catch both throwables and exceptions have a look at the catch-throwable packages in javadoc. They provide the same API as the catch-exception packages but they belong to a different maven module.

JUnit4

If you want to handle expected exceptions, the documentation of catch-exception names some general reasons to prefer catch-exception in comparison to mechanisms that are provided by testing frameworks.

But some reasons that are specific to JUnit4 are outlined only here.

Collecting errors

If you want to combine the JUnit4's rules ExpectedException and ErrorCollector you will find out: this won't work.

Catch-exception instead can be easily combined with the error collecting rule:

@Rule
public ErrorCollector collector = new ErrorCollector();

@Test
public void testErrorCollectorWithExpectedException() {

    // collect first error
    collector.checkThat("a", equalTo("b"));

    // collect second error
    catchException(new ArrayList()).get(1);
    collector.checkThat(caughtException(), instanceOf(IllegalArgumentException.class));

    // collect third error
    collector.checkThat(1, equalTo(2));
}

Theories respectively parameterized tests

Sometimes you want to test for an optional exception in a parameterized test. JUnit4's ExpectedException rule does not help in this case. This is another use case where catch-exception comes in quite handy.

Download

Go to the Installation page to get the latest release. This page provides also the Maven coordinates, prerequisites, and information about dependencies to other libraries.

Future enhancements

This is maintenance project only - new features are not planned.

Read about catching exception with Java 8:

We have plan to release Catch-Exception 2 for Java 8 only with breaking API change.

Credits

Thanks to Rod Woo, the former author of catch-exception for creating this awesome library.

Thanks to Szczepan Faber who made some suggestions about a BDD-like syntax for catch-exception. Finally, his ideas triggered the enhancements that came with the 1.0.4 release.

Questions, Suggestions, Issues

Questions, suggestions and Issues are welcome and can be reported via Issues page of this project.

Please give me feedback of any kind. It is highly appreciated.

catch-exception's People

Contributors

mariuszs avatar rwoo avatar hazendaz avatar szpak avatar mkordas avatar

Watchers

chensong avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.