0

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?

Oleksandr Tarasenko
  • 587
  • 1
  • 8
  • 16
  • 4
    If constructor is private, your test class doesn't compile. – agad Jun 16 '15 at 10:19
  • 2
    You could use reflection, but **why?** Do you not trust the people you're working with? Also be aware that tests of implementation are brittle and hard to maintain as the system grows. – kdgregory Jun 16 '15 at 10:20
  • 1
    If you just want to gurantee that the private constructor is never called (for what ever reasons) throw a checked exception within the body of the constructor. Though, as agad already stated, your test won't even compile due to the none-visibility of the constructor outside of the class. – Roman Vottner Jun 16 '15 at 10:23

2 Answers2

2

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.

Community
  • 1
  • 1
oleksii
  • 35,458
  • 16
  • 93
  • 163
1

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.

Phil Anderson
  • 3,146
  • 13
  • 24