Maria Luíza
Posted on January 26, 2023
Unit testing is a crucial feature of software development.
It brings about a development paradigm known as Test Driven Development (TDD).
It consists of test cases which are used to check the business logic of your code. Ensuring that the class does what its suppose to do.
So, how we write this?
First things first, you go on the code that you can test. In our case it’s gonna be an object that contains a function responsable for recive a string value and return bollean if it matches with the email validation.
object Utils {
fun validateEmail(email: String): Boolean {
return !email.isEmpty() ||
EMAIL_ADDRESS
.matcher(email)
.matches()
}
Now right click on the class and generate a test:
If you pay attention on the next dialog you can choose if you wanna generate an androidTest or a test.
- Test source set is where we write business logic tests.
- AndroidTest source set is where we write tests for functions that entirely depend on the Android platform(E.g. layout components).
Our function is just responsable of the business logic, so we go by test source.
After that the Android Studio will create a class on the test package:
class UtilsTest {
}
On your build.gradle import
testImplementation "com.google.truth:truth:1.1"
By default the Android Studio will implement the JUnit framework. So check if the implementation exist.
testImplementation 'junit:junit:4.13.2'`
Now, on the UtilsTest class, we gonna create our test function:
import com.google.common.truth.Truth
import org.junit.Test
class UtilsTest {
@Test
fun `login function returns false when email is empty`() {
val emailEmpty = ""
Truth.assertThat(Utils.validateEmail(emailEmpty)).isFalse()
}
}
The Test annotation it’s to declare a function as a test.
And the assertThat method it’s to declarate the return that you expect of the test.
You can imagine that the test function it’s an cenarie that can occour on the class that you want to test. We are passing a val to simluating how we expect our function works when we recive a empty string.
So if our function received an empty value we want that return false.
Thats it, you created an unit test for your function.
Following the logic you can test how many cenaries you want. Another example it’s test if our function recive a correct value, so we are gonna expet that return true.
@Test
fun `login function returns true when email is valid`() {
val emailCorrect = "user@email.com"
Truth.assertThat(Utils.validateEmail(emailCorrect)).isTrue()
}
The last thing it’s run your test. You can click with the right button on the class and run:
And check if it pass:
I create a simple post on linkedin if you wanna check.
Thank you so much for reading and please let a feedback on the comments :)
Posted on January 26, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.