Hi Konsist community! :wave: I have recently start...
# konsist
i
Hi Konsist community! 👋 I have recently started working with Konsist and loving it! However, I've stumbled upon one issue I cannot figure out so any help is very much appreciated. I have a ViewModel defined as:
Copy code
class MyViewModel(
    private val a: A?,
    backgroundCoroutineScope: BackgroundCoroutineScope,
) : ViewModel(viewModelScope = backgroundCoroutineScope.scope)
and a Unit test with Konsist:
Copy code
Konsist.scopeFromProject()
            .classes()
            .withParentOf(ViewModel::class)
            .withName { it.equals("MyViewModel", ignoreCase = true) }
            .withPrimaryConstructor()
            .properties()
            .print()
The
print
statement you see above, prints only
a
, but not
backgroundCoroutineScope
. I assume this is due to the
backgroundCoroutineScope
not being a var nor a val. Is there a way I can verify that this constructor property exists? Thank you 🙏
Additionally, is there a way to verify that a value from the primary constructor of my class is passed in to the super class constructor? In this case
backgroundCoroutineScope
is passed in to the ViewModel constructor.
v
This would find all of the fields that you need:
Copy code
Konsist.scopeFromProject()
    .classes()
    .withParentOf(ViewModel::class)
    .withName { it.equals("MyViewModel", ignoreCase = true) }
    .mapNotNull { it.primaryConstructor }
    .forEach {
        println("${it.parameters}")
    }
Result:
[a, backgroundCoroutineScope]
🙌 1
For your other question - I did not find a good solution myself, but for my own needs, I just used the raw
text
field of the declaration and parsed + asserted what I needed using String manipulation.
i
Thank you, it works! 🦠 I'll try your other suggestion as well.
v
But that other suggestion is very cumbersome and unstable 😄 E.g. in this case you'd get this whole line as a String:
Copy code
) : ViewModel(viewModelScope = backgroundCoroutineScope.scope)
And check appropriately. Even if you get it working:
Copy code
) : ViewModel(
    viewModelScope = backgroundCoroutineScope.scope)
)
Such formatting becomes an issue immediately.
i
Maybe using a regex would help? 😬 But yeah, I can see this solution being fragile