PowerMock笔记-构造函数


import lombok.Data;

/**
 * @author chenjianfei
 */
@Data
public class Employee {
    private String name;
    private Integer age;
}
public class EmployeeDao {
    private String username;
    private String password;

    public EmployeeDao(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public void insert() {
        throw new UnsupportedOperationException();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
public class EmployeeService {

    public void save(String username , String password){
        EmployeeDao employeeDao = new EmployeeDao(username,password);
        employeeDao.insert();
    }
}

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.fail;

/**
 * 通过构造参数传参
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(EmployeeService.class)
public class EmployeeServiceTest {
    @Test
    public void testSave() {
        try {
            EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class);
            String username = "andy";
            String password = "1234567";
            PowerMockito.whenNew(EmployeeDao.class).withArguments(username, password).thenReturn(employeeDao);
            PowerMockito.doNothing().when(employeeDao).insert();

            EmployeeService employeeService = new EmployeeService();
            employeeService.save(username,password);

            Mockito.verify(employeeDao).insert();
        } catch (Exception e) {
            fail();
        }

    }
}



你可能感兴趣的:(PowerMock)