How to make unit test on Android with Kotlin (KAD 22)
Of course, Kotlin also allows us to do unit tests in a very simple way, and very similar to what we’re used in Java.
There are some small complications when we use libraries like Mockito, but we’ll see some tricks to make it easier.
Unit tests in Kotlin
Although the subject of what a unitary test is always generates controversy, I won’t go into details here about this topic.
For our particular example, it’s enough to think that a unit test is a test that doesn’t need a device to run. The IDE will be able to execute them and display a result, identifying which ones were executed and which ones failed.
Configure Gradle
You need to add jUnit to your dependencies. It’s possible that, when you created the project, it was already be included by default. We’ll also add Mockito, as we’ll use it later:
12 | testCompile"junit:junit:4.12"testCompile"org.mockito:mockito-core:1.10.19" |
Create your first test
In the app/src/test
folder (you can create it if it doesn’t exist yet), you can create a new class called MyTest
1234567 | classMyTest{@Testfun testsWork(){assertTrue(true)}} |
Want to learn Kotlin?
Check my free guide to create your first project in 15 minutes!
As you can see, it’s very similar to what you’re used to in Java.
How to use Mockito
Mockito in Kotlin can be used like any other library, although it’s true that you could find some complications that you’ll need to solve.
12345678910 | @Test fun emptyDatabaseReturnsServerValue(){val db=Mockito.mock(ForecastDataSource::class.java)val server=Mockito.mock(ForecastDataSource::class.java)`when`(server.requestForecastByZipCode(any(Long::class.java),any(Long::class.java))).then{ForecastList(0,"city","country",listOf())}val provider=ForecastProvider(listOf(db,server))assertNotNull(provider.requestByZipCode(0,0))} |
You see, everything is very similar. You can create your mocks and use them seamlessly throughout the code. Although I’m not doing it here, you could also use ‘MockitoJUnitRunner’ and annotations.
The word when
is a reserved word in Kotlin, so you need to use inverted commas, or you could even rename the import
and give it the name you want:
1 | import org.mockito.Mockito.`when`as_when |
The problem arises when trying to mock types that don’t allow null values. Mockito by default gives null values to mocked objects, so sooner or later problems will arise.
A little trick is to use a library like mockito-kotlin, which instead of using nulls, will give specific values by default to each type, solving that problem. In addition, it provides other functions that take advantage of Kotlin’s power to make things simpler.https://antonioleiva.com/mockito-2-kotlin/
Another problem is that, by default, all classes and functions in Kotlin are closed, which means that they can’t be extended. This is a problem for Mockito, which won’t be able to mock them.
But that’s not an issue anymore, because Mockito 2 allows mocking final objects.
In an upcoming article we’ll see how to use it.
A little interesting thing
Kotlin allows us more flexibility than Java by naming functions. If we use inverted commas, we can put any text that comes to our mind.
This can be very useful for tests, where the most important thing is that the name of the test perfectly describes what you are doing, so as to be able to serve as specification.
Therefore, you can have a test that is named like this:
123 | @Test fun`test something works asexpected`(){Assert.assertTrue(false)} |
The best thing is that, apart from improving readability, it is also better understood in the output of the result when it fails. You’ll see the readable error more clearly.
If you use it on an Android project, you’ll see that it shows a Lint error indicating that methods on Android projects can’t have spaces. In my tests I haven’t noticed that this can be a problem. Gradle runs them without problem, so you can add an annotation to ignore the error.
In any case, remember to use this only for tests.
Conclusion
Although theoretically the testing tools that we use in Java should work without problems in Kotlin, it’s true that those that are based on reflection and add null to the code can give us problems.
Kotlin is very careful about nullity, and this can be a sticking point in some cases. But increasingly, there are more alternatives to do it in a simple way, and with Mockito 2 all those problems tend to disappear.
Apart from these small pitfalls, everything else works just as it would in Java.
I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.
SharesLike this:
Loading...Related
相關推薦
How to make unit test on Android with Kotlin (KAD 22)
Of course, Kotlin also allows us to do unit tests in a very simple way, and very similar to what we’re used in Java. There are some small complicatio
How to use Dagger 2 on Android with Kotlin (KAD 20)
Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later. Although there is some
How to use Retrofit on android with Kotlin (KAD 21)
This is just one more example about how in Kotlin we can continue to use the same libraries we’ve always used in Java for Android. Retrofit is a libr
How To Create Custom Dialog In Android With Validation
Let’s learn how to create custom dialog in android and while we are at it, let us also do simple validation of the data the user entered before clicking
How to do Deep Learning on Graphs with Graph Convolutional Networks
Observe that the weights (the values) in each row of the adjacency matrix have been divided by the degree of the node corresponding to the row. We apply th
How to create beautiful pipelines on Elixir with Opus
Use caseAt Quiqup, we have a business model that requires our drivers to perform different kinds of work. For example, depending on who is ordering, our dr
How To Make My Python Code Shorter With Function.
Python function is very important in structuring your code in a program. When it comes to writing a simple program, you can do it without functions, b
iOS: How To Make AutoLayout Work On A ScrollView
Posted on June 11th, 2014 Ok, I’ll admit. I’ve been seriously struggling with AutoLayout ever since it’s been introduced. I understand the concept, and
Custom Views in Android with Kotlin (KAD 06)
When we saw the article about classes, you may remember that in general only one constructor is used. This is a problem for creating custom views. Th
【 InkGenius】Good developers who are familiar with the entire stack know how to make life easier for those around
Good developers who are familiar with the entire stack know how to make life easier for those around
How to make your iOS apps more secure with SSL pinning
swift 和 obj-c 完成 ssl 的寫法如下: We can start by instantiating an NSURLSession object with the default session configuration. Swift self.urlSession = NSURLSes
How to make HTTP Post request with JSON body in Swift
Try this, // prepare json data let json: [String: Any] = ["title": "ABC", "dict": ["1":"First", "2":"Second"]] let jsonDat
How to make the impossible possible in CSS with a little creativity
CSS Previous sibling selectors don’t exist, but that doesn’t mean we can’t use themIf you ever used CSS sibling selectors, you know there’s only two. The +
How to make form submissions secure on an API website
Implementing forms on a Vue.js website? Having a readonly website is a piece of cake. Easy to develop using headless CMS, easy to maintain, and zero worrie
How to black box test a Go app with RSpec
Automated testing is all the rage in web development these days and goes on across the whole industry. A well-written test dramatically reduces the risk of
How to make onActivityResult get called on Nested Fragment
One of the common problem we always meet in the world of Fragment is: although we could call startActivityForResult directly from Nested
Listeners with several functions in Kotlin. How to make them shine?
One question I get often is how to simplify the interaction with listeners that have several functions on Kotlin. For listeners (or any interfaces) w
How to Make Blogging Easier with Artificial Intelligence
Mike Kaput is a senior consultant at PR 20/20 who is passionate about AI's potential to transform marketing. At PR 20/20, he creates measurable marketing r
How to Make Predictions with scikit
Tweet Share Share Google Plus How to predict classification or regression outcomes with scikit-l
How To Make A Swipeable Table View Cell With Actions – Without Going Nuts With Scroll Views
Make a swipeable table view cell without going nuts with scroll views! Apple introduced a great new user interface scheme in the iOS 7 Mail app – sw