eucalypto / learn

These are projects that help me learn
0 stars 0 forks source link

JUnit5 in an Android Project? #26

Open eucalypto opened 3 years ago

eucalypto commented 3 years ago

Out of the box, in Android you can use JUnit4.

But JUnit5 is a major evolution and I don't want to miss its power.

So how do I use JUnit5 in Android?

eucalypto commented 3 years ago

Android Studio tries to help. When you're in a class and go to the test "Ctrl+Shift+t" and there is no test it offers to make a new one. In this dialog you can select JUnit5 and it will give you the option to "Add JUnit5 to classpath" and indeed it will add testImplementation 'org.junit.jupiter:junit-jupiter' to the app gradle file. But it will not do the trick

This video shows how to get it to work: https://www.youtube.com/watch?v=IhPPDzNzJBQ

Android Studio's auto-fix does not include the version number in the generated junit-jupiter gradle file entry. You can add it manually, or go to Project Structure -> Dependencies -> app -> junit-jupiter:x.x.x in the list and select a version from the drop-down list of Requested Version

You have to be careful, because this might collide with existing JUnit4 implementation that you may have to remove. Also JUnit5 is not able to support instrumentation tests in androidTest so you may have to use JUnit4 there.

eucalypto commented 3 years ago

There is this 3rd party library:

android-junit5

That gives you JUnit5 in unit tests and an alpha version for instrumentation tests.

Now, with new gradle versions being able to natively support JUnit5, this library has less use cases. But apparently it's still great for instrumentation tests (that are still based on JUnit4 in Android)

eucalypto commented 3 years ago

https://vladsonkin.com/how-to-write-better-tests-with-junit-5-android/ Here's a nice Article describing the 2 biggest benefits of JUnit5 in Android over JUnit4