### Define Architectural Layers
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/create-secound-konsist-test-architectural-check.md
Initial setup for defining layers using the Layer class before applying architectural assertions.
```kotlin
// Define layers
private val presentationLayer = Layer("Presentation", "com.myapp.presentation..")
private val domainLayer = Layer("Domain", "com.myapp.domain..")
private val dataLayer = Layer("Data", "com.myapp.data..")
Konsist
.scopeFromProject()
// Assert architecture
.assertArchitecture {
// Define architectural rules
}
```
--------------------------------
### Representing Kotlin code with KoFileDeclaration
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/declaration.md
Example of a Kotlin file structure that is represented by the KoFileDeclaration class.
```kotlin
private const val logLevel = "debug"
@Entity
open class Logger(val level: String) {
fun log(message: String) {
}
}
```
--------------------------------
### Verify Module Package Consistency
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/architecture-snippets.md
Ensures that every file within a module is located in a package that starts with the module's name.
```kotlin
@Test
fun `every file in module reside in module specific package`() {
Konsist
.scopeFromProject()
.files
.assertTrue { it.packagee?.name?.startsWith(it.moduleName) }
}
```
--------------------------------
### Validate classes reside in a package starting with a prefix
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/packageselector.md
Uses the '..' wildcard to match any sub-packages under a specific base package.
```kotlin
Konsist
.scopeFromProject()
.classes()
.assertTrue { it.resideInPackages("com.app..") }
```
--------------------------------
### Define Static Use Case Tests
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/dynamic-konsist-tests/README.md
Examples of enforcing architectural rules for use cases using JUnit and Kotest frameworks.
```kotlin
class UseCaseKonsistTest {
@Test
fun `use case should have test`() {
Konsist
.scopeFromProject()
.classes()
.withNameEndingWith("UseCase")
.assertTrue { it.hasTestClass() }
}
@Test
fun `use case reside in domain dor usecase package`() {
Konsist
.scopeFromProject()
.classes()
.withNameEndingWith("UseCase")
.assertTrue { it.resideInPackage("..domain..usecase..") }
}
}
```
```kotlin
class UseCaseKonsistTest : FreeSpec({
val useCases = Konsist
.scopeFromProject()
.classes()
.withNameEndingWith("UseCase")
"use case should have test" {
useCases.assertTrue(testName = this.testCase.name.testName) { it.hasTestClass() }
}
"use case should reside in ..domain.usecase.. package" {
useCases.assertTrue(testName = this.testCase.name.testName) { it.resideInPackage("..domain.usecase..") }
}
})
```
--------------------------------
### Representing External Types
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/declaration-references.md
Example of a class inheriting from an external library type that Konsist cannot fully parse.
```kotlin
class MyViewModel: ViewModel
```
--------------------------------
### Publish Konsist to Local Maven
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/help/contributing.md
Execute this command to publish a SNAPSHOT version of Konsist to your local Maven repository.
```bash
./gradlew publishToMavenLocal -Pkonsist.releaseTarget=local
```
--------------------------------
### Retrieve direct parents of a class
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/indirect-parents.md
Use the parents() method to get the immediate parent of a class.
```kotlin
Konsist
.scopeFromProject()
.classes()
.first { it.name == "ClassC" }
.parents() // ClassB
```
--------------------------------
### Define Project Layers
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/create-secound-konsist-test-architectural-check.md
Create Layer instances by specifying a name and a package pattern. The double dot syntax (..) represents the package and all its sub-packages.
```kotlin
// Define layers
private val presentationLayer = Layer("Presentation", "com.myapp.presentation..")
private val domainLayer = Layer("Domain", "com.myapp.domain..")
private val dataLayer = Layer("Data", "com.myapp.data..")
```
--------------------------------
### Access the Konsist entry point
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/create-first-konsist-test-declaration-check.md
The Konsist object serves as the primary entry point for the library.
```kotlin
Konsist
```
--------------------------------
### Create scope from directory
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Creates a scope containing all files within a specified project directory.
```kotlin
val myScope = Konsist.scopeFromDirectory("app/domain")
```
--------------------------------
### Restrict 'm' prefix in field names
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/general-snippets.md
Checks that class properties do not start with the 'm' prefix followed by an uppercase letter.
```kotlin
@Test
fun `no field should have 'm' prefix`() {
Konsist
.scopeFromProject()
.classes()
.properties()
.assertFalse {
val secondCharacterIsUppercase = it.name.getOrNull(1)?.isUpperCase() ?: false
it.name.startsWith('m') && secondCharacterIsUppercase
}
}
```
--------------------------------
### Query Functions in Project
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-functions.md
Initial entry points for querying functions from the project scope.
```kotlin
Konsist
.scopeFromProject()
.functions()
...
```
```kotlin
Konsist
.scopeFromProject()
.classes()
.functions()
...
```
```kotlin
Konsist
.scopeFromProject()
.classes()
.functions(includeLocal = true)
...
```
--------------------------------
### Query project properties
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-properties.md
Initial entry point for querying all properties in a project scope.
```kotlin
Konsist
.scopeFromProject()
.properties()
...
```
--------------------------------
### Configure konsistTest in Gradle (Kotlin)
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/isolate-konsist-tests.md
Uses the JVM Test Suite Plugin to register a new test suite and add necessary dependencies.
```kotlin
// build.gradle.kts (root)
plugins {
`jvm-test-suite`
}
testing {
suites {
register("konsistTest", JvmTestSuite::class) {
dependencies {
// Add 'main' source set dependency
implementation(project())
// Add Konsist dependency
implementation("com.lemonappdev:konsist:0.13.0")
}
}
}
}
// Optional : Remove Konsist tests from the 'check' task if it exists
tasks.matching { it.name == "check" }.configureEach {
setDependsOn(dependsOn.filter { it.toString() != "konsistTest" })
}
```
--------------------------------
### Restrict RestController Return Types
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/spring-snippets.md
Prevents controller methods from returning types that start with 'List', enforcing specific response wrappers.
```kotlin
@Test
fun `classes with 'RestController' annotation should never return collection`() {
Konsist
.scopeFromPackage("story.controller..")
.classes()
.withAnnotationOf(RestController::class)
.functions()
.assertFalse { function ->
function.hasReturnType { it.hasNameStartingWith("List") }
}
}
```
--------------------------------
### Configure konsistTest in Maven
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/isolate-konsist-tests.md
Uses the Build Helper Maven Plugin to add a custom test source directory.
```xml
# app/pom.xml
org.codehaus.mojobuild-helper-maven-plugin3.3.0add-konsist-test-sourcegenerate-test-sourcesadd-test-source${project.basedir}/src/konsistTest/kotlin
```
--------------------------------
### Apply Konsist to the Entire Project
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/add-konsist-existing-project.md
Use scopeFromProject to cover all modules, ensuring future modules are automatically included.
```kotlin
Konsist
.scopeFromProject()
.classes()
.assertTrue { it.hasTest() }
```
--------------------------------
### Run project test suites
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/help/contributing.md
Execute various test suites including unit, API, integration, and Konsist-specific tests.
```bash
./gradlew lib:test
```
```bash
./gradlew lib:apiTest
```
```bash
./gradlew lib:integrationTest
```
```bash
./gradlew lib:konsistTest
```
--------------------------------
### Run Detekt static analysis
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/help/contributing.md
Execute static code analysis using Detekt.
```bash
./gradlew detektCheck
```
```bash
./gradlew detektApply
```
--------------------------------
### Configure konsistTest in Gradle (Groovy)
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/isolate-konsist-tests.md
Defines a custom test suite using the JVM Test Suite Plugin with Groovy DSL.
```groovy
// build.gradle (root)
plugins {
id 'jvm-test-suite'
}
testing {
suites {
test {
useJUnitJupiter()
}
konsistTest(JvmTestSuite) {
dependencies {
// Add 'main' source set dependency
implementation project()
// Add Konsist dependency
implementation "com.lemonappdev:konsist:0.13.0"
}
targets {
all {
testTask.configure {
shouldRunAfter(test)
}
}
}
}
}
}
// Optional: Remove Konsist tests from the 'check' task if it exists
tasks.matching { it.name == "check" }.configureEach { task ->
task.setDependsOn(task.getDependsOn().findAll { it.toString() != "konsistTest" })
}
```
--------------------------------
### Include konsistTest module in settings.gradle.kts
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/isolate-konsist-tests.md
Register the new module in the project's settings file.
```kotlin
// settings.gradle.kts
include(":konsistTest")
```
```groovy
// settings.gradle
include ':konsistTest'
```
--------------------------------
### Configure Local Repository in Build Files
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/help/contributing.md
Add these blocks to your build configuration to enable resolution of the locally published Konsist artifact.
```kotlin
repositories {
mavenLocal()
}
```
```xml
localfile://${user.home}/.m2/repository
```
--------------------------------
### Execute Konsist Tests
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/isolate-konsist-tests.md
Commands to run the isolated test suite in Gradle and Maven environments.
```bash
./gradlew app:konsistTest
```
```yaml
mvn test
```
--------------------------------
### Run Spotless code checks
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/help/contributing.md
Execute code formatting and linting checks using Spotless.
```bash
./gradlew spotlessCheck
```
```bash
./gradlew spotlessApply
```
--------------------------------
### Konsist Scope Creation Methods
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Methods to initialize a KoScope for testing purposes.
```APIDOC
## Konsist Scope Creation
### Konsist.scopeFromProject()
Creates a scope containing all Kotlin files in the project.
### Konsist.scopeFromProduction()
Creates a scope containing only production code files.
### Konsist.scopeFromTest()
Creates a scope containing only test code files.
### Konsist.scopeFromModule(moduleName: String)
Creates a scope containing all files within a specific module. Supports nested modules using path syntax (e.g., "app/feature").
### Konsist.scopeFromSourceSet(sourceSetName: String)
Creates a scope containing all files within a specific source set.
### Konsist.scopeFromProject(moduleName: String, sourceSetName: String)
Creates a scope filtered by both module name and source set name.
### Konsist.sourceFromPackage(packagePattern: String)
Creates a scope containing files matching a specific package pattern (e.g., "com.usecase..").
```
--------------------------------
### Include Layers Without Dependencies
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/architecture-assert.md
Use include() to verify a layer without defining dependencies, or doesOnNothing() to ensure a layer remains independent.
```kotlin
private val domain = Layer("Domain", "com.domain..")
private val presentation = Layer("Presentation", "com..presentation..")
Konsist
.scopeFromProject()
scope.assertArchitecture {
// Include presentation for architectural check without defining a dependency
presentation.include()
// Include domain layer or architectural check and define no dependency (independent)
domain.doesOnNothing()
}
}
```
--------------------------------
### Query interfaces in project
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-interfaces.md
Selects all interfaces within the project scope.
```kotlin
Konsist
.scopeFromProject()
.interfaces()
...
```
--------------------------------
### Apply annotation to a function
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/declaration-vs-property.md
Demonstrates the use-site of an annotation on a function.
```kotlin
@CustomLogger
fun logHello() {
println("Hello")
}
```
--------------------------------
### JUnit5 Configuration File Paths
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/additional-junit5-setup.md
Recommended locations for the junit-platform.properties file within the test source sets.
```text
src/test/resource/junit-platform.properties
or
src/konsistTest/resource/junit-platform.properties
```
--------------------------------
### Print KoScope Files
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/debug-konsist-test.md
Outputs the list of files contained within the KoScope to the console.
```kotlin
koScope // KoScope
.print()
```
--------------------------------
### Define Architecture Layers
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/architecture-assert.md
Create Layer instances to represent project layers, using the name for error reporting and a package string to define the layer scope.
```kotlin
Konsist
.scopeFromProject()
.assertArchitecture {
// Define layers
val presentation = Layer("Presentation", "com.myapp.presentation..")
val data = Layer("Data", "com.myapp.data..")
}
```
--------------------------------
### Define Generic Type Parameters and Arguments
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/verify-codebase/verify-generics.md
Illustrates the difference between type parameters in declarations and type arguments in usage.
```kotlin
// Example 1: Class
// Here 'T' is a TYPE PARAMETER
class Box(val item: T)
// Here 'String' is a TYPE ARGUMENT
val stringBox = Box("Hello")
// Example 2: Function
// Here 'T' is a TYPE PARAMETER
fun printWithType(item: T) {
println("Type is: ${item::class.simpleName}")
}
// Here 'String' and 'Int' are TYPE ARGUMENTS
printWithType("Hello") // prints: Type is: String
```
--------------------------------
### Retrieving functions from classes
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/declaration.md
Demonstrates chaining methods to access all functions within all classes of a file.
```kotlin
koFile // List
.classes() // List
.functions() // List
```
--------------------------------
### Create Production Codebase Scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Creates a scope containing only production code files.
```kotlin
Konsist.scopeFromProduction()
```
--------------------------------
### Create scope from file paths
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Creates a scope from a single file path or a list of file paths.
```kotlin
val myScope = Konsist.scopeFromFile("app/main/domain/UseCase.kt")
```
```kotlin
val filePaths = listOf("/domain/UseCase1.kt", "/domain/UseCase2.kt")
val myScope = Konsist.scopeFromFile(filePaths)
```
--------------------------------
### Print Declarations
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/debug-konsist-test.md
Outputs a list of class declarations to the console.
```kotlin
koScope
.classes() // List
.print()
```
--------------------------------
### Print Query Pipeline
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/debug-konsist-test.md
Logs the state of declarations before and after applying a filter in the query chain.
```kotlin
koScope
.classes() // List
.print(prefix = "Before") // or .print(prefix = "Before") { it.name }
.withSomeAnnotations("Logger")
.print(prefix = "After") // or .print(prefix = "After") { it.name }
```
--------------------------------
### Configure Full Exception Logging in Gradle
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/enable-full-command-line-logging.md
Enable detailed exception reporting in Gradle to see file paths and line numbers for failed tests.
```kotlin
tasks.withType {
testLogging {
events(TestLogEvent.FAILED)
exceptionFormat = TestExceptionFormat.FULL
}
}
```
```groovy
tasks.test {
testLogging {
events(TestLogEvent.FAILED)
exceptionFormat = TestExceptionFormat.FULL
}
}
```
--------------------------------
### Add Snapshot Repository
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/konsist-snapshots.md
Configure the snapshot repository URL in your build system to enable access to development builds.
```kotlin
repositories {
// Konsist snapshot repository
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/")
// More repositorues
}
```
```groovy
repositories {
// Konsist snapshot repository
maven {
url 'https://s01.oss.sonatype.org/content/repositories/snapshots/'
}
// More repositories
}
```
```xml
konsist-snapshotshttps://s01.oss.sonatype.org/content/repositories/snapshots/true
```
--------------------------------
### Create Module and Source Set Scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Retrieves a scope using both module and source set identifiers.
```kotlin
Konsist.scopeFromProject(moduleName = "app", sourceSetName = "test)
```
--------------------------------
### Create Test Codebase Scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Creates a scope containing only test code files.
```kotlin
Konsist.scopeFromTest()
```
--------------------------------
### Validate package name matches file path
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/general-snippets.md
Verifies that the package declaration in a file corresponds to its directory structure.
```kotlin
@Test
fun `package name must match file path`() {
Konsist
.scopeFromProject()
.packages
.assertTrue { it.hasMatchingPath }
}
```
--------------------------------
### Apply Konsist to a Single Module
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/add-konsist-existing-project.md
Use scopeFromModule to target a specific module for initial testing.
```kotlin
Konsist
.scopeFromModule("featureCaloryCalculator")
.classes()
.assertTrue { it.hasTestClasses() }
```
--------------------------------
### Verify Clean Architecture Layer Dependencies
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/clean-architecture-snippets.md
Defines architectural layers and asserts their dependency rules using Konsist's assertArchitecture DSL.
```kotlin
@Test
fun `clean architecture layers have correct dependencies`() {
Konsist
.scopeFromProduction()
.assertArchitecture {
// Define layers
val domain = Layer("Domain", "com.myapp.domain..")
val presentation = Layer("Presentation", "com.myapp.presentation..")
val data = Layer("Data", "com.myapp.data..")
// Define architecture assertions
domain.dependsOnNothing()
presentation.dependsOn(domain)
data.dependsOn(domain)
}
}
```
--------------------------------
### Verify property initialization
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-properties.md
Verifies if a property is initialized.
```kotlin
...
.assertTrue {
it.isInitialized
}
```
--------------------------------
### Print Single Declaration
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/debug-konsist-test.md
Logs the details of a single declaration to the console.
```kotlin
koScope
.classes() // List
.first() // KoClassDeclaration
.print()
```
--------------------------------
### Verify Compose Preview Naming
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/android-snippets.md
Ensures that all functions annotated with @Preview include 'Preview' in their method name.
```kotlin
@Test
fun `All JetPack Compose previews contain 'Preview' in method name`() {
Konsist
.scopeFromProject()
.functions()
.withAnnotationOf(Preview::class)
.assertTrue {
it.hasNameContaining("Preview")
}
}
```
--------------------------------
### Verify constructor parameter naming convention
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/general-snippets.md
Ensures that every constructor parameter name matches its type name in title case.
```kotlin
@Test
fun `every constructor parameter has name derived from parameter type`() {
Konsist
.scopeFromProject()
.classes()
.constructors
.parameters
.assertTrue {
val nameTitleCase = it.name.replaceFirstChar { char -> char.titlecase(Locale.getDefault()) }
nameTitleCase == it.type.sourceType
}
}
```
--------------------------------
### Configure JVM Heap Size in Build Systems
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/help/known-issues/java.lang.outofmemoryerror-java-heap-space.md
Adjust the maximum heap size for test execution in Gradle and Maven projects.
```kotlin
tasks.withType {
maxHeapSize = "1g"
}
```
```groovy
tasks.withType(Test).configureEach {
maxHeapSize = "1g"
}
```
```xml
org.apache.maven.pluginsmaven-surefire-plugin3.0.0-Xmx1g
```
--------------------------------
### Create Source Set Scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Creates a scope based on a specific source set name.
```kotlin
Konsist.scopeFromSourceSet("test")
```
--------------------------------
### Create Package Scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Creates a scope containing code within a specific package.
```kotlin
Konsist.sourceFromPackage("com.usecase..")
```
--------------------------------
### Define a project scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/create-first-konsist-test-declaration-check.md
Use scopeFromProject to obtain a scope containing all Kotlin files in the project.
```kotlin
// Define the scope containing all Kotlin files present in the project
Konsist.scopeFromProject() //Returns KoScope
```
--------------------------------
### Print Nested Declarations
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/debug-konsist-test.md
Logs a chain of nested declarations, such as constructors and their parameters, to the console.
```kotlin
koScope
.classes() // List
.constructors // List
.parameters // List
.print()
```
--------------------------------
### Register custom konsistCheck task
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/isolate-konsist-tests.md
Create a root-level task to execute Konsist tests with the --rerun-tasks flag to ensure full analysis.
```kotlin
tasks.register("konsistCheck") {
group = "verification"
description = "Runs Konsist static code analysis"
doLast {
val output = ByteArrayOutputStream()
val result = project.exec {
commandLine("./gradlew", "konsistTest:test", "--rerun-tasks")
standardOutput = output
errorOutput = output
isIgnoreExitValue = true
}
println(output.toString())
if (result.exitValue != 0) {
throw GradleException("Konsist tests failed")
}
}
}
```
```groovy
tasks.register("konsistCheck") {
group = "verification"
description = "Runs Konsist static code analysis"
doLast {
def output = new ByteArrayOutputStream()
def result = project . exec {
commandLine './gradlew', 'konsistTest:test', '--rerun-tasks'
standardOutput = output
errorOutput = output
ignoreExitValue = true
}
println output . toString ()
if (result.exitValue != 0) {
throw new GradleException ("Konsist tests failed")
}
}
}
```
--------------------------------
### Enforce Naming Convention for Files in Package
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/general-snippets.md
Ensures all files within the 'ext' package follow a specific naming convention ending with 'Ext'.
```kotlin
@Test
fun `files in 'ext' package must have name ending with 'Ext'`() {
Konsist
.scopeFromProject()
.files
.withPackage("..ext..")
.assertTrue { it.hasNameEndingWith("Ext") }
}
```
--------------------------------
### Prevent empty files
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/general-snippets.md
Validates that no files in the project are empty.
```kotlin
@Test
fun `no empty files allowed`() {
Konsist
.scopeFromProject()
.files
.assertFalse { it.text.isEmpty() }
}
```
--------------------------------
### Check Primary Constructor
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/compiler-type-inference.md
Illustrates that Konsist returns null for primary constructors not explicitly defined in the source code.
```kotlin
class Logger
```
```kotlin
koClass.primaryConstructor // null
```
--------------------------------
### Print Specific Attribute
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/debug-konsist-test.md
Logs a specific attribute, such as the fully qualified name, for each declaration in the list.
```kotlin
koScope
.classes() // List
.print { it.fullyQualifiedName }
```
--------------------------------
### Verify package location
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/create-first-konsist-test-declaration-check.md
Use resideInPackage within an assertion to verify the package structure of the filtered classes.
```kotlin
Konsist.scopeFromProject()
.classes()
.withAllAnnotationsOf(RestController::class)
.assertTrue {
// Check if classes are located in the controller package
it.resideInPackage("..controller")
}
```
--------------------------------
### Print declarations
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/declaration-query-and-filter.md
Output all declarations within a scope to the console using the print method.
```kotlin
koScope
.classes()
.properties()
.print()
```
--------------------------------
### Add Konsist Dependency
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/konsist-snapshots.md
Include the Konsist snapshot dependency in your project using the X.Y.Z-SNAPSHOT version format.
```kotlin
dependencies {
testImplementation("com.lemonappdev:konsist:X.Y.Z-SNAPSHOT")
}
```
```groovy
dependencies {
testImplementation "com.lemonappdev:konsist:X.Y.Z-SNAPSHOT"
}
```
```xml
com.lemonappdevkonsistX.Y.Z-SNAPSHOTtest
```
--------------------------------
### Define Reusable Architecture Configurations
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/architecture-assert.md
Store architecture rules in a variable to apply the same configuration across multiple scopes or test methods.
```kotlin
// Define architecture
val architecture = architecture {
val presentation = Layer("Presentation", "com.myapp.presentation..")
val data = Layer("Data", "com.myapp.data..")
presentation.dependsOn(data)
data.dependsOnNothing()
}
// Assert Architecture of two modules using common architecture rules
moduleFeature1Scope.assertArchitecture(architecture)
moduleFeature2Scope.assertArchitecture(architecture)
```
```kotlin
class ArchitectureTest {
private val architecture = architecture {
val presentation = Layer("Presentation", "com.myapp.presentation..")
val data = Layer("Data", "com.myapp.data..")
presentation.dependsOn(data)
data.dependsOnNothing()
}
@Test
fun `architecture layers of feature1 module have dependencies correct`() {
moduleFeature1Scope.assertArchitecture(architecture)
}
@Test
fun `architecture layers of feature2 module have dependencies correct`() {
moduleFeature2Scope.assertArchitecture(architecture)
}
}
```
--------------------------------
### Define Layer Dependencies
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/architecture-assert.md
Use the assertArchitecture block to define layers and their respective dependencies within the project scope.
```kotlin
Konsist
.scopeFromProject()
.assertArchitecture {
val presentation = Layer("Presentation", "com.myapp.presentation..")
val data = Layer("Data", "com.myapp.data..")
// Define dependencies
presentation.dependsOn(data)
data.dependsOnNothing()
}
```
--------------------------------
### Add Maven Central Repository
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/add-konsist-dependency.md
Include the Maven Central repository in your build configuration to resolve the Konsist dependency.
```gradle
repositories {
mavenCentral()
}
```
--------------------------------
### Add Konsist Dependency
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/add-konsist-dependency.md
Add the Konsist library as a test dependency using Gradle or Maven.
```kotlin
dependencies {
testImplementation("com.lemonappdev:konsist:0.17.3")
}
```
```groovy
dependencies {
testImplementation "com.lemonappdev:konsist:0.17.3"
}
```
```xml
com.lemonappdevkonsist0.17.3test
```
--------------------------------
### Verify Use Case Package Location
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/README.md
Tests that all classes ending with 'UseCase' are located within the 'domain.usecase' package.
```kotlin
class UseCaseKonsistTest {
@Test
fun `every use case reside in use case package`() {
Konsist
.scopeFromProject() // Define the scope containing all Kotlin files present in the project
.classes() // Get all class declarations
.withNameEndingWith("UseCase") // Filter classes heaving name ending with 'UseCase'
.assertTrue { it.resideInPackage("..domain.usecase..") } // Assert that each class resides in 'any domain.usecase any' package
}
}
```
```kotlin
class UseCaseKonsistTest : FreeSpec({
"every use case reside in use case package" {
Konsist
.scopeFromProject() // Define the scope containing all Kotlin files present in the project
.classes() // Get all class declarations
.withNameEndingWith("UseCase") // Filter classes heaving name ending with 'UseCase'
.assertTrue (
testName = this.testCase.name.testName
){
it.resideInPackage("..domain.usecase..")
} // Assert that each class resides in 'any domain.usecase any' package
}
})
```
--------------------------------
### Retrieve classes from scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/create-first-konsist-test-declaration-check.md
Query all classes present within the defined project scope.
```kotlin
Konsist.scopeFromProject()
// Get scope classes
.classes()
```
--------------------------------
### Configure JUnit5 Parallel Execution
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/additional-junit5-setup.md
Properties to enable and configure parallel execution in the junit-platform.properties file.
```properties
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=concurrent
junit.jupiter.execution.parallel.config.strategy=dynamic
junit.jupiter.execution.parallel.config.dynamic.factor=0.95
```
--------------------------------
### Create Module Scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Creates a scope based on a specific module name.
```kotlin
Konsist.scopeFromModule("app")
```
```kotlin
val refactoredModule1Scope = Konsist.scopeFromModule("refactoredModule1")
val refactoredModule1Scope = Konsist.scopeFromModule("refactoredModule2")
val scope = refactoredModule1Scope + refactoredModule1Scop2
scope
.classes()
...
.assertTrue { /*..*/ }
```
--------------------------------
### Mixing Queries and Filters
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/query-and-filter-declarations.md
Combine querying and filtering stages to perform complex declaration checks.
```kotlin
koScope
.classes() // query all classes
.resideInPackage("..controller") // filter classes in 'controller' package
.properties() // query all properties
.withAnnotationOf() // filter classes in 'controller' package
.assertTrue { // .. }
```
--------------------------------
### Verify class package
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-classes.md
Ensures a class resides within a specific package or its sub-packages.
```kotlin
...
.assertTrue {
it.resideInPackage("com.lemonappdev.model..")
}
```
--------------------------------
### Verify class constructors
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-classes.md
Validates primary and secondary constructor presence and annotations.
```kotlin
...
.assertTrue {
it.hasPrimaryConstructor
}
```
```kotlin
...
.primaryConstructors
.assertTrue {
it.hasAnnotation(Inject::class)
}
```
--------------------------------
### Verify alphabetical order of constructor parameters
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/general-snippets.md
Validates that all parameters within a class constructor are sorted alphabetically by name.
```kotlin
@Test
fun `every class constructor has alphabetically ordered parameters`() {
Konsist
.scopeFromProject()
.classes()
.constructors
.assertTrue { it.parameters.isSortedByName() }
}
```
--------------------------------
### Verify property type
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-properties.md
Ensures properties match a specific type.
```kotlin
...
.assertTrue {
it.type?.name == "LocalDateTime"
}
```
--------------------------------
### Applying Multiple Filters
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/query-and-filter-declarations.md
Chain multiple conditions to refine the selection of declarations.
```kotlin
koScope
.classes()
.withAnnotationOf()
.resideInPackage("..usecase")
.assertTrue { // .. }
```
--------------------------------
### Combine Konsist scopes using the plus operator
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Use the + operator to merge multiple module scopes into a single scope for analysis.
```kotlin
val featureModule1Scope = Konsist.scopeFromModule("myFeature1")
val featureModule2Scope = Konsist.scopeFromModule("myFeature2")
val refactoredModules = featureModule1Scope + featureModule2Scope
refactoredModules
.classes()
...
.assertTrue { ... }
```
--------------------------------
### Print files within a scope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Invoke the print method on a koScope instance to output all contained files.
```kotlin
koScope.print()
```
--------------------------------
### Verify Function Annotations
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-functions.md
Verifies the presence of specific annotations on functions.
```kotlin
...
.assertTrue {
it.hasAnnotationOf(Binding::class)
}
```
--------------------------------
### Verify companion objects
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-interfaces.md
Checks for the existence of a companion object with specific modifiers.
```kotlin
...
.assertTrue {
it.hasObject { objectt -> objectt.hasCompanionModifier }
}
```
--------------------------------
### Cast and verify type declarations
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/declaration-references.md
Demonstrates casting a generic KoTypeDeclaration to a specific KoClassDeclaration to verify annotations.
```kotlin
Konsist
.scopeFromProject()
.properties()
.types
.assertTrue { koTypeDeclaration ->
val koClass = koTypeDeclaration as KoClassDeclaration
koClass.hasAllAnnotations {
it.representsTypeOf()
}
}
```
```kotlin
Konsist
.scopeFromProject()
.properties()
.types
.assertTrue { koTypeDeclaration ->
koTypeDeclaration
.asClassDeclaration
?.hasAllAnnotations {
it.representsTypeOf()
}
}
```
--------------------------------
### Verify KDoc presence on API declarations
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/library-snippets.md
Ensures all declarations within the API package implement KDoc.
```kotlin
@Test
fun `every api declaration has KDoc`() {
Konsist
.scopeFromPackage("..api..")
.declarationsOf()
.assertTrue { it.hasKDoc }
}
```
--------------------------------
### Accessing function names
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/declaration.md
Shows how to retrieve the name property from a specific function declaration.
```kotlin
val name = koFile // List
.classes() // List
.functions() // List
.first() // KoFunctionDeclaration
.name // String
println(name) // prints: log
```
--------------------------------
### Generate dynamic tests with Kotest
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/dynamic-konsist-tests/README.md
Integrates dynamic testing using FreeSpec to iterate over use cases and define test assertions.
```kotlin
class UseCaseKonsistTest : FreeSpec({
Konsist
.scopeFromProject()
.classes()
.withNameEndingWith("UseCase")
.forEach { useCase ->
"${useCase.name} should have test" {
useCase.assertTrue(testName = this.testCase.name.testName) { it.hasTestClass() }
}
"${useCase.name} should reside in ..domain.usecase.. package" {
useCase.assertTrue(testName = this.testCase.name.testName) { it.resideInPackage("..domain..usecase..") }
}
}
})
```
--------------------------------
### Verify list emptiness
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/declaration-assert.md
Checks if the collection of declarations is empty or not empty.
```kotlin
Konist
.scopeFromProject()
.classes()
.assertEmpty()
```
```kotlin
Konist
.scopeFromProject()
.classes()
.assertNotEmpty()
```
--------------------------------
### Verify members order
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-classes.md
Enforces a specific order of members, such as properties before functions.
```kotlin
...
.assertTrue {
val lastKoPropertyDeclarationIndex = it
.declarations(includeNested = false, includeLocal = false)
.indexOfLastInstance()
val firstKoFunctionDeclarationIndex = it
.declarations(includeNested = false, includeLocal = false)
.indexOfFirstInstance()
if (lastKoPropertyDeclarationIndex != -1 && firstKoFunctionDeclarationIndex != -1) {
lastKoPropertyDeclarationIndex < firstKoFunctionDeclarationIndex
} else {
true
}
}
```
--------------------------------
### Verify Repository Package Location
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/android-snippets.md
Enforces that classes ending with 'Repository' are located within the 'repository' package.
```kotlin
@Test
fun `'Repository' classes should reside in 'repository' package`() {
Konsist
.scopeFromProject()
.classes()
.withNameEndingWith("Repository")
.assertTrue { it.resideInPackage("..repository..") }
}
```
--------------------------------
### Verify Generic Parameters and Arguments
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-functions.md
Checks for the presence of type parameters or the structure of generic type arguments.
```kotlin
...
.assertTrue {
it.hasTypeParameters()
}
```
```kotlin
...
.assertFalse {
it.returnType?.hasTypeArguments()
}
```
--------------------------------
### Validate 2 Layer Architecture Dependencies
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/architecture-snippets.md
Defines architectural layers and enforces dependency rules between them using Konsist's assertArchitecture.
```kotlin
@Test
fun `2 layer architecture has correct dependencies`() {
Konsist
.scopeFromProject()
.assertArchitecture {
val presentation = Layer("Presentation", "com.myapp.presentation..")
val business = Layer("Business", "com.myapp.business..")
val persistence = Layer("Persistence", "com.myapp.persistence..")
val database = Layer("Database", "com.myapp.database..")
presentation.dependsOn(business)
business.dependsOn(presentation)
business.dependsOn(persistence)
persistence.dependsOn(business)
business.dependsOn(database)
database.dependsOn(business)
}
}
```
--------------------------------
### Querying Properties in Classes
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/query-and-filter-declarations.md
Retrieve all properties defined within classes in the scope.
```kotlin
koScope
.classes()
.properties()
.assertTrue { // .. }
```
--------------------------------
### Verify companion objects
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-classes.md
Checks for the existence of a companion object within the class.
```kotlin
...
.assertTrue { declaration ->
declaration.hasObject { it.hasCompanionModifier }
}
```
--------------------------------
### Extend Konsist Scope to Multiple Modules
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/add-konsist-existing-project.md
Expand the testing scope by adding additional modules to the scopeFromModule function.
```kotlin
Konsist
.scopeFromModule("featureCaloryCalculator", "featureGroceryListGenerator")
.classes()
.assertTrue { it.hasTest() }
```
--------------------------------
### Verify interface children package
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/declaration-references.md
Checks if all interfaces have children residing in a specific package.
```kotlin
Konsist
.scopeFromProject()
.interfaces()
.assertTrue {
it.hasAllChildren(indirectChildren = true) { child ->
child.resideInPackage("..somepackage..")
}
}
```
--------------------------------
### Force test execution by disabling up-to-date checks
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/isolate-konsist-tests.md
Configure the test task to always run, preventing Gradle from skipping tests when the module appears unchanged.
```kotlin
// konsistTest/build.gradle.kts
tasks.withType {
outputs.upToDateWhen { false }
}
```
```groovy
// konsistTest/build.gradle
tasks.withType(Test) {
outputs.upToDateWhen { false }
}
```
--------------------------------
### Pass testName argument to Konsist assertion
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/advanced/dynamic-konsist-tests/explicit-test-names.md
Demonstrates the basic syntax for passing a custom test name to a Konsist assertion method.
```kotlin
Konsist.scopeFromProject()
.classes()
.assertTrue(testName = "My test name") { ... } //passed test name
```
--------------------------------
### Validate multiple UseCase architectural rules
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/kotest-snippets.md
Iterates over UseCase classes to apply multiple architectural assertions, such as package location and test existence.
```kotlin
class UseCaseTests : FreeSpec({
Konsist
.scopeFromProject()
.classes()
.withNameEndingWith("UseCase")
.forEach { useCase ->
"${useCase.name} should have test" {
useCase.assertTrue(testName = this.testCase.name.testName) { it.hasTestClasses() }
}
"${useCase.name} should reside in ..domain..usecase.. package" {
useCase.assertTrue(testName = this.testCase.name.testName) { it.resideInPackage("..domain..usecase..") }
}
"${useCase.name} should ..." {
// another Konsist assert
}
}
})
```
--------------------------------
### Exclude Files from Architecture Verification
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/architecture-assert.md
Filter the KoScope by file names before passing it to the assertArchitecture block to narrow the verification scope.
```kotlin
Konsist
.scopeFromProject()
.files
.withNameStartingWith("Repository")
.assertArchitecture {
val presentation = Layer("Presentation", "com.myapp.presentation..")
val data = Layer("Data", "com.myapp.data..")
presentation.dependsOn(data)
data.dependsOnNothing()
}
```
--------------------------------
### Verify Function Parameters
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-functions.md
Checks for specific parameter types within a function signature.
```kotlin
...
.assertTrue {
it.hasParameter { parameter -> parameter.hasTypeOf(String::class) }
}
```
--------------------------------
### Check Class Visibility
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/compiler-type-inference.md
Demonstrates the difference between checking for an explicit public modifier versus the effective public visibility.
```kotlin
class Logger
```
```kotlin
koClass.hasPublicModifier() // false
```
```kotlin
koClass.isPublicOrDefault() // true
```
--------------------------------
### Implement Konsist Declaration Check in JUnit
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/create-first-konsist-test-declaration-check.md
Use the JUnit framework to define a test that verifies classes annotated with 'RestController' reside in the 'controller' package.
```kotlin
class ControllerClassKonsistTest {
@Test
fun `classes annotated with 'RestController' annotation reside in 'controller' package`() {
// 1. Create a scope representing the whole project (all Kotlin files in project)
Konsist.scopeFromProject()
// 2. Retrieve class declarations
.classes()
// 3. Filter classes annotated with 'RestController'
.withAllAnnotationsOf(RestController::class)
// 4. Define the assertion
.assertTrue { it.resideInPackage("..controller..") }
}
}
```
--------------------------------
### Validate interfaces reside in a package with a specific segment
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/packageselector.md
Uses '..' as both a prefix and suffix to match any package path containing the specified segment.
```kotlin
Konsist
.scopeFromProject()
.interfaces()
.assertTrue { it.resideInPackages("..logger..") }
```
--------------------------------
### Verify class name
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-classes.md
Validates that a class name ends with a specific suffix.
```kotlin
...
.assertTrue {
it.hasNameEndingWith("Repository")
}
```
--------------------------------
### Verify interface methods
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-interfaces.md
Validates naming patterns for functions defined within an interface.
```kotlin
...
.functions()
.assertTrue {
it.hasNameStartingWith("Local")
}
```
--------------------------------
### Validate UseCase test existence with Konsist
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/kotest-snippets.md
Uses Konsist to verify that all classes ending in 'UseCase' have corresponding test classes.
```kotlin
class UseCaseTest : FreeSpec({
"UseCase has test class" {
Konsist
.scopeFromProject()
.classes()
.withNameEndingWith("UseCase")
.assertTrue(testName = this.testCase.name.testName) { it.hasTestClasses() }
}
})
```
--------------------------------
### Verify ViewModel Suffix
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/android-snippets.md
Ensures all classes inheriting from ViewModel follow the naming convention by ending with the 'ViewModel' suffix.
```kotlin
@Test
fun `classes extending 'ViewModel' should have 'ViewModel' suffix`() {
Konsist
.scopeFromProject()
.classes()
.withParentClassOf(ViewModel::class)
.assertTrue { it.name.endsWith("ViewModel") }
}
```
--------------------------------
### Verify companion object position
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/general-snippets.md
Checks that if a companion object exists in a class, it is the final declaration within that class.
```kotlin
@Test
fun `companion object is last declaration in the class`() {
Konsist
.scopeFromProject()
.classes()
.assertTrue {
val companionObject = it.objects(includeNested = false).lastOrNull { obj ->
obj.hasModifier(KoModifier.COMPANION)
}
if (companionObject != null) {
it.declarations(includeNested = false, includeLocal = false).last() == companionObject
} else {
true
}
}
}
```
--------------------------------
### Verify Function Name
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-functions.md
Validates that function names adhere to specific naming patterns.
```kotlin
...
.assertTrue {
it.hasNameStartingWith("get")
}
```
--------------------------------
### Verify property accessors
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-properties.md
Checks for the existence of getters or setters.
```kotlin
...
.assertTrue {
it.hasGetter
}
```
```kotlin
...
.assertTrue {
it.hasSetter
}
```
--------------------------------
### Verify interface name
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-interfaces.md
Validates that an interface name ends with a specific suffix.
```kotlin
..
.assertTrue {
it.hasNameEndingWith("Repository")
}
```
--------------------------------
### Define koTestName extension
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/kotest-support.md
Create a custom extension property on TestScope to simplify retrieving the Kotest test name.
```kotlin
val TestScope.koTestName: String
get() = this.testCase.name.testName
```
--------------------------------
### Integrate Architectural Checks in Tests
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/getting-started/getting-started/create-secound-konsist-test-architectural-check.md
Wrap Konsist architectural assertions within JUnit or Kotest test classes to automate validation during builds.
```kotlin
class ArchitectureKonsistTest {
@Test
fun `architecture layers have dependencies correct`() {
Konsist
.scopeFromProject()
.assertArchitecture {
private val presentationLayer = Layer("Presentation", "com.myapp.presentation..")
private val domainLayer = Layer("Domain", "com.myapp.business..")
private val dataLayer = Layer("Data", "com.myapp.data..")
// Define layer dependnecies
presentationLayer.dependsOn(domainLayer)
dataLayer.dependsOn(domainLayer)
domainLayer.dependsOnNothing()
}
}
}
```
```kotlin
class ArchitectureKonsistTest {
class UseCaseTest : FreeSpec({
"architecture layers have dependencies correct" {
Konsist
.scopeFromProject()
.assertArchitecture {
private val presentationLayer = Layer("Presentation", "com.myapp.presentation..")
private val domainLayer = Layer("Domain", "com.myapp.business..")
private val dataLayer = Layer("Data", "com.myapp.data..")
// Define layer dependnecies
presentationLayer.dependsOn(domainLayer)
dataLayer.dependsOn(domainLayer)
domainLayer.dependsOnNothing()
}
}
})
}
```
--------------------------------
### Declare an annotation class
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/features/declaration-vs-property.md
Defines a custom annotation class for use in the codebase.
```kotlin
annotation class CustomLogger
```
--------------------------------
### Configure assertion parameters
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/declaration-assert.md
Adjusts assertion behavior using strict mode or by providing additional failure messages.
```kotlin
Konist
.scopeFromProject()
.classes()
.assertFalse(strict = true) { ... }
```
```kotlin
Konist
.scopeFromProject()
.classes()
.assertFalse(additionalMessage = "Do X to fix the issue") { ... }
```
--------------------------------
### Slice KoScope
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/koscope.md
Filters an existing scope to retrieve a subset of files based on specific criteria.
```kotlin
// scope containing all files in the 'test' folder
koScope.slice { it.relativePath.contains("/test/") }
// scope containing all files in 'com.domain.usecase' package
koScope.slice { it.hasImport("com.domain.usecase") }
// scope containing all files in 'usecase' package and its sub-packages
koScope.slice { it.hasImport("usecase..") }
```
--------------------------------
### Verify UseCase Test Coverage
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/inspiration/snippets/clean-architecture-snippets.md
Ensures every class ending with 'UseCase' has a corresponding test class.
```kotlin
@Test
fun `every UseCase class has test`() {
Konsist
.scopeFromProduction()
.classes()
.withNameEndingWith("UseCase")
.assertTrue { it.hasTestClasses() }
}
```
--------------------------------
### Verify property annotations with assertFalse
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/writing-tests/assert.md
Verifies that none of the properties in the classes have the Inject annotation.
```kotlin
koScope
.classes()
.flatMap { it.properties() }
.assertFalse { it.hasAnnotationOf() }
```
--------------------------------
### Verify property name
Source: https://github.com/lemonappdev/konsist-documentation/blob/main/veryfying-codebase/verify-properties.md
Validates that Boolean properties follow the 'is' naming convention.
```kotlin
...
.assertTrue {
it.type?.name == "Boolean" && it.hasNameStartingWith("is")
}
```