gpt4 book ai didi

java - Mockito单元测试: on all method invocations of a class,返回 "true"

转载 作者:行者123 更新时间:2023-12-01 20:05:19 25 4
gpt4 key购买 nike

我有 kotlin 类(class) SmsHandler ,使用方法 determineFiltersPass调用另一个类的方法 SmsSendingFilters :

class SmsHandler(val filterPredicates: SmsSendingFilters) {
fun determineFiltersPass(sms: SmsDto): Boolean = with(sms.filters) {
var pass = true
for (filter in FiltersDto::class.memberProperties)
pass = when (FilterType.valueOf(filter.name.toUpperCase())) {
UNIQUE -> if (filter.get(sms.filters) != null) {
val unique = filter.get(sms.filters) as Boolean
pass && if (unique) filterPredicates.isUnique().test(sms) else true
} else pass && true
RECENT -> if (filter.get(sms.filters) != null) {
pass && filterPredicates.shouldSendByTimePeriodFromLastMessage().test(sms)
} else pass && true
else -> pass && true
}
pass
}
}


class SmsSendingFilters {

fun isUnique(): Predicate<SmsDto> = Predicate {
with(it) {
repo.findAllByMessageIdAndMobileNumAndAppIdAndParamMap(messageId!!, mobileNum!!, appId!!, paramMap!!.toString()).isEmpty()
}
}

fun shouldSendByTimePeriodFromLastMessage(): Predicate<SmsDto> = Predicate {
val calendar = Calendar.getInstance()
calendar.time = Date()
with(it.filters.recent ?: "" to "") {
val size = this.second.toInt()
when (IntervalType.valueOf(this.first.toUpperCase())) {
SECOND -> calendar.add(Calendar.SECOND, -1 * size)
MINUTE -> calendar.add(Calendar.MINUTE, -1 * size)
HOUR -> calendar.add(Calendar.HOUR, -1 * size)
MONTH -> calendar.add(Calendar.MONTH, -1 * size)
YEAR -> calendar.add(Calendar.YEAR, -1 * size)
else -> Unit
}
with(it) {
repo.findAllByMessageIdAndMobileNumAndAppId(messageId!!, mobileNum!!, appId!!)
.none { it.dateSent?.toInstant()?.isAfter(calendar.toInstant()) ?: true }
}
}
}
}

现在,我正在测试类 SmsHandler因为我预测更多的过滤器将添加到第二个类中,所以我想创建一个通用模拟,在调用类 SmsSendingFilters 中的任何方法时,将返回truefalse随我便。有没有一种方法可以在不显式描述每个方法名称的调用的情况下(我猜是通过反射)?

我不是在寻找某种解决方案:

when(filterPredicates.shouldSendByTimePeriodFromLastMessage().test(any()).thenReturn(true)

但是,符合这个逻辑的东西:

when(filterPredicates.<anyMethodInvoked>().test(any())).thenReturn(true)

最佳答案

You can register an Answer to change the default return value .

例如(使用优秀的 mockito-kotlin 包装器):

interface Thingy {
fun foo() : Boolean
fun bar() : Boolean
}

class ThingyTest {
@Test
fun test() {
val t1 = mock<Thingy>(defaultAnswer = Answer { false })
println(t1.foo()) // "false"
println(t1.bar()) // "false"

val t2 = mock<Thingy>(defaultAnswer = Answer { true })
println(t2.foo()) // "true"
println(t2.bar()) // "true"
}
}

当然,在更复杂的情况下,您可能有返回不同类型的方法,在这种情况下,您需要在 Answer 实现中做一些更聪明的事情!

关于java - Mockito单元测试: on all method invocations of a class,返回 "true",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47519631/

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