2

How can I test a class like this (see code below)?

public final class A {

    public static final String FIRST = "1st";
    public static final String SECOND = "2nd";

    private A() {
        // NOP
    }
}

For now all my coverage tools say that constructor isn't covered with tests. My tests look like on this:

assertEquals(A.FIRST, "1st");
assertEquals(A.SECOND, "2nd");

How can I test my class?

UPD

This code solved my problem.

@Test
public void magic() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    Constructor<A> constructor = A.class.getDeclaredConstructor();
    constructor.setAccessible(true);
    A instance = constructor.newInstance();

    assertNotNull(instance);
}

Yes, I agree that this isn't the best solution. But it works :)

barbara
  • 3,111
  • 6
  • 30
  • 58
  • 2
    Why would you want to test what is essentially a NOP method? – Martin Aug 18 '14 at 18:15
  • I need it because of coverage. I need 100% of coverage. But Cobertura, Jacoco, and my InelliJ IDEA tools say that class in uncovered. – barbara Aug 18 '14 at 18:16
  • You are using a class only to put constants on it. Don't you have any better place to set thoses? It's really a strange case – Martin Aug 18 '14 at 18:19
  • I don't want to use an enum. – barbara Aug 18 '14 at 18:21
  • @barbara That is not a good use of your time! And I think you can set those to ignore empty methods. – assylias Aug 18 '14 at 18:23
  • Things like this, and other trivial-type methods, are why people rarely ask for 100% coverage. – yshavit Aug 18 '14 at 18:24
  • 1
    Wanting 100% code coverage is probably more to _known who has the biggest_ (which is not what testing and code coverage are meant to), than to help maintainability and reduce bugs. – Volune Aug 18 '14 at 18:31
  • See also http://stackoverflow.com/questions/19106976/technique-for-extending-a-class-with-private-constructors – Raedwald Aug 18 '14 at 18:43

1 Answers1

4

Reflection is probably the way to go: How do I test a class that has private methods, fields or inner classes?

By the way, this is possibly a duplicate of the question in the link provided.

Alternatively, could you create a wrapper method that is protected which simply forwards all calls to the private method?

Community
  • 1
  • 1
Alex Kleiman
  • 709
  • 5
  • 14