java.lang.UnsupportedOperationException shown when trying to Assert some values

I am using the below code to assert text in my test script. But its giving UnsupportedOperationException error every time it hits this code.

public static void verifyEquals(Object actual, Object expected) {
        try {
            Assert.assertEquals(actual, expected);
        } catch(Throwable e) {
            addVerificationFailure(e);
        }
    }

    public static List<Throwable> getVerificationFailures() {
        List verificationFailures = verificationFailuresMap.get(Reporter.getCurrentTestResult());
        return verificationFailures == null ? new ArrayList() : verificationFailures;
    }

    private static void addVerificationFailure(Throwable e) {
        StackTraceElement[] error = e.getStackTrace();
        List<StackTraceElement> errors = Arrays.asList(error);
        verificationFailuresMap.put(Reporter.getCurrentTestResult(), errors);
        List verificationFailures = getVerificationFailures();
        verificationFailuresMap.put(Reporter.getCurrentTestResult(), verificationFailures);
        verificationFailures.add(e);
    }

Can anyone help me on this?

Jon Skeet
people
quotationmark

This is the problem:

List verificationFailures = getVerificationFailures();
verificationFailuresMap.put(Reporter.getCurrentTestResult(), verificationFailures);
verificationFailures.add(e);

You're calling List.add on the result of Arrays.asList. You can't do that, as the result of Arrays.asList is a view onto the array - you can't add or remove elements.

Additionally - erasure aside - that list is a List<StackTraceElement> - it's backed by a StackTraceElement[]. What does it even mean to add a Throwable to that?

It's simpler to see the problem if you remove the code which puts the list into the map and then fetches it back again before adding:

private static void addVerificationFailure(Throwable e) {
    StackTraceElement[] error = e.getStackTrace();
    List<StackTraceElement> errors = Arrays.asList(error);
    verificationFailuresMap.put(Reporter.getCurrentTestResult(), errors);
    errors.add(e);
}

This will now fail at compile time due to trying to add a Throwable to a List<StackTraceElement>. But even if you were trying to add a StackTraceElement it would still fail due to Arrays.asList not supporting add.

It's really unclear what you're trying to do, but you need to rethink it...

people

See more on this question at Stackoverflow