EasyMock,PowerMockとともにmock静的方法static method

3377 ワード

どこでかばんをダウンロードするかは言わないで、いくつか降ります.
easymock-3.1
easymockclassextension-3.1
powermock-easymock-junit-1.5
 
後でmockされるクラスを作成し、Job
package com.jwu.mock;

import java.util.Random;

public class Job {

	public Job(String name) {
		this.name = name;
	}

	private String name;

	public String getName() {
		return name;
	}

	public static int generateId() {
		return new Random().nextInt(1000);
	}

}
 
後でテストするクラスを作成します.このテストされるクラスはmockされるクラスに使用する必要があります.Person
package com.jwu.mock;

public class Person {

	private int id;
	private String name;
	private Job job;

	public Person() {
		this(1, "noname", new Job("nojob"));
	}

	public Person(int id, String name, Job job) {
		this.id = id;
		this.name = name;
		this.job = job;
	}

	public String getJobName() {
		return job.getName();
	}

	public int getJobId() {
		return Job.generateId();
	}

	public String getJobNamePrefixId() {
		return getJobId() + getJobName();
	}

	public String toString() {
		return "#" + id + ": " + name;
	}
}
 
次にUTクラスを書き始めます.ここではEasyMockを使用してmockを除去する一般的な方法と、PowerMockを使用して静的方法をシミュレートする方法を示します.
package com.jwu.mock;

import static org.junit.Assert.assertEquals;

import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Job.class)
public class MockStaticTest {

	@Test
	public void testMockMethod() {
		Job job = EasyMock.createMock(Job.class);
		String jobName = "owen";
		EasyMock.expect(job.getName()).andReturn(jobName);
		EasyMock.replay(job);

		Person person = new Person(123, "testName", job);
		assertEquals(person.getJobName(), jobName);
	}

	@Test
	public void testStatic() {
		Job job = EasyMock.createMock(Job.class);
		int expectId = 1234;
		PowerMock.mockStatic(Job.class);
		EasyMock.expect(Job.generateId()).andReturn(expectId);
		PowerMock.replay(Job.class);

		Person person = new Person(123, "testName", job);

		assertEquals(person.getJobId(), expectId);
	}

	@Test
	public void testMix() {
		Job job = EasyMock.createMock(Job.class);
		int expectId = 1234;
		PowerMock.mockStatic(Job.class);
		EasyMock.expect(Job.generateId()).andReturn(expectId);
		PowerMock.replay(Job.class);
		String jobName = "owen";
		EasyMock.expect(job.getName()).andReturn(jobName);
		EasyMock.replay(job);

		Person person = new Person(123, "testName", job);

		assertEquals(person.getJobNamePrefixId(), expectId + jobName);
	}
}
 
 
特に何もなくて、ツールとかばんは見てすぐにできて、本当に重要なのはどのようにUTを設計することです.