[JAVA] Switched property files for development and production using JMockit

I touched J Mockit for the first time and tried various things, so a memo that I was able to double as a reminder ・ Java1.8 ・ Eclipse Oxygen (4.7.0) ・ Jmockit-1.33

Test class

import static org.junit.Assert.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.junit.Test;
import mockit.Invocation;
import mockit.Mock;
import mockit.MockUp;

public class PackagesTest {

	/**
	 *If nothing is Mocked
	 */
	@Test
	public void test_getData() {
		assertEquals("some_id"			,Packages.getData("id"));
		assertEquals("some_password"	,Packages.getData("password"));
	}

	/**
	 *When switching property files for testing, should I mess with the return value of load or inputstream?
	 */
	@Test
	public void test_getData_MockPath() {
		new MockUp<Properties>() {
			@Mock
			public void load(Invocation inv,InputStream inputStream) {
				InputStream inputStream2;
				try {
					inputStream2 = new FileInputStream("sample -copy.properties");
					inv.proceed(inputStream2);
					inputStream2.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		assertEquals("test_id"			,Packages.getData("id"));
		assertEquals("test_password"	,Packages.getData("password"));
	}

	/**
	 *Is it less burdensome to review by MockUp with literal value as it is on the code of the test unit?
	 */
	@Test
	public void test_getData_MockProperty() {
		new MockUp<Properties>() {
			@Mock
			public String getProperty(Invocation inv,String value) {
				switch (value){
				case "id":
					return "mock_string";
				default:
					return inv.proceed(value);
				}
			}
		};
		assertEquals("mock_string"		,Packages.getData("id"));
		assertEquals("some_password"	,Packages.getData("password"));
	}
}

Main class

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class Packages{

	public static void main(String[] args){
		System.out.println(getData("id"));
		System.out.println(getData("password"));
	}

	public static String getData(String arg) {
		String file = "sample.properties";
		String value = new String();
		Properties properties = new Properties();

		try {
			InputStream inputStream = new FileInputStream(file);
			properties.load(inputStream);
			inputStream.close();

			value = properties.getProperty(arg);

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return value;
	}
}

Recommended Posts

Switched property files for development and production using JMockit
[Java] Development with multiple files using package and import
[For myself] Browser display using JSP files and Servlet classes
Notes for reading and generating xlsx files from Java using Apache POI
Save files and folders using File Manager
Streamlining Web system development using docker-compose and Git