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?
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.