Adding a happy path test

Let's add a class that will contain our Functional Tests. We will call it SampleAppFT and put it in the chapter8 package of the test module:

Inside it, let's start by creating a class with two empty tests. We will implement those in a bit:

class SampleAppFT {

@Test
fun testHappyPath() = runBlocking {
// TODO: Implement a happy path test
}

@Test
fun testOppositeOrder() = runBlocking {
// TODO: Implement a test with an
// unexpected order of retrieva
l
}
}

Next to the SampleAppFT class, let's create a mock implementation of DataSource that fits the expected behavior when retrieving the information. In it, getting data from the database will be faster than the cache, which will be faster still than the external application:

// Mock a datasource that retrieves the data in the expected order
class MockDataSource: DataSource {
// Mock getting the name from the database
override fun getNameAsync(id: Int) = async {
delay(200)
"Susan Calvin"
}

// Mock getting the age from the cache
override fun getAgeAsync(id: Int) = async {
delay(500)
Calendar.getInstance().get(Calendar.YEAR) - 1982
}

// Mock getting the profession from an external system
override fun getProfessionAsync(id: Int) = async {
delay(2000)
"Robopsychologist"
}
}

With this mocked DataSource, we are able to complete our happy path test:

@Test
fun testHappyPath() = runBlocking {
val manager = UserManager(MockDataSource())

val user = manager.getUser(10)
assertTrue { user.name == "Susan Calvin" }
assertTrue { user.age == Calendar.getInstance().get(Calendar.YEAR) - 1982 }
assertTrue { user.profession == "Robopsychologist" }
}
assertTrue() is from the kotlin.test package.

By running this test—right-click on its name and select Run testHappyPath()—we will be able to assert that, under the expected timing, our UserManager behaves well:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225