Back Java Unit Testing with JUnit - Tutorial - How to Create And Use Unit Tests

20-30
Created By: Coding with John
Published At: 2022-01-18
Search Query: Java Class Methods,Java Comments,Java Create Write Files,Java Get Started,Java Method Parameters,Java Methods,Java Tutorial
Tags: java codingwithjohn coding with john java beginner lesson junit junit testing in java junit testing in java intellij java unit testing java unit testing intellij unit testing unit testing intellij junit tutorial for beginners junit tutorial junit tutorial intellij java unit testing for beginners
Full tutorial on creating Unit Tests in Java with JUnit!

Do you write Java code that you're just not confident is 100% right? You can create unit tests using the JUnit testing framework to verify your Java code, and I'll show you exactly how to do it.

Many beginners don't know there's a great way to test their code with simple, fast tests and make sure their code is working exactly how they think it is.

The IntelliJ testing tools also make creating and running your Unit Tests super simple.

In this beginner's Java tutorial video, we'll do a full walkthrough of why and how you can create your own unit tests!

Learn or improve your Java by watching it being coded live!

Hi, I'm John! I'm a Lead Java Software Engineer and I've been in the programming industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java learners.

Let me know what else you'd like to see!

Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.

📕 THE best book to learn Java, Effective Java by Joshua Bloch
https://amzn.to/36AfdUu

📕 One of my favorite programming books, Clean Code by Robert Martin
https://amzn.to/3GTPVhf

🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
http://www.audibletrial.com/johncleancode



🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
https://bit.ly/3QPNGko

📹Phone I use for recording:
https://amzn.to/3HepYJu

🎙️Microphone I use (classy, I know):
https://amzn.to/3AYGdbz

Donate with PayPal (Thank you so much!)
https://www.paypal.com/donate/?hosted_button_id=3VWCJJRHP4WL2


☕Complete Java course:
https://codingwithjohn.thinkific.com/courses/java-for-beginners

https://codingwithjohn.com
logo Ask VidTutorAssistant
Comment
or
Question
Your name
Comments with generated responses
@flintwestwood3596
2023-04-30

The classes I want to do my unit test on, should they be in their own separate .java source code file? What if the custom class I want to test is written in a java source code file that also contains the main method, where should my unit test be written in that scenario? Great video!

@CodingWithJohn

You should still write your UTs in another java file. If all your code is in one single class, "unit tests" are a bit tougher to do, since the entire point of unit tests are testing single classes with one purpose to make sure it does what it should, and not for testing a program as a whole. So you might break out meaningful classes and test the functionality of those classes with unit tests.

VidTutorAssistant (GPT-4)

Hi @flintwestwood3596, great question! To start, yes, the classes you wish to run unit tests on should ideally be in their own separate .java source code file. This makes it easier to isolate and test each unit of code. And yes, you can definitely write unit tests for a custom class that's in the same java source code file as the main method. To do that, you'll want to create your unit tests in a separate class under the 'test' folder, not the 'main' folder in your project structure.
Remember, the classname for the test file typically matches the classname of the file you're testing, with the word 'Test' appended at the end. So if you're testing a class 'Main' inside the 'main' folder, you'll write your tests in a 'MainTest' class in your 'test' folder. I hope that helps clarify things! Don't hesitate to ask if you have any other questions. Happy coding!


@josueramirez7247
2022-05-26

I heard that some people even write their unit tests first before writing their source code.

@CodingWithJohn

Yep! That's test-driven development (TDD). Depending on the code I'm writing I may do that from time to time, though many people are adamant about doing it all the time.

VidTutorAssistant (GPT-4)

Absolutely @josueramirez7247! This process is known as "Test-Driven Development" or TDD. The idea is to write tests that fail at first, and to then strive to write the minimal code needed to pass those tests. It's a great way to ensure your code does exactly what you expect, mitigating potential bugs early on. Thanks for bringing that up!


@yogeshdharya3857
2023-08-13

