IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 人工智能 -> PowerMock -> 正文阅读

[人工智能]PowerMock

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:以下是本篇文章正文内容,下面案例可供参考

1 PowerMock基本介绍

1.1 被测试类:

User.class

package com.lanshang.common;

public class User {
}


UserDao.class

package com.lanshang.helloworld.dao;

import com.lanshang.common.User;

public class UserDao {
    public void insertUser(User user){
        throw new UnsupportedOperationException();
    }

    public int getCount(){
        throw new UnsupportedOperationException();
    }
}

UserService.class

package com.lanshang.helloworld.service;

import com.lanshang.common.User;
import com.lanshang.helloworld.dao.UserDao;

public class UserService {
    private UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public void insertUser(User user){
        userDao.insertUser(user);
    }

    public int getCount(){
        return userDao.getCount();
    }
}

1.2 基本用法

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>powerMock_study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4 -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>1.6.5</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>1.6.5</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>
package com.lanshang.helloworld.service;

import com.lanshang.common.User;
import com.lanshang.helloworld.dao.UserDao;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;

import javax.annotation.processing.SupportedSourceVersion;

import static org.junit.Assert.*;

public class UserServiceTest {
    UserDao userDao;
    UserService userService;
    @Before
    public void init(){
        userDao = PowerMockito.mock(UserDao.class);
        userService = new UserService(userDao);
    }

    @Test
    public void testInsertUser() {
        PowerMockito.doNothing().when(userDao).insertUser(Mockito.anyObject());
        User user = new User();
        userService.insertUser(user);
        Mockito.verify(userDao,Mockito.times(1)).insertUser(user);
    }

    @Test
    public void testGetCount() {
        PowerMockito.when(userService.getCount()).thenReturn(2);
        int count = userService.getCount();
        assertEquals(2,count);
    }
}

2 Mock局部变量

2.1 要点

  • 要在测试类上加注释
    • @RunWith(PowerMockRunner.class)
    • @PrepareForTest({局部变量所在方法的类名.class})
    • PowerMockito.whenNew().withAnyArguments().thenReturn();

2.2 被测试基础类

UserDao.class

package com.lanshang.local.dao;

import com.lanshang.common.User;

public class UserDao {
    public void insertUser(User user){
        throw new UnsupportedOperationException();
    }

    public int getCount(){
        throw new UnsupportedOperationException();
    }
}

UserService.class

package com.lanshang.local.service;

import com.lanshang.common.User;
import com.lanshang.local.dao.UserDao;

public class UserService {

    public UserService() {

    }

    public void insertUser(User user){
        UserDao userDao = new UserDao();
        userDao.insertUser(user);
    }

    public int getCount(){
        UserDao userDao = new UserDao();
        return userDao.getCount();
    }
}

2.3 mock局部变量测试

package com.lanshang.local.service;

import com.lanshang.common.User;
import com.lanshang.local.dao.UserDao;
import org.junit.Before;
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.assertEquals;

@RunWith(PowerMockRunner.class)
@PrepareForTest({UserService.class})
public class UserServiceTest {
    private UserService userService;
    @Before
    public void init(){
        userService = new UserService();
    }

