[JAVA] How to execute and mock methods using JUnit

please note!

I leave it here for personal study purposes! I don't know if it will be helpful.

Target

: thinking: I'm in trouble with JUnit in the future : beginner: People who are new to JUnit : alarm_clock: JUnit hasn't been in a long time : disappointed_relieved: What is the mocking method? People

What you can expect from reading this article

(1) How to call the method (with sample source) (2) How to mock (with sample sauce) (3) A clear relationship between the test class and the test target class (with image)

It's a long time, but if you follow the order, will you be able to master (1) and (2)?

table of contents

·environment ・ (1) How to call the method (with sample source) ・ (2) How to mock (with sample sauce) ・ (3) Relationship between test class and test target class (with image) ・ Let's take a look at the test target class and the entire test class with explanations. ·Finally

environment

・ JUnit4 ・ Jmockit ・ Eclipse ・ Java SE5 (verified by SE7,8)

Automatic generation of test class

Here Was referred to

(1) How to call the method (with sample source)

▼ Code that calls the method

Method method =【name of the class】.class.getDeclaredMethod("[Method name]",[Argument type].class);
method.setAccessible(true);
method.invoke([Instance name],【argument】);

◆ Explanation 1st line: Describe the class, the method name to be executed, and the arguments (if any). For the argument, write the argument type such as "** String.class " or " int.class **". What you write is ** argument type **!

Second line: Determine if the method can be accessed. If this is true, both protected and private can be called from the outside and tested.

Line 3: Method executed by invoke. I will pass the argument that the instance was created here. You can do basic execution with this, but if you can't ** there is not enough information to call ** or ** it is missing at the callee **

Example)


//Instantiation of the class to be tested ... (A)
Test sample = new Test();

//Argument setting ... (B)
String moji = "Cat type robot";
int suuji = 2112903;

//Method execution ... (C)
Method method = Test.class.getDeclaredMethod("testMethod", String.class, int.class);
method.setAccessible(true);
method.invoke(sample, moji, suuji);

◆ Explanation (A): Instantiation of the class to be tested. This instance name is used at the bottom of (C).

(B): Define the arguments when executing the method here! Used at the bottom of (C).

(C): Since there are two arguments this time, two of "String.class" and "int.class" are described in the first line. Here ** add as many arguments **! Of course, ** not described for methods without arguments **! Describe the order in the order of the arguments of the method you want to test.

(2) How to mock (with sample sauce)

▼ Code to mock

new MockUp<【name of the class】>(){
	@Mock
[A solid description of the method you want to mock here]{
return [The items listed here will be returned];
* If it is void, there is no return.
	}
};

◆ Explanation Rather than explain, please copy and paste as it is and customize the inside of []. Let's see an example!

Example)

new MockUp<sample>(){
	@Mock
	public String testMethod(String moji, int suuji) {
		String result = "Hello, this is my Doraemon";
		return result ;
	}
};

◆ Explanation 1st line: Describe the test class in <> Line 2: @Mock is ready! So don't worry Line 3: ** Write down the method you want to test here! ** I will explain later! Lines 4 and 5: This is where the mock decides who will test what they want to return. In this case, let's return the value that will be returned from the testMethod method with "return"! And that.

(3) Relationship between test class and test target class (with image)

Eh, why do I have to prepare all the arguments in the test class? !! You can get the value because you are calling the method!

