How to mock final classes on Kotlin using Mockito 2
One of the most common issues for Kotlin, as we talked about in a previous article, is that all classes and functions are closed by default.
This means that if you want to mock a class (something that may be quite common in Java testing), you need to either open it with the reserved keyword open
, or extract an interface.
Both options can be tedious, and the truth is that they are a limitation for Java developers that start using Kotlin.
Luckily, Mockito 2 has removed this restriction, and today I’m going to teach you how to do it.
What is the problem?
Imagine that you have a class in Kotlin that looks like this:
12345 | classClosedClass{fun doSomething(){}} |
And you want to test that its doSomething
method is called.
The way to do it would be the following:
Want to learn Kotlin?
Check my free guide to create your first project in 15 minutes!
12345 | @Test fun testClosedClass(){valc=Mockito.mock(ClosedClass::class.java)c.doSomething()verify(c).doSomething()} |
If you use Mockito 1.x, you’ll get the following error:
Mockito cannot mock/spy following:
– final classes
– anonymous classes
– primitive types
Update dependencies to Mockito 2
As we have said, Mockito 2 is able to mock it all, so we’re going to update the dependency. At the time of writing this article the latest version is 2.8.9. But check it out because they are updating very often lately.
1 | testCompile'org.mockito:mockito-core:2.8.9' |
So now we run our code again, but… it fails again!
Mockito cannot mock/spy because :
– final class
We’re no longer limited to mock anonymous classes or primitive types, but it’s not the same for final classes. Why is this?
This option is still a bit experimental, and requires a manual activation.
Enable the option to mock final classes
To do this, you’ll need to create a file in the test/resources/mockito-extensions
folder called org.mockito.plugins.MockMaker
:
It’s a simple text file, in which you have to write:
1 | mock-maker-inline |
Nothing else.
Now you can run the test again, and you’ll see that it runs smoothly. Great!
Mocking Properties
You can also mock properties with no issues. If we change the code of the class to this, for example:
12345 | classClosedClass(val prop:Int){fun doSomething(){}} |
Now let’s mock the value of the property:
1234567 | @Test fun testClosedClass(){valc=Mockito.mock(ClosedClass::class.java)`when`(c.prop).thenReturn(3)val prop=c.propassertEquals(3,prop)} |
I’m asking it to return 3 when it’s called, and later, I check that the value is correct.
You can also check that a property has been called with:
1 | verify(c).prop |
Conclusion
As you can see, all the limitations have disappeared thanks to the latest version of the most popular mocking library.
So excuses are over! You can now write all your tests using Kotlin.
And remember that you can find all this and much more in this free guide that will help you build your first project, or in the book where you can learn how to create a complete App from scratch.
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 mock final classes on Kotlin using Mockito 2
One of the most common issues for Kotlin, as we talked about in a previous article, is that all classes and functions are closed by default. This mea
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 fix yum errors on CentOS, RHEL or Fedora
http dsm list plain ... prop package cat cse Yum is a package management tool for installing, updating and removing rpm packages on Red
WPF:How to display a Bitmap on Image control
bug con 另一個 spa and maps api 如果 reat 一個Bitmap文件,叫做screenShotFile, 你可以這樣顯示到Image控件上。 BitmapImage bi = new BitmapImage();
How-to Install VMware Tools on Debian Stretch 9 32/64bit Linux+GNU
網絡配置 bsp install com tutorial des linux 虛擬機 top 在虛擬機VMWARE上安裝debian9 安裝vmwaretools時候遇到問題 詢問我IFCONFIG安裝在哪裏? 新版的debian不知道是用戶權限問題還是使用了其他網絡
[Selenium+Java] How to Upload & Download a File using Selenium Webdriver
HR erb 14. ava inter pub was cape googl Original source: https://www.guru99.com/upload-download-file-selenium-webdriver.html Uploadin
How to Install VMware Tools on RHEL 7/CentOS 7
advance paste rman rip prot disable features box etc The original address Mware Tools is one of important components for virtual mach
How to fix Error: listen EADDRINUSE while using nodejs
highlight nod node row light end eat test event If I run a server with the port 80, and I try to use xmlHTTPrequest i get this error: Err
How to increase JVM memory on Tomcat 8
https://docs.oracle.com/cd/E40520_01/integrator.311/integrator_install/src/cli_ldi_server_config.html Creating a setenv file It is
How To Add Swap Space on Ubuntu 16.04
Introduction One of the easiest way of increasing the responsiveness of your server and guarding against out-of-memory errors in applications is to ad
How to use common workflows on Amazon SageMaker notebook instances
Amazon SageMaker notebook instances provide a scalable cloud based development environment to do data science and machine learning. This blog post
How to Recreate the Banksy Artwork Shredder Using CSS Grid
On Friday, Banksy pranked the world again by shredding “Girl With Balloon” immediately after it fetched $1.4 million in auction. While everyone debates if
How to visualise the Global Exporting Network using NetworkX and D3
How to visualise the Global Exporting Network using NetworkX and D3Data-Driven Documents (D3) is a JavaScript library for building powerful graphics to com
How to run custom application on SONM
How to run custom application on SONMThis little guide will help experienced SONM users to run custom applications on SONM suppliers. If you don’t know any
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 list your cryptocurrency on exchange
How to list your cryptocurrency on exchangeSo one day you woke up with a plan of creating a new coin. Then somehow you’ve forked suitable codebase from Git
How to list your cryptocurrency on an exchange
How to list your cryptocurrency on an exchangeSo one day you woke up with a plan of creating a new coin. Then somehow you’ve forked suitable codebase from
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 train your own FaceID CNN using TensorFlow Eager execution
Faces are everywhere — from photos and videos on social media websites, to consumer security applications like the iPhone Xs FaceID.Computer vision, applie
How to Promote Your Bot on a Budget
How to Promote Your Bot on a BudgetChatbots are taking over the business world. Every month, people send more than a billion messages to businesses and org