0

I want to write a JUnit with Java for a generic method. I know that erasure happens in Java for generics but I suspect it should be possible to since there are ParametraizedTypes.

I want a way to get a string like this: T extends Comparable<? super T> or some way to check that method written in this format. I only want to check constraints. How can I test it in the best way?

@SafeVarargs
public static <T extends Comparable<? super T>> T findMax(T... list) {
    if (list.length == 0)
        return null;
    T max = list[0];
    for (T item : list)
    {
        if (item.compareTo(max) > 0)
            max = item;
    }
    return max;
}   

I want to write a test for this:

class A implements Comparable<Integer> {

    @Override
    public int compareTo(Integer o) {
        // do something
    }
}

// Test Method with JUnit
A a1 = new A();
A a2 = new A();
findMax(a1, a2); // Compile error
Erik
  • 503
  • 1
  • 7
  • 26
Ali
  • 1
  • 1
  • 1
    So you're asking how to write a JUnit test to verify the bound on the type parameter? – John Bollinger Jan 21 '19 at 17:00
  • Yes. I want to write a test for this method with most coverage. – Ali Jan 21 '19 at 17:01
  • So you don't want to test what the code does, but how is it written? Could you explain a bit why you want to do that? You can get 100 % code coverage without analyzing sources. – NeplatnyUdaj Jan 21 '19 at 17:10
  • I want to check that method written in this format. I want to check that if I sent two things that are not comparable, get Runtime error instead of compile error and fail test. but I couldn't write this. – Ali Jan 21 '19 at 17:16
  • I add a code to question. how can I test that with JUnit? – Ali Jan 21 '19 at 17:20
  • But the whole point of generics is that incompatible types are detected at compile time, not run time. If your code compiles without type safety warnings or errors (and does not suppress any such) then you should rely on it to not throw any `ClassCastException`s at tun time. If you see differently, then it indicates a bug in the compiler -- at minimum, it failed to perform adequate type analysis. – John Bollinger Jan 21 '19 at 17:23
  • Thanks. however I found something useful: https://stackoverflow.com/questions/2600854/how-to-work-with-varargs-and-reflection – Ali Jan 21 '19 at 17:31

0 Answers0