I had a lot of trouble thinking about it, so I made a diagram and understood it. (I'm sorry if it's difficult to understand because it's for personal memo purposes !!)

▼ Relationship that I thought at first JUnit理解001.PNG

I thought I was calling the class under test from the test class.

▼ Actually such a relationship JUnit理解002.PNG

It seems to be an image of sticking to the back. ** It's attached to the back = I have to pass the value **.

Let's take a look at the test target class and the entire test class with explanations

Let's learn JUnit in the wonderful scenery of the national anime Doraemon. (If you do something like this with your favorite thing, it will be unexpectedly good.)

[Test target class] ・Nobita.java ・Doraemon.java

[Test class] ・NobitaTest.java ・DoraemonTest.java

Nobita.java



package nobita;

import doraemon.Doraemon;

public class Nobita {

	public void NobitaHelp() {

		Doraemon dora = new Doraemon();

		int point = 0;
		System.out.println("Nobita "I got 0 points! Doraemon somehow!"");

		String GetTool = dora.help(point);

		if (GetTool != null) {
			System.out.println("Nobita "Hmm! I'm getting motivated!"");
		} else {
			System.out.println("Nobita "Suyaa ..."");
			System.out.println("Doraemon "Get up!"");
		}
	}
}


Doraemon.java



package doraemon;

public class doraemon {

	public String help(int point) {

		String tool = null;

		if (point == 0) {
			System.out.println("Doraemon "Well, you are ..."");
			tool = secretTool();
		} else {
			System.out.println("Doraemon "You did your best! I reviewed Nobita-kun"");
			return null;
		}
			return tool;
	}

	public String secretTool() {

		String secretTool = "Makeover fan";
		System.out.println("Doraemon "" + secretTool + "!」");
		return secretTool;
	}
}

▼ First of all, the test code of Nobita.java!

NobitaTest.java


package nobita;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import doraemon.doraemon;
import mockit.Mock;
import mockit.MockUp;

public class NobitaTest {

	/*****************************************
     *Testing the NobitaHelp method
     *throws are automatically imported so I don't care now!
     ******************************************/

	@Test
	public void test001_NobitaHelp() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

		Nobita nobi = new Nobita();

		new MockUp<doraemon>(){
			@Mock
			public String help(int point) {
// Nobita.Comment out the above process when executing a test that goes inside an if statement in java.
				String doraemonAction = "Makeover fan";
// Nobita.Comment out the following process when executing else test with java if statement.
				//String doraemonAction = null;
				return doraemonAction;
			}
		};

		Method method = Nobita.class.getDeclaredMethod("NobitaHelp");
		method.setAccessible(true);
		method.invoke(nobi);
		System.out.println("-----End of test-----");
	}
}

When I run JUnit,

** Nobita "I got 0 points! Doraemon somehow?" ** ** Nobita "Hmm! I'm getting motivated!" ** ** ----- End of test ----- **

If you get back like this, you're successful!

▼ Next, the test code of Doraemon.java

DoraemonTest.java



package doraemon;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder (MethodSorters.NAME_ASCENDING)
//↑ This one sentence tests in ascending order of method names and numbers in this test class. If this is not stated, the tests will be run separately.

public class DoraemonTest {

	/*****************************************
     *Help method test
     *throws are automatically imported so I don't care now!
     ******************************************/
	@Test
	public void test001_Help() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

		Doraemon dora = new Doraemon();

		int point = 0;

		Method method = Doraemon.class.getDeclaredMethod("help", int.class);
		method.setAccessible(true);
		method.invoke(dora, point);
		System.out.println("-----End of test-----");
	}

	/*****************************************
     *Testing the SecretTool method
     *throws are automatically imported so I don't care now!
     ******************************************/
	@Test
	public void test002_SecretTool() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Doraemon dora = new Doraemon();

		Method method = Doraemon.class.getDeclaredMethod("secretTool");
		method.setAccessible(true);
		method.invoke(dora);
		System.out.println("-----End of test-----");
	}
}

When I run JUnit,

** Doraemon "Well, you are ..." ** ** Doraemon "Transformation Fan!" ** ** ----- End of test ----- ** ** Doraemon "Transformation Fan!" ** ** ----- End of test ----- **

It's a success!

Finally

JUnit goes fast once you learn how to execute methods and mock them. (Experience story)

This article is for those who are in trouble because they will be doing JUnit in the future. Lol

Recommended Posts

How to execute and mock methods using JUnit
How to call classes and methods
How to execute a contract using web3j
How to use substring and substr methods
How to output Excel and PDF using Excella
How to play audio and music using javascript
[Ethereum] How to execute a contract using web3j-Part 2-
How to use JUnit 5
How to execute processing before and after docker-entrypoint.sh
How to access Java Private methods and fields
How to convert A to a and a to A using AND and OR in Java
How to create and execute method, Proc, Method class objects
How to use JUnit (beginner)
How to write Junit 5 organized
How to migrate from JUnit4 to JUnit5
[Creating] How to use JUnit
How to authorize using graphql-ruby
How to test including images when using ActiveStorage and Faker
How to separate words in names in classes, methods, and variables
[Rails] Differences between redirect_to and render methods and how to output render methods
How to set and describe environment variables using Rails zsh
How to mock some methods of the class under test
How to join a table without using DBFlute and sql
How to batch run JUnit and get coverage as well
How to use StringBurrer and Arrays.toString.
How to run JUnit in Eclipse
How to use EventBus3 and ThreadMode
How to use equality and equality (how to use equals)
How to connect Heroku and Sequel
How to convert LocalDate and Timestamp
How to use class methods [Java]
How to execute Ruby irb (interactive ruby)
How to build CloudStack using Docker
How to run a mock server on Swagger-ui using stoplight/prism (using AWS/EC2/Docker)
How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws
[Rails] How to upload images to AWS S3 using refile and refile-s3
How to sort a List using Comparator
How to test a private method in Java and partially mock that method
How to use OrientJS and OrientDB together
[Android] How to turn the Notification panel on and off using StatusBarManager
How to deploy to AWS using NUXTJS official S3 and CloudFront? With docker-compose
[Rails] How to upload images using Carrierwave
How to filter JUnit Test in Gradle
How to realize hybrid search using morphological analysis and Ngram with Solr
How to test private methods with arrays or variadic arguments in JUnit
[Java] How to calculate age using LocalDate
[Android] How to pass images and receive callbacks when sharing using ShareCompat
[Java] How to output and write files!
How to set up and use kapt
How to fix system date in JUnit
How to build SquashTM and how to support Japanese
How to find the tens and ones
Output using methods and constants Learning memo
[Easy] How to upgrade Ruby and bundler
How to test private scope with JUnit
[Swift5] How to implement animation using "lottie-ios"
How to implement image posting using rails
How to make asynchronous pagenations using Kaminari
Note: [Docker] How to start and stop
How to write and explain Dockerfile, docker-compose