如果存在构造函数,如何使 JUnit 测试失败?
How to make JUnit test fall down if constuctor is present?
我正在学习 JUnit 和测试驱动开发实践。我有空的 Money 接口:
public interface Money {
}
实现 Money 接口的 CommonMoney class:
public class CommonMoney implements Money {
private CommonMoney() {
}
public static Money create(String decimalPart, Currency currency) {
return new Money() {
};
}
}
和测试 CommonMoney
的 MoneyTest class
public class MoneyTest {
// some test cases before
@Test
public void shouldNotCreateCommonMoneyObjectWithEmptyConstructor() {
@SuppressWarnings("unused")
Money money = new CommonMoney();
fail();
}
}
目前测试用例 shouldNotCreateCommonMoneyObjectWithEmptyConstructor 是红色的,但如果 CommonMoney 的构造函数是私有的,它应该是绿色的,如果是 public,它应该是红色的。是否可以制作这样的测试用例?我该怎么做?
Is it possible to make test case like this?
是的,可以通过使用java反射来实现这个测试,例如see this question。否则,您无法从 class 外部测试私有构造函数是否存在 - 代码无法编译。
但是,测试这个真的没有意义。访问修饰符实际上是为了方便开发人员并限制访问范围。可以说,范围限制也是为了方便。
您的测试应该涵盖 public API 而不是私有实现。
这不是您需要测试的那种东西。
正如 Agad 指出的那样,代码无论如何都不会编译,因为通过将构造函数设为私有,您就不可能使用空构造函数创建对象。
编译器正在有效地为您进行检查,因此您无需编写特定的测试来进行检查。
我正在学习 JUnit 和测试驱动开发实践。我有空的 Money 接口:
public interface Money {
}
实现 Money 接口的 CommonMoney class:
public class CommonMoney implements Money {
private CommonMoney() {
}
public static Money create(String decimalPart, Currency currency) {
return new Money() {
};
}
}
和测试 CommonMoney
的 MoneyTest classpublic class MoneyTest {
// some test cases before
@Test
public void shouldNotCreateCommonMoneyObjectWithEmptyConstructor() {
@SuppressWarnings("unused")
Money money = new CommonMoney();
fail();
}
}
目前测试用例 shouldNotCreateCommonMoneyObjectWithEmptyConstructor 是红色的,但如果 CommonMoney 的构造函数是私有的,它应该是绿色的,如果是 public,它应该是红色的。是否可以制作这样的测试用例?我该怎么做?
Is it possible to make test case like this?
是的,可以通过使用java反射来实现这个测试,例如see this question。否则,您无法从 class 外部测试私有构造函数是否存在 - 代码无法编译。
但是,测试这个真的没有意义。访问修饰符实际上是为了方便开发人员并限制访问范围。可以说,范围限制也是为了方便。
您的测试应该涵盖 public API 而不是私有实现。
这不是您需要测试的那种东西。
正如 Agad 指出的那样,代码无论如何都不会编译,因为通过将构造函数设为私有,您就不可能使用空构造函数创建对象。
编译器正在有效地为您进行检查,因此您无需编写特定的测试来进行检查。