Question

For one of my projects, I am attempting to get rid of string-based unit testing; one class I have as a target right now is ParsingResult.

I have successfully converted another class with a custom AssertJ assertion, so I am now trying to write a custom assertion class for my next "victim". The class goes like this:

public final class ParsingResultAssert<V>
    extends AbstractAssert<ParsingResultAssert<V>, ParsingResult<V>>
{
    private ParsingResultAssert(final ParsingResult<V> actual)
    {
        super(actual, ParsingResult.class);
    }

    public static <E> ParsingResultAssert<E> assertResult(
        final ParsingResult<E> actual)
    {
        return new ParsingResultAssert<E>(actual);
    }
}

In order to test it, I though I'd try and insert it in a test file I ultimately want to remove:

public abstract class ParboiledTest<V> {

    public class TestResult<V> {
        public final ParsingResult<V> result;
        private final ParsingResultAssert<V> resultAssert;

        public TestResult(ParsingResult<V> result) {
            this.result = result;
            resultAssert = ParsingResultAssert.assertResult(result); // HERE
        }
    // rest is not relevant

At the line marked HERE it fails with this:

java.lang.ClassCastException
    at java.lang.Class.cast(Class.java:2999)
    at org.assertj.core.api.AbstractAssert.<init>(AbstractAssert.java:63)
    at com.github.parboiled1.grappa.assertions.ParsingResultAssert.<init>(ParsingResultAssert.java:13)
    at com.github.parboiled1.grappa.assertions.ParsingResultAssert.assertResult(ParsingResultAssert.java:19)
    at org.parboiled.test.ParboiledTest$TestResult.<init>(ParboiledTest.java:42)
    [...]

The last line of the stacktrace is this line:

            resultAssert = ParsingResultAssert.assertResult(result);

And org.assertj.core.api.AbstractAssert.<init>(AbstractAssert.java:63) is this:

  // we prefer not to use Class<? extends S> selfType because it would force inherited
  // constructor to cast with a compiler warning
  // let's keep compiler warning internal (when we can) and not expose them to our end users.
  @SuppressWarnings("unchecked")
  protected AbstractAssert(A actual, Class<?> selfType) {
    myself = (S) selfType.cast(this); // <-- THIS ONE
    this.actual = actual;
    info = new WritableAssertionInfo();
  }

But I am lost; I cannot understand why this happens. I have already written two custom assertions successfully (here and here), but this is the first time I see this error; the only difference here is that there is a type parameter to the class I attempt to create an assertion class for.

What am I missing?

Was it helpful?

Solution

You're trying to cast a ParsingResultAssert to class ParsingResult. The second argument to the super constructor should be ParsingResultAssert.class, not ParsingResult.class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top