How to make JUnit test fall down if constuctor is present?

101 views Asked by At

I am learning JUnit and Test Driven Development practice. I have empty Money interface:

public interface Money {

}

CommonMoney class which implements Money interface:

public class CommonMoney implements Money {

    private CommonMoney() {

    }

    public static Money create(String decimalPart, Currency currency) {
        return new Money() {
        };
    }
}

And MoneyTest class which tests CommonMoney

public class MoneyTest {

    // some test cases before

    @Test
    public void shouldNotCreateCommonMoneyObjectWithEmptyConstructor() {
        @SuppressWarnings("unused")
        Money money = new CommonMoney();
        fail();
    }
}

For now test case shouldNotCreateCommonMoneyObjectWithEmptyConstructor is red, but it should be green if constructor of CommonMoney is private and red if it is public. Is it possible to make test case like this? And how can I do it?

2

There are 2 answers

0
oleksii On BEST ANSWER

Is it possible to make test case like this?

Yes, it is possible to implement this test by using java reflection, for example see this question. Otherwise, you cannot test, that the private constructor is present, from outside of that class - the code just won't compile.

However, it doesn't really make sense to test this. Access modifiers are really there for developer convenience and to limit the access scope. Arguably, scope limitation is also done for convenience.

Your tests should cover public API and not look at private implementation.

0
Phil Anderson On

This is not the sort of thing you need to test.

As Agad pointed out, the code won't compile the way it is anyway, because by making the constructor private you've made it impossible to create the object with an empty constructor.

The compiler is effectively doing the check for you, so you don't need to write a specific test to check for it.