    @Test
    public void insertUser() {
        User user = new User();
        UserDao userDao = PowerMockito.mock(UserDao.class);
        try {
            PowerMockito.whenNew(UserDao.class).withAnyArguments().thenReturn(userDao);
            PowerMockito.doNothing().when(userDao).insertUser(Mockito.anyObject());
            userService.insertUser(user);
            Mockito.verify(userDao,Mockito.times(1)).insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void getCount() {
        UserDao userDao = PowerMockito.mock(UserDao.class);
        try {
            PowerMockito.whenNew(UserDao.class).withAnyArguments().thenReturn(userDao);
            PowerMockito.when(userService.getCount()).thenReturn(1);
            int count = userService.getCount();
            assertEquals(1,count);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3 Mock静态方法

3.1 要点

  • PowerMockito.mockStatic(UserDao.class);

3.2 被测试基础类

UserDao.class

package com.lanshang.mockstatic.dao;

import com.lanshang.common.User;

public class UserDao {
    public static void insertUser(User user){
        throw new UnsupportedOperationException();
    }

    public static int getCount(){
        throw new UnsupportedOperationException();
    }
}

UserService.class

package com.lanshang.mockstatic.service;

import com.lanshang.common.User;
import com.lanshang.mockstatic.dao.UserDao;

public class UserService {

    public void insertUser(User user){
        UserDao.insertUser(user);
    }

    public int getCount(){
        return UserDao.getCount();
    }
}

3.3 mock静态方法测试

package com.lanshang.mockstatic.service;

import com.lanshang.common.User;
import com.lanshang.mockstatic.dao.UserDao;
import org.junit.Before;
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.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({UserService.class,UserDao.class})
public class UserServiceTest {
    UserService userService;
    @Before
    public void init(){
        userService = new UserService();
    }

    @Test
    public void insertUser() {
        User user = new User();
        PowerMockito.mockStatic(UserDao.class);
        PowerMockito.doNothing().when(UserDao.class);
        userService.insertUser(user);
        //PowerMockito.verifyStatic();
        PowerMockito.verifyStatic(Mockito.times(1));
    }

    @Test
    public void getCount() {
        PowerMockito.mockStatic(UserDao.class);
        PowerMockito.when(UserDao.getCount()).thenReturn(1);
        int count = UserDao.getCount();
        assertEquals(1,count);
    }
}

4 Mock final修饰的类

4.1 要点

  • 如果需要Mock被final修饰的类的对象,用PowerMockito.mock()就好,其他用法与Mockito一样。

4.2 被测试基础类

UserDao.class

package com.lanshang.mockfinal.dao;

import com.lanshang.common.User;

public final class UserDao {
    public void insertUser(User user){
        throw new UnsupportedOperationException();
    }

    public int getCount(){
        throw new UnsupportedOperationException();
    }
}

UserService.class

package com.lanshang.mockfinal.service;

import com.lanshang.common.User;
import com.lanshang.mockfinal.dao.UserDao;

public class UserService {
    private UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public void insertUser(User user){
        userDao.insertUser(user);
    }

    public int getCount(){
        return userDao.getCount();
    }
}

4.3 mock final修饰的类

package com.lanshang.mockfinal.service;

import com.lanshang.common.User;
import com.lanshang.mockfinal.dao.UserDao;
import org.junit.Before;
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.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({UserDao.class,UserService.class})
public class UserServiceTest {

    @Test
    public void insertUser() {
        User user = new User();
        UserDao userDao = PowerMockito.mock(UserDao.class);
        UserService userService = new UserService(userDao);
        PowerMockito.doNothing().when(userDao).insertUser(Mockito.anyObject());
        userService.insertUser(user);
        Mockito.verify(userDao,Mockito.times(1)).insertUser(user);
    }

    @Test
    public void getCount() {
        UserDao userDao = PowerMockito.mock(UserDao.class);
        UserService userService = new UserService(userDao);
        PowerMockito.when(userDao.getCount()).thenReturn(1);
        int count = userService.getCount();
        assertEquals(1,count);
    }
}

5 Verify的使用

5.1 要点

  • Mockito.verify(userDao,Mockito.times(1)).insertUser(Mockito.anyObject());

5.2 被测试基础类

UserDao.class

package com.lanshang.verify.dao;

import com.lanshang.common.User;

public class UserDao {
    public void updateUser(User user){
        throw new UnsupportedOperationException();
    }

    public void insertUser(User user){
        throw new UnsupportedOperationException();
    }

    public int getUser(){
        throw new UnsupportedOperationException();
    }
}

UserService.class

package com.lanshang.verify.service;

import com.lanshang.common.User;
import com.lanshang.verify.dao.UserDao;

public class UserService {
    
    public void saveOrUpdate(User user){
        UserDao userDao = new UserDao();
        if(userDao.getUser()==0){
            userDao.insertUser(user);
        }else{
            userDao.updateUser(user);
        }

    }
}

5.3 测试类

package com.lanshang.verify.service;

import com.lanshang.common.User;
import com.lanshang.verify.dao.UserDao;
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.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({UserService.class})
public class UserServiceTest {

    @Test
    public void saveOrUpdate() {
        UserService userService = new UserService();
        UserDao userDao = PowerMockito.mock(UserDao.class);
        try {
            PowerMockito.whenNew(UserDao.class).withAnyArguments().thenReturn(userDao);
            PowerMockito.when(userDao.getUser()).thenReturn(0);
            userService.saveOrUpdate(new User());
            Mockito.verify(userDao,Mockito.times(1)).insertUser(Mockito.anyObject());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void saveOrUpdate1() {
        UserService userService = new UserService();
        UserDao userDao = PowerMockito.mock(UserDao.class);
        try {
            PowerMockito.whenNew(UserDao.class).withAnyArguments().thenReturn(userDao);
            PowerMockito.when(userDao.getUser()).thenReturn(1);
            userService.saveOrUpdate(new User());
            Mockito.verify(userDao,Mockito.times(1)).updateUser(Mockito.anyObject());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6 Mock构造函数

6.1 要点

  • PowerMockito.whenNew(UserDao.class).withArguments(username,password).thenReturn(userDao);
  • 注意PowerMockito.whenNew如果是指定参数的,那mock时指定的参数要与被测试方法里new对象的参数一致。

6.2 被测试基础类

UserDao.class

package com.lanshang.construction.dao;

public class UserDao {
    String username;
    String password;

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

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

    public int getCount(){
        throw new UnsupportedOperationException();
    }
}

UserService.class

package com.lanshang.construction.service;

import com.lanshang.construction.dao.UserDao;

public class UserService {

    public void insertUser(String username,String password){
        UserDao userDao = new UserDao(username,password);
        userDao.insertUser();
    }
}

6.3 mock构造函数

package com.lanshang.construction.service;

import com.lanshang.construction.dao.UserDao;
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.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({UserDao.class,UserService.class})
public class UserServiceTest {

    @Test
    public void insertUser() {
        String username="cat";
        String password="111";
        UserDao userDao = PowerMockito.mock(UserDao.class);
        try {
            PowerMockito.whenNew(UserDao.class).withArguments(username,password).thenReturn(userDao);
            PowerMockito.doNothing().when(userDao).insertUser();
            UserService userService = new UserService();
            userService.insertUser(username,password);
            Mockito.verify(userDao,Mockito.times(1)).insertUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

7 ArgumentMatcher的使用

7.1 要点

  • ArgumentMatcher用于简化多种mock when return。下例就是典型的用法。

7.2 被测试基础类

UserDao.class

package com.lanshang.matcher.dao;

public class UserDao {
    public String query(String name){
        throw new UnsupportedOperationException();
    }
}

UserService.class

package com.lanshang.matcher.service;

import com.lanshang.matcher.dao.UserDao;

public class UserService {
    UserDao userDao = new UserDao();

    public String query(String name){
        return userDao.query(name);
    }

}

7.3 使用ArgumentMatcher

package com.lanshang.matcher.service;

import com.lanshang.matcher.dao.UserDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Matchers;
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({UserService.class,UserDao.class})
public class UserServiceTest {

    @Test
    public void query() {
        UserDao userDao = PowerMockito.mock(UserDao.class);
        PowerMockito.when(userDao.query(Matchers.argThat(new MyArgumentMatcher()))).thenReturn("yes");
        UserService userService = new UserService();
        userService.userDao=userDao;
        assertEquals("yes",userService.query("aaa"));
        assertEquals("yes",userService.query("bbb"));
        assertEquals("yes",userService.query("ccc"));
    }

    static class MyArgumentMatcher extends ArgumentMatcher<String>{

        @Override
        public boolean matches(Object o) {
            String name =(String)o;
            switch (name){
                case "aaa":
                case "bbb":
                case "ccc":
                    return true;
                default:
                    return false;
            }
        }
    }
}

8 Answer的使用

8.1 要点

  • answer功能和matcher类似,是matcher的增强版。

8.2 被测试基础类

UserDao.class

package com.lanshang.answer.dao;

public class UserDao {
    public String query(String name){
        throw new UnsupportedOperationException();
    }
}

UserService.class

package com.lanshang.answer.service;

import com.lanshang.answer.dao.UserDao;

public class UserService {
    UserDao userDao = new UserDao();

    public String query(String name){
        return userDao.query(name);
    }

}

8.3 使用answer

package com.lanshang.answer.service;

import com.lanshang.answer.dao.UserDao;
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.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({UserService.class, UserDao.class})
public class UserServiceTest {

    @Test
    public void query() {
        UserDao userDao = PowerMockito.mock(UserDao.class);
        PowerMockito.when(userDao.query(Mockito.anyString())).then(invocation ->{
            String argument = (String) invocation.getArguments()[0];
            switch (argument){
                case "aaa":return "AAA";
                case "bbb":return "BBB";
                case "ccc":return "CCC";
                default:
                    return new RuntimeException(argument);
            }
        });
        UserService userService = new UserService();
        userService.userDao=userDao;
        assertEquals("AAA",userService.query("aaa"));
        assertEquals("BBB",userService.query("bbb"));
        assertEquals("CCC",userService.query("ccc"));
    }
}

9 Mock私有方法

9.1 要点

  • 用于处理同一个对象的公有方法调用私有方法。

9.2 被测试基础类

package com.lanshang.spy;

public class CheckService {
    public Boolean check(String name){
        return checkExist1(name);
    }

    public Boolean check1(){
        return checkExist();
    }

    public void check3(String name){
        checkExist2(name,"a");
    }

    private Boolean checkExist() {
        throw new UnsupportedOperationException();
    }

    private Boolean checkExist1(String name) {
        throw new UnsupportedOperationException();
    }

    private void checkExist2(String name,String passwoed) {
        throw new UnsupportedOperationException();
    }

}

9.3 mock私有方法

package com.lanshang.spy;

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.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({CheckService.class})
public class CheckServiceTest {

    //有返回值,带参数的私有方法
    @Test
    public void check() throws Exception {
        CheckService checkService = PowerMockito.spy(new CheckService());
        //下面这种写法不行,原因未明
        //PowerMockito.when(checkService,"checkExist1","a").thenReturn(true);
        PowerMockito.doReturn(true).when(checkService,"checkExist1","a");
        assertTrue(checkService.check("a"));
    }

    //有返回值,不带参数的私有方法
    @Test
    public void check1() throws Exception {
        CheckService checkService = PowerMockito.spy(new CheckService());
        PowerMockito.doReturn(true).when(checkService,"checkExist");
        assertTrue(checkService.check1());
    }

    //没有返回值的
    @Test
    public void check2() throws Exception {
        CheckService checkService = PowerMockito.spy(new CheckService());
        PowerMockito.doNothing().when(checkService).check3("name");
        checkService.check3("name");
        Mockito.verify(checkService,Mockito.times(1)).check3("name");
    }
}
  人工智能 最新文章
2022吴恩达机器学习课程——第二课(神经网
第十五章 规则学习
FixMatch: Simplifying Semi-Supervised Le
数据挖掘Java——Kmeans算法的实现
大脑皮层的分割方法
【翻译】GPT-3是如何工作的
论文笔记:TEACHTEXT: CrossModal Generaliz
python从零学(六)
详解Python 3.x 导入(import)
【答读者问27】backtrader不支持最新版本的
上一篇文章      下一篇文章      查看所有文章
加:2021-08-30 12:03:49  更:2021-08-30 12:04:29 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/1 12:27:44-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码