Powermock-如何模拟特定方法并使对象的其余部分保持原样 [英] Powermock - how to mock a specific method and leave the rest of the object as-is
本文介绍了Powermock-如何模拟特定方法并使对象的其余部分保持原样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Person类,并为其设置了FirstName,LastName
I have a Person class with get set for FirstName, LastName
执行TestCase1的TestClass
A TestClass to execute TestCase1
我们可以只模拟一个特定的方法(getLastName)并保留其他所有内容(其他内部字段,函数...原样)吗?
Can we just only mock a specific method (getLastName) and leave every thing else (other internal fields, functions ... as-is)?
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
import static org.powermock.api.easymock.PowerMock.*;
import static org.easymock.EasyMock.expect;
@RunWith(PowerMockRunner.class)
@PrepareForTest ( {Person.class} )
public class TestClass {
@Test
public void TestCase1() {
Person person = createNiceMock(Person.class);
person.setFirstName = "First name";
expect(person.getLastName()).andReturn("Fixed value").anyTimes();
replayAll();
String ln = person.getLastName(); //will return "Fixed value";
String fn = person.getFirstName();
// Currently it returns null because of createNiceMock
// but I want it to return "First name" (value has been set to mock object)
// Is it possible?
verifyAll();
}
}
推荐答案
您可以使用间谍来模拟单个(包括私有)方法:
You can use spy to mock individual (including private) methods:
Person classUnderTest = PowerMockito.spy(new Person());
// use PowerMockito to set up your expectation
PowerMockito.doReturn("Fixed value").when(classUnderTest, "getLastName");
这篇关于Powermock-如何模拟特定方法并使对象的其余部分保持原样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文