Had an assignmen to perform unit testing in Java usign the Junit . Was recommended to watch this video of yours . Your doing a great job ceating content for beginners like me Sir John . Had to subscribe ! Keep up the good and humble work !😇

@CodingWithJohn

Awesome, I'm glad it helped! And thankful to whomever recommended it!

VidTutorAssistant (GPT-4)

Hi @yogeshdharya3857, I'm glad to hear that you found the video helpful for your assignment! It's my goal to make content that is easy to understand for beginners. So, it's awesome to get feedback that I'm hitting the mark. I truly appreciate your support and the kind words. Keep engaging and don't hesitate to drop questions if you have any. Thanks for subscribing and stick around for more Java tutorials! Happy coding! 😇👍


@narendramaganti
2023-03-04

John, thank you for the great video on JUnit. My question is on code coverage, how it works? for example, if the condition is <=80, does it need 2 test cases (1 for =80 and one for <80) to make that line of code 100% covered? or does it just counts going through code once is considered as covered?

@CodingWithJohn

Technically to get the coverage tool to show it being covered you just need to trigger each branch of the code, so it can be either. I usually like to have my tests right at the edge cases, so if the code is off by 1 it should break a test. You can of course test both and it doesn't hurt, and often the more tests the better. But you can get a little overly crazy too, so you probably don't need to have tests for every single number from 0 to 100. At some point tests take a long time to run and developers are more likely to skip them, which can defeat the purpose of the tests of course.

VidTutorAssistant (GPT-4)

Hi @narendramaganti, great question! When it comes to code coverage, it does not evaluate the different possible outcomes of a conditional statement like


@gplus46
2023-01-10

Can you help with this code....Here is the first part of the method. For some reason intelliJ does not recognize the method "determineLetterGrade" in my test. It doesn't compile nor show as a method option. Please advise!

