【发布时间】:2023-03-23 06:30:01
【问题描述】:
我正在尝试模拟 DateTimeFormatter 类。我做了以下事情:
@RunWith(PowerMockRunner.class)
@PrepareForTest({DateTimeFormatter.class})
public class UnitTest {
private DateTimeFormatter mockDateFormatter;
private AwesomeClass awesomeClass;
@Before
public void setUp() {
mockDateFormatter = PowerMockito.mock(DateTimeFormatter.class);
awesomeClass = new AwesomeClass(mockDateFormatter);
}
@Test
public void shouldToTestSomethingAwesome() {
// Other test code
PowerMockito.when(mockDateFormatter.format(any(LocalDate.class)))
.thenReturn("20150224");
// Other test code
}
AwesomeClass 使用它来格式化LocalDateTime.now(ZoneId.of("UTC"));。然后,格式化的字符串进一步用于生成另一个字符串。我需要确保正确生成字符串。所以我需要从格式化程序返回一致的日期或模拟 LocalDateTime.now(..) 静态方法
我做错了什么?
【问题讨论】:
-
为什么你想模拟
DateTimeFormatter,出于兴趣?为什么你不只使用一个真实的?我会警惕过度模拟 - 它会使测试变得更加脆弱(并且难以阅读),而不是简单地使用真实代码或具有大致相同行为的假货。 -
听起来单元测试对我来说是个模拟......
-
我传递格式化程序的类使用它来格式化
LocalDateTime.now(ZoneId.of("UTC"));。然后,格式化的字符串进一步用于生成另一个字符串。我需要确保正确生成字符串。所以我需要从格式化程序返回一致的日期或模拟LocalDateTime.now(..)静态方法 -
确实,您应该使用真正的
DateTimeFormatter。您“需要确保正确生成字符串”的论点对我来说听起来并不令人信服。测试应旨在验证正确的行为,并尽可能通过被测类的公共合约;当然,您可以传递正确的输入,然后检查是否产生了正确的输出和/或结果;使用DateTimeFormatter只是一个实现细节。 (顺便说一句,要使其与 PowerMock 一起使用,您还需要准备被测类;但是,最好还是不要模拟。) -
我已经在代码中有
@PrepareForTest({DateTimeFormatter.class})。无论如何,我使用了@assylias 建议的方法