Powermock-如何模拟特定的方法并保持对象的其余部分不变



我有一个Person类,它为FirstName、LastName 设置了get

执行TestCase1 的TestClass

我们可以只模拟一个特定的方法(getLastName),而保留其他所有东西(其他内部字段、函数……原样)吗?

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();
    }
}

您可以使用spy来模拟单个(包括私有)方法:

Person classUnderTest = PowerMockito.spy(new Person());
    // use PowerMockito to set up your expectation
    PowerMockito.doReturn("Fixed value").when(classUnderTest, "getLastName");

相关内容

  • 没有找到相关文章

最新更新