Skip to content

Instantly share code, notes, and snippets.

@sugihaya
Created December 12, 2023 04:02
Show Gist options
  • Save sugihaya/d94bc4a8e5fabe68002caec535f91c54 to your computer and use it in GitHub Desktop.
Save sugihaya/d94bc4a8e5fabe68002caec535f91c54 to your computer and use it in GitHub Desktop.
リフレションを使った自作assert
fun assertAllPropertiesNotNull(obj: Any) {
obj::class.memberProperties
.forEach { p ->
val value = (p as KProperty1<Any?, *>).get(obj) ?: throw AssertionFailedError("${p.name} is null", null, null)
assertNotNull(value, "${p.name} is null")
if (value.isUncheckType()) {
return@forEach // continue
}
// recursive
if (value is Collection<*>) {
value.forEach collectionForEach@ { element ->
if (element == null) {
throw AssertionFailedError("${p.name} contains null")
}
if (element.isUncheckType()) {
return@collectionForEach // continue
}
assertAllPropertiesNotNull(element, excludePropertyNames)
}
return@forEach // continue
}
// recursive
assertAllPropertiesNotNull(value, excludePropertyNames)
}
}
// POJO or プリミティブさえ判定できればいいがもっといい方法がないか
fun Any.isUncheckType() = when(this) {
is String, is Int, is Long, is Double, is Float, is Boolean -> true
else -> false
}
@sugihaya
Copy link
Author

すべてのプロパティがnull以外の値で初期化されているか?などを検証するために使うことを想定

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment