[JAVA] MOCK constructors of other classes with Spring MVC + PowerMock + Junit

How to use PowerMock

Environmental information

domain/pom.xml(Excerpt)


		<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
		<dependency>
			<groupId>com.jcraft</groupId>
			<artifactId>jsch</artifactId>
			<version>0.1.54</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.powermock/powermock -->
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4-legacy</artifactId>
			<version>${powermock.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4</artifactId>
			<version>${powermock.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-mockito</artifactId>
			<version>${powermock.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4-rule</artifactId>
			<version>${powermock.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-classloading-xstream</artifactId>
			<version>${powermock.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

Test class


package training.domain.service;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CallJsch.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class CallJschTest {

	@Mock
	private JschTraining mock;

	@InjectMocks
	public CallJsch target = spy(new CallJsch());

	@Test
	public void test1() throws Exception {
		{
			MockitoAnnotations.initMocks(this);

			PowerMockito.whenNew(JschTraining.class).withAnyArguments().thenReturn(mock);
			PowerMockito.when(mock.exec(any())).thenReturn("SUCCESS");
		}

		target = new CallJsch();
		String str = target.call("root", "127.0.0.0", 22, "Administrator", 10);
		assertThat(str ,is("SUCCESS"));

	}

}

Test target


package training.domain.service;

import java.io.IOException;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

public class CallJsch {

	public String call(String user, String host, int port, String password, int timeout)
			throws JSchException, IOException, SftpException, Exception {
		JschTraining target = new JschTraining(user, host, port, password, timeout);
		return target.exec("ECHO TEST");
	}

}

Class called by the test target


package training.domain.service;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class JschTraining {

	JSch jsch;
	Session session;
	ChannelExec channel;

	public JschTraining(String user, String host, int port, String password, int timeout) throws JSchException {
		jsch = new JSch();
		session = jsch.getSession(user, host, port);
		// known_Skip hosts check
		session.setConfig("StrictHostKeyChecking", "no");
		session.setPassword(password);
		session.setTimeout(timeout);
		session.connect();
		channel = (ChannelExec) session.openChannel("exec");
	}

	public String exec(String command) throws JSchException, SftpException, FileNotFoundException, IOException {
		BufferedInputStream bin = null;
		ByteArrayOutputStream bout = null;
		try {
			channel.setCommand(command);
			channel.connect();

			//Command execution
			bin = new BufferedInputStream(channel.getInputStream());
			bout = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int length;
			while (true) {
				length = bin.read(buf);
				if (length == -1) {
					break;
				}
				bout.write(buf, 0, length);
			}
			//Standard output
			System.out.format("Execution result=%1$s", new String(bout.toByteArray(), StandardCharsets.UTF_8));
		} finally {
			if (bin != null) {
				try {
					bin.close();
				} catch (IOException e) {
				}
			}
			if (channel != null) {
				try {
					channel.disconnect();
				} catch (Exception e) {
				}
			}
			if (session != null) {
				try {
					session.disconnect();
				} catch (Exception e) {
				}
			}
		}
		return new String(bout.toByteArray(), StandardCharsets.UTF_8);
	}
}

point

@PrepareForTest (CallJsch.class) ← This is the class to be tested

@Mock private JschTraining mock; ← Here are other classes called by the test subject

Recommended Posts

MOCK constructors of other classes with Spring MVC + PowerMock + Junit
Test controller with Mock MVC in Spring Boot
Mock Enums with PowerMock
Java Config with Spring MVC
Mock static methods with PowerMock
Mock the constructor with PowerMock
Implement file download with Spring MVC
Test Spring framework controller with Junit
Implement image input / output with Spring MVC