0

I am trying to test that a class that handles some animation change the value of a given object in x amount of milliseconds.

The test I want to do is "simple"

  1. check that after totalAnimationDuration / 2 the current value is bigger than the initial value
  2. check that after totalAnimationDuration the value is the one I wanted.

My test looks now something like this:

    fun start() {
        InstrumentationRegistry.getInstrumentation().runOnMainSync {
            val linearAnimation = LinearAnimation()
            linearAnimation.start("Name", 0f, 1f, ::setValueTester)
            Thread.sleep(2000)
            assertEquals(1, currentValue)
        }

    }

The problem I have if that Thread.sleep(2000)sleeps the test it self so the complete animation inside start happens after the sleep and assert

distante
  • 6,438
  • 6
  • 48
  • 90
  • Does this answer your question? [How to use JUnit to test asynchronous processes](https://stackoverflow.com/questions/631598/how-to-use-junit-to-test-asynchronous-processes) – Top-Master May 26 '22 at 12:43

3 Answers3

0

Try to use a Handler and postDelayed instead of Thread.sleep().

e.g.

Handler().postDelayed({
TODO("Do something")
}, 2000)
Felix
  • 284
  • 2
  • 12
0

You could add Awaitility to your project and express your expectation like the following:

fun start() {
    InstrumentationRegistry.getInstrumentation().runOnMainSync {
        val linearAnimation = LinearAnimation()
        linearAnimation.start("Name", 0f, 1f, ::setValueTester)
        await().atMost(5, SECONDS).until{ assertEquals(1, currentValue) }

    }

}

PS: Awaitility also provides a Kotlin DSL.

rieckpil
  • 10,470
  • 3
  • 32
  • 56
  • I would like to use this solution but sadly I can not add more dependencies to the project I am working at. – distante Nov 13 '20 at 09:06
0

The problem was that I was doing the sleep on the wrong thread. This is my working solution:

    fun start() {
        // Test Thread
        val linearAnimation = LinearAnimation()

        InstrumentationRegistry.getInstrumentation().runOnMainSync {    
        // Ui Thread
            linearAnimation.start("Name", 0f, 1f, ::setValueTester)
        }
        
        // Sleep the Test thread until the UI thread is done
        Thread.sleep(2000)
        assertEquals(1, currentValue)

    }
distante
  • 6,438
  • 6
  • 48
  • 90