Powermock - how to mock a specific method and leave the rest of the object as-is

一笑奈何 提交于 2019-12-20 05:18:06

问题


I have a Person class with get set for FirstName, LastName

A TestClass to execute TestCase1

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

回答1:


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");


来源:https://stackoverflow.com/questions/9305167/powermock-how-to-mock-a-specific-method-and-leave-the-rest-of-the-object-as-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!