Last Updated: September 20, 2020

Nesting test cases with kotlin

Description: As features and requirements grows in our application, code and test cases grows hand in hand. It becomes very difficult to track the test cases with lots of them in single class. 

Consider a sample unit test class in Kotlin with bunch of test cases in single class

class ClientTest {

@Test
fun create(){
assert(true)
}
@Test
fun delete(){
assert(true)
}

@Test
fun connected(){
assert(true)
}

@Test
fun disconnected() {
assert(true)
}
}
fig.1

                                                        fig. 1

Well nothing wrong with test cases. 

Just imagine if you have 100+ tests within fig.1

By looking at fig.2 results it becomes difficult to figure out,

1. What exactly does these tests do ? or 

2. What's the logical connection within unit tests? etc 

That's where nesting comes useful for developers.

Consider a nesting sample with Kotlin

class ClientTest {

@Nested
inner class Operations{
@Test
fun create(){
assert(true)
}
@Test
fun delete(){
assert(true)
}
}

@Nested
inner class Client {
@Test
fun connected(){
assert(true)
}

@Test
fun disconnected(){
assert(true)
}
}
}

                                                   fig. 3

                                                     
                                                    fig. 4

We can now clearly make some distinction that, class in connecting to a client and doing some operations. (fig. 3 and fig. 4)

Although nesting is just a logical separation of test cases, it's very handy for developers in large scale projects.

For more updates follow us on -  Twitter

#codingIsAnArt #coderconsole