PowerMock笔记-Answer接口


import lombok.Data;

/**
 * @author chenjianfei
 */
@Data
public class Employee {
    private String name;
    private Integer age;
}
public class EmployeeDao {
    public String findByName(String name) {
        throw new UnsupportedOperationException();
    }
}
public class EmployeeService {

    public String find(String name) {
        EmployeeDao employeeDao = new EmployeeDao();
        return employeeDao.findByName(name);
    }
}
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.ArgumentMatchers;
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.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest(EmployeeService.class)
public class EmployeeServiceTest {

    @Test
    public void findByNameWithAnswer() {
        try {
            EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class);
            PowerMockito.whenNew(EmployeeDao.class).withAnyArguments().thenReturn(employeeDao);
            PowerMockito.when(employeeDao.findByName(Mockito.anyString())).then(invocation -> {
                String args = (String) invocation.getArguments()[0];
                switch (args) {
                    case "Jacky":
                        return "I am Jacky";
                    case "Andy":
                        return "I am Andy";
                    default:
                        throw new RuntimeException("Not Support:" + args);
                }
            });
            EmployeeService employeeService = new EmployeeService();
            Assert.assertEquals("I am Jacky",employeeService.find("Jacky"));
            Assert.assertEquals("I am Andy",employeeService.find("Andy"));

            try{
                String anyValue = employeeService.find("anyValue");
                Assert.fail();
            }catch (Exception e){
                Assert.assertTrue(e instanceof RuntimeException);
            }
        } catch (Exception e) {
            Assert.fail();
        }
    }
}




阅读更多

扫码向博主提问

去开通我的Chat快问

andy2019

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • Java后端开发
版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/Andy2019/article/details/80316054
个人分类: PowerMock
想对作者说点什么? 我来说一句

powerMock的测试样例集合

2015年07月27日 2.85MB 下载

powermock

2011年08月28日 1.8MB 下载

没有更多推荐了,返回首页

不良信息举报

PowerMock笔记-Answer接口

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