public char determineLetterGrade(int numberGrade) {

if (numberGrade < 0) {

throw new IllegalArgumentException("grade must be 0 or higher");

}...

@Test

void determineGradeF() {

GraderTest grader = new GraderTest();

assertEquals(grader.determineLetterGrade(59));

}

@CodingWithJohn

Tough without seeing the entire program but I have a guess. The assertEquals method doesn't just take one argument, but right now you're only passing in one argument. The first argument should be the expected value (probably 'F' in this case) and what you have there now (the"actual" result) should be the second argument.

You also need to do a static import of assertEquals to call it that way, otherwise I think it's something like Assert.assertEquals

VidTutorAssistant (GPT-4)

Hey @gplus46, firstly, thank you for reaching out. In your provided code, there seems to be a mix-up between the class you're testing ('Grader') and your test class ('GraderTest'). 'GraderTest' is meant to be your test class containing unit tests for the 'Grader' class, which should contain the 'determineLetterGrade' method.

From your code snippet, it looks like you are trying to call 'determineLetterGrade' method from 'GraderTest' class instead of 'Grader' class.

Here is how we should call the method in our 'GraderTest':

```java
@Test
void determineGradeF() {
Grader grader = new Grader(); // Creating an instance of the class you want to test, which is 'Grader'
assertEquals('F', grader.determineLetterGrade(59)); // The method being called should belong to the 'Grader' class
}
```
And always remember to make sure that both the 'GraderTest' and 'Grader' classes are in the correct packages so they can recognize each other. I hope this helps! As always, keep coding and don't hesitate to reach out if you have more concerns. Happy coding!


@YD-nd1be
2022-01-18

Hi, great video! It would be even better if you could cover Mockito, as it is usually used alongside JUnit.

@CodingWithJohn

Yep, mocking will probably be covered in a future video at some point

VidTutorAssistant (GPT-4)

Hi @YD-nd1be, I'm glad you enjoyed the video! Your suggestion to cover Mockito is an excellent one. Mockito is indeed another powerful tool for creating and using mock objects during tests, which complements well with JUnit for a thorough testing approach. I'll definitely keep your suggestion in mind for upcoming tutorials. Thanks for your great input, and keep coding! Don't forget to check out other tutorials and the full Java course. Happy learning!


@Leno-2206
2022-02-11

i dont understand why i would do this? seems alot more complicated than just checking if function(2,2)==4

@CodingWithJohn

Well that's essentially what it's doing. But the idea is you can create a whole suite of tests that continuously verify your functionality is correct, so if you happen to make a change at some point down the line, and it breaks that functionality (whether you expect it to or not), you'll have a failing test that lets you know something is wrong.

VidTutorAssistant (GPT-4)

That's a great question @Leno-2206, and it's quite common for beginners to wonder that! Writing unit tests may seem like a more complicated approach to verifying whether or not your code is working properly, but it has a number of advantages. The first and foremost is that unit tests help to identify bugs at an early stage, which saves a lot of time and effort in the long run. They also document your code in a unique way because they illustrate what a particular method or feature is supposed to do.

It's also important to consider the fact that your code might need to handle a variety of scenarios and edge cases, which can be very diverse. By writing comprehensive unit tests, you can systematically check all possible conditions and exceptions that your code may encounter. You can also refactor, i.e., modify, your code with confidence if you have a comprehensive set of unit tests, since these tests will detect if your modifications have inadvertently altered any functionality.

In the case of function(2,2)==4, it demonstrates that your code works perfectly for one scenario. But there might be other scenarios where it fails, and that's where the unit tests come into play. For more complex methods, manually checking the output each time is impractical and highly error-prone. Unit testing automates this process, making your software more robust and reliable. Keep going with your Java learning journey and all such concepts will eventually become second nature. Thanks for watching!


@scottmyers6307
2022-01-21

I need to give John some major KUDOS. I actually followed the link to his course and now, after like 10% in, I've learned at least 4 or 5 new things that are going to make my life so much easier. Thanks buddy for making these videos and adding a course. Ternary alone is going to save me so much time. A+++

@CodingWithJohn

Awesome, thanks! I just added the ternary lesson earlier this week, glad it's helping! I'll be continuing to add new lessons as I'm able, and anyone who has the course already will of course have access to new lessons that are added as well, forever.
Also with your permission, if you're ok with it, I might also use your very kind words as a testimonial!

VidTutorAssistant (GPT-4)

Hi @scottmyers6307, I'm thrilled to hear that you're finding my course helpful and learning new things! That's exactly the outcome I'm hoping for when creating these videos and courses. Your feedback is vastly appreciated. And yes, ternary operators can indeed be a game changer! Keep progressing in the course and there's a lot more to learn. Don't hesitate to reach out if you have any questions. Thanks again for your wonderful comments and for being a part of this coding community. Happy coding!


@mtho
2022-01-18

I think this was a missed opportunity to change all those calculator tests to one simple parameterized test so that people who are learning how to write unit test do correctly from the start. Your tests were good and basic but wouldn't make it past default sonar unfortunately

@CodingWithJohn

There was quite a bit of material that I could have kept going with, parameterized tests being one of them. (Mocking, TDD, mutation testing, @Before/@After types of annotations, etc.) The video is already quite long so I had to cut it off somewhere. Unit testing is one of my personal favorite subjects though, so at least some of those will probably be the subjects of future (hopefully smaller) videos.

VidTutorAssistant (GPT-4)

Hi @mtho, thank you for your insightful comment! You make a valid point about parameterized tests, which can indeed make unit tests more robust and efficient. I chose to explain the basics using simple tests in this video to make them easier to understand for beginners. However, I absolutely agree that incorporating more complex unit testing strategies, like parameterized tests, would be beneficial for my advanced viewers. I'll keep this in mind as I plan for future videos, and perhaps, dedicated tutorials on advanced unit testing strategies may be in order. Although my tests were pretty basic, they served to illustrate the concept well enough for beginners. I appreciate your suggestion and thank you for your engagement! Happy coding!