gpt4 book ai didi

java - 如何在返回 void 类型的公共(public)方法中测试局部变量?

转载 作者:行者123 更新时间:2023-11-29 04:31:16 26 4
gpt4 key购买 nike

我的 CUT 有一个公共(public)方法“sync()”,它返回 void,它使用一些变量,如“syncContactEnabled”,它们是使用 spring 和属性文件设置的。这是我的剪辑:

public class ContactSyncServiceImpl implements SyncService {

public void sync() {
long start = System.currentTimeMillis();
logger.info("-----sync() start:{}", start);
if (!syncContactEnabled) { //***********first: want to test this if
logger.info("Contact sync isn't enabled.");
return;
}

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date now = new Date();
Date startDate = null;
String contactSyncStartDateConfig = configService.get(CONTACT_SYNC_START_DATE);
if (StringUtils.isBlank(contactSyncStartDateConfig)) { \\**********second: I want to test startDate value in this if-else
startDate = new Date(now.getTime() - syncStartDaysCount * 24 * 60 * 60 * 1000l);
} else {
try {
startDate = formatter.parse(contactSyncStartDateConfig);
} catch (Exception e) {
logger.warn("There's a problem parsing date:" + e);
}
}


/////////It is NOT complite code of class.......(:
}

第一个问题:

  • 我如何模拟一些变量,例如在属性文件中设置的“syncContactEnabled”?

第二个问题:

  • 如何测试“sync()”方法的内部方式,例如如何在 if-else 条件下测试“startDate”值?

最后是我的属性文件:

sync.contact.enabled=false
sync.page.size=100
sync.cron=0 30 6,18 * * ?
#*/1 * * * * *
sync.start.days.count=365

最佳答案

first question:

  • How can I mock some variables like "syncContactEnabled" which it is set in properties file?

你不知道。

second question:

  • How can I test internal manner of "sync()" method, for example How can I test "startDate" value in if-else condition?

你也不知道。

当单元测试验证公共(public)可观察行为时,这意味着:返回什么结果取决于输入以及单元如何依赖项通信。

变量“syncContactEnabled”是您未验证的实现细节。这是因为 in 可能会在不更改单元行为的情况下更改,并且您不想在这种情况下更改测试。


I think, I just can use some test like: PowerMockito.donothing or PowerMockito.verify..... yes???? and I can not test internal manner... – m.mjn202

尽量避免 PowerMock(-ito)。在大多数情况下,PowerMock(-ito) 的需要是糟糕设计和缺乏依赖注入(inject)的标志。

通常你模拟依赖,你的单元与之通信的其他类。唯一的异常(exception)是您的单元是一个抽象类

doNothing(mock).someMethod()配置是必需的,如果你模拟了一个真正的类(而不是接口(interface))并且你需要禁止方法(someMethod()) 被调用(例如,因为它连接到数据库...)

关于java - 如何在返回 void 类型的公共(public)方法中测试局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43735887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com