PoisonedYouth
09/11/2023, 10:52 AMArchUnit
Tests to Konsist
to check if all requirements are fullfiled.
❓ How would you solve the following requirement: All classes that are not in a given package should not use a specified class (or in other words) depend on it.
Konsist.scopeFromProduction()
.files
.filterNot { it.packagee?.fullyQualifiedName == "com.example.package" }
.assertNot {
it.imports.map { import -> import.name }.contains("com.example.package.TestClass")
}
igor.wojda
09/11/2023, 11:01 AMKonsist
.scopeFromProject()
.classes()
.withoutPackage("com.myapp")
.assertNot {
it.containingFile.hasImports("com.unwantedimport")
}
BTW wildcard can be used in packages
• .withoutPackage("com.myapp")
- com.myapp
package
• .withoutPackage("com.myapp..")
- com.myapp
package and all subpackages
https://docs.konsist.lemonappdev.com/features/packageselectorigor.wojda
09/11/2023, 11:06 AMPoisonedYouth
09/11/2023, 11:38 AMPoisonedYouth
09/11/2023, 11:43 AMPoisonedYouth
09/11/2023, 6:34 PMhasImports
method is working for checking that there are a defined list of imports are used in the given file.
override fun hasImports(vararg names: String): Boolean = when {
names.isEmpty() -> imports.isNotEmpty()
else -> names.all {
imports.any { import -> LocationUtil.resideInLocation(it, import.name) }
}
}
But this does not work I want to use it to define something like "should only use imports or none", because in this case imports.any
returns false and an assertion failure is returned.
Is this intended?PoisonedYouth
09/11/2023, 6:41 PMfun KoFileDeclaration.hasOnlyImportsOrNone(vararg names: String): Boolean {
if (this.imports.isEmpty()) {
return true
}
return imports.all { import ->
names.any { name ->
LocationUtil.resideInLocation(name, import.name)
}
}
}
igor.wojda
09/11/2023, 8:11 PMPoisonedYouth
09/12/2023, 4:31 AMNatalia Peterwas
09/12/2023, 8:20 AMassert
, so check is only performed hasImports
as classes that actually have imports
.classes()
.withImports()
.assert {
it.hasImports("com.myapp")
}
PoisonedYouth
09/12/2023, 8:50 AM