Coder Social home page Coder Social logo

catch-exception's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

catch-exception's Issues

Catch-Exception 2.0 Ideas

Full integration with AssertJ 2.0

import static com.googlecode.catchexception.apis.BDDCatchException.*;
import static org.assertj.core.api.BDDAssertions.then;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class AssTest {

    @Test
    public void testName() throws Exception {
        // given an empty list
        List myList = new ArrayList();

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

        then(caughtException())
                .isInstanceOf(IndexOutOfBoundsException.class);
    }

}
  • No proxing,
  • Java8 and AssertJ API only,
  • without conflict with BDDAssertions.then in single class

Catch exceptions directly in the expected type

I have a custom BusinessRuleException with an extra method getCode(). With catch-exception 1.4.2, my tests look like this (didn't find a better way):

when(service).doSomething();

then(caughtException()).isInstanceOf(BusinessRuleException.class);
BusinessRuleException e = (BusinessRuleException) caughtException();
then(e.getCode()).isEqualTo(MY_ERROR_CODE);

This has 2 issues:

  • on the third line, where caughtException() is called, IntelliJ IDEA 14.1 warns that I get an exception which is not rethrown
  • not fluent

I would expect to be able to write something like (or some variation with better API and taking into account what's required to avoid unchecked casts and whatnot):

when(service).doSomething();

then(caughtException())
    .isInstanceOfAndGet(BusinessRuleException.class)
    .getCode().isEqualTo(MY_ERROR_CODE);

NullPointerExceptions after catchException()

Hi,
i used the "Hamcrest" way of catch-exception and ran into some strange errors.
Some of my objects simply dissappear after the catchException Line, which leads to NullPointer Exception.
One NullpointerException happend during a call to one of the mocked Objects and another happend to a static Instance of ThreadLocal

@Test
public void foo() {
        FirstMock firstMock = mock(FirstMock.class);
        HttpURLConnection connection = mock(HttpURLConnection.class);
        OutputStreamerEventbus eventbus = mock(OutputStreamerEventbus.class);
        subject.setEventbus(eventbus); //Here Eventbus is an object
        doReturn(connection).when(subject).createConnection(any(URL.class));
        when(connection.getResponseCode()).thenReturn(httpCode);

        catchException(subject).doStuff(new URL(siteUrl), firstMock);

        assertThat(caughtException(),is(instanceOf(FunctionalException.class)));
        ArgumentCaptor<Failure> failure = ArgumentCaptor.forClass(Failure.class);
        verify(eventbus).put(failure.capture());
        assertThat(failure.getValue().getCode(),is(equalTo(failureCode)));
}

Inside of doStuff a call to ThreadLocal get() method leads to NullPointerException. After replacing the call with a in value the next error.
Insicde of doStuff(...) Eventbus reference is null.

This following works:

@Test
public void foo() {
        FirstMock firstMock = mock(FirstMock.class);
        HttpURLConnection connection = mock(HttpURLConnection.class);
        OutputStreamerEventbus eventbus = mock(OutputStreamerEventbus.class);
        subject.setEventbus(eventbus); //Here Eventbus is an object
        doReturn(connection).when(subject).createConnection(any(URL.class));
        when(connection.getResponseCode()).thenReturn(httpCode);

        try {
            subject.doStuff(new URL(siteUrl), firstMock);

            fail("Expected FunctionalException");
        }
        catch(FunctionalException ex) {
            assertThat(ex.getCode(),is(equalTo(exceptionCode)));
        }
        ArgumentCaptor<Failure> failure = ArgumentCaptor.forClass(Failure.class);
        verify(eventbus).put(failure.capture());
        assertThat(failure.getValue().getCode(),is(equalTo(failureCode)));
   }

BDD-like assertions don't work with Java 8

The example code below:

import static com.googlecode.catchexception.CatchException.*;
import static org.assertj.core.api.BDDAssertions.then;

// 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();

is not compiling, because the method then (org.assertj.core.api.BDDAssertions.then) cannot resolve the argument of type java.lang.Exception (at least Intellij IDEA 14 says so).

Java 8 compiler says:

error: reference to then is ambiguous
then(caughtException())
^
both method <T#1>then(Iterator<T#1>) in BDDAssertions and method <T#2>then(Iterable<T#2>) in BDDAssertions match
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>then(Iterator<T#1>)
T#2 extends Object declared in method <T#2>then(Iterable<T#2>)

Consider making repo read only (archived now)

Given last commit in 2020, then in 2022, I started releasing from the fork to take over maintenance, and finally a year or more later still no activity here, I've started more formally doing long overdue automation and don't see my code efforts coming back up to this original repo. Marking it archived makes sense for a number of reasons beyond what I mentioned especially considering original direction here had stated at one point that junit 5 would make this obsolete. It doesn't entirely but focus I'm sure is elsewhere. Most of what I'm doing post today anyways makes it far harder to just accept back up and its already 4 years since release here. Doing so will help those trying to use know where to use it from.

https://github.com/hazendaz/catch-exception is the fork I've been running it from and branch is 'master-fork'. My last efforts to bring code in where on master and never got merged and I closed some time ago. While I know github can shift ownership, that would cause more work so I think this is the right path. As it were, all credit and licensing remains as it were and much appreciated for this great project.

Better error when mocking a final class

When a user accidentally applies CatchException to an object whose class is final, CatchException should show a better error message along the lines of "Unable to mock final class`, so that the user has a better idea of why the ClassCastException occurs.

Handling runtime exceptions

Hello everyone,
Just an offer: how about adding handling runtime exceptions? I'm working on E2E tests where it can be helpful.
Thanks!

Fails to forward .call() method properly

When I try to use catch-exception to forward a .call() message to an Autocloseable, I get a runtime error:

java.lang.ClassCastException: com.googlecode.catchexception.internal.InterfaceOnlyProxy$$EnhancerByCGLIB$$5d8fd3e4 cannot be cast to MyClass

Other method names forward correctly. Unfortunately, my use case calls for implementing Callable, which means I need to be able to name the method call.

Better integration with AssertJ 2.0

What do you think about this usage:

@Test
public void testName() throws Exception {
    // given an empty list
    List myList = new ArrayList();

    // we are recording exception here
    when(myList).get(1);

    // and then rethrowing for verification
    thenThrownBy(CatchException::rethrow) 
            .isInstanceOf(IndexOutOfBoundsException.class);
}

This allows migrating existing catch-exception code to Java 8 and AssertJ with minimal effort.

Which Maven dependency should I use?

The catch-exception libs on Maven Central look really out of date compared to the development on this catch-exception git repo. Which org, artifact name, and version should we use? Google, EU?

VerifyError on verifyException

I´m getting this VerifyError when running my test.

The simplified class under test::

public class Action {
public final String payload;
public JSONObject getPayloadJSONObject() throws JSONException {
        return new JSONObject(payload);
    }
}

The test:

Action action = new Action();
action.payload = "[\"foo\", \"bar\"]";
verifyException(arrayPayloadAction, JSONException.class).getPayloadJSONObject();

my stacktrace:


java.lang.VerifyError: org/mockito/cglib/core/ReflectUtils
at org.mockito.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:167)
at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)
at org.mockito.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145)
at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:117)
at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:109)
at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:105)
at org.mockito.cglib.proxy.Enhancer.<clinit>(Enhancer.java:70)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxyClass(ClassImposterizer.java:96)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:60)
at com.googlecode.catchexception.internal.SubclassProxyFactory.createProxy(SubclassProxyFactory.java:59)
at com.googlecode.catchexception.CatchException.processException(CatchException.java:390)
at com.googlecode.catchexception.CatchException.verifyException(CatchException.java:300)
at com.sensorberg.sdk.action.TheActionShould.test_reveal_the_real_type_of_the_payload(TheActionShould.java:22)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1701)

running gradle with these dependencies:

dependencies {
    androidTestCompile 'com.squareup:fest-android:1.0.8'
    androidTestCompile "org.mockito:mockito-core:1.9.5"
    androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
    androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0'

    androidTestCompile 'org.apache.commons:commons-io:1.3.2'
    androidTestCompile 'eu.codearte.catch-exception:catch-exception:1.3.4'

    compile 'com.loopj.android:android-async-http:1.4.5'
}

Fix compatibility issue with Mockito 1.10.8

[ERROR] src/main/java/com/googlecode/catchexception/internal/SubclassProxyFactory.java:[46,40] cannot find symbol
[ERROR] symbol:   method canImposterise(java.lang.Class<capture#1 of ?>)
[ERROR] location: variable INSTANCE of type org.mockito.internal.creation.jmock.ClassImposterizer

Mockito spies call real methods instead of stubs with catchException

Hi Everyone,

catch-exception is cool, but I think I encountered a potential issue. Sorry if this is the expected behaviour or if this was reported already. If you're aware of a workaround, please let me know. :)

I'm using version 1.4.4, Mockito and Hamcrest. I found out that real methods of a spy are called instead of stubs when using catchException when I explicitly stub the method. Consider the example below.

The class I'm trying to test:

public class SomeClass {

    public Object method(String text) throws Exception {
        Object object = otherMethod(text);

        if (object == null) {
            throw new Exception();
        }

        return object;
    }

    public Object otherMethod(String text) {
        return "some other text";
    }
}

The test below fails as the real otherMethod gets called during the test.

@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {

    @Spy
    private SomeClass someClass = new SomeClass();

    @Test
    public void testMethod() throws Exception {
        // Stubbing otherMethod to return null
        doReturn(null).when(someClass).otherMethod(any());

        catchException(someClass).method("some text");

        assertThat(caughtException(), instanceOf(Exception.class));
    }
}

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.