Is it reasonable to have a `@Composable` function ...
# compose
c
Is it reasonable to have a
@Composable
function with return type? I am trying to evaluate the feasibility to write JVM unit tests for them:
Copy code
@Composable
fun spanStyleRange(textAttribute: TextAttribute): AnnotatedString.Range<SpanStyle> {
    val spanStyle: SpanStyle = when (textAttribute.type) {
        TextAttributeType.HASHTAG ->
            SpanStyle(color = MaterialTheme.colors.primary, fontWeight = FontWeight.Bold)
        else -> SpanStyle()
    }
    return AnnotatedString.Range(
        item = spanStyle,
        start = textAttribute.start,
        end = textAttribute.start + textAttribute.length
    )
}
In thie example,
spanStyleRange
need to be annotated with
@Composable
because it is using
MaterialTheme.colors
d
Absolutely. If you couldn't do this, you wouldn't be able to refactor out code that doesn't show something on the screen. The guidelines say that composables that return a value (like say
remember
) should follow standard naming conventions. https://github.com/androidx/androidx/blob/androidx-main/compose/docs/compose-api-guidelines.md#naming-composable-functions-that-return-values
c
Thanks. I remember reading this coding guideline a few months back but forgot about this completely. Now my next question would be is there an easy way to write unit test for this
d
Probably not? Depends on what you mean by unit test
This is like a method on an activity, it requires a mocked or real whole Android device
So you'll need to test this in an integration test. The integration test can just call only that function though
c
What I meant was not an Android instrumentation test. The unit test I am looking forward is to run on Jvm.
a
you can do this but you'll probably want a non-
@Composable
overload that accepts a
MaterialColors
as a parameter and does the heavy lifting. That way you can more easily use and test the non-composable version with all of the logic, but the composable version without the parameter can be used as a convenience.
as for easy ways to write unit tests for these, we've got a number of utilities in the runtime for doing non-UI composable tests host-side like this one: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/[…]pose/runtime/CompositionTests.kt;l=3017?q=localRecomposerTest
not public in the test artifacts, but pretty short/simple to copy and use if you find them useful
c
Thanks for the great information. I will look into this
I had another case uses
ImageBitmap.Companion.imageResource
which is a top-level extension. It feels quite awkward to extract a non-
@Composable
function to accept
(@DrawableRes id) -> Unit
as a parameter.
158 Views