当前位置: 首页 > 工具软件 > PowerMock > 使用案例 >

PowerMock代码

茅慈
2023-12-01

准备

  • 依赖
 	<properties>
        <java.version>1.8</java.version>
        <powermock.version>2.0.2</powermock.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--PowerMock-->

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>

        <!--<dependency>-->
            <!--<groupId>net.bytebuddy</groupId>-->
            <!--<artifactId>byte-buddy</artifactId>-->
            <!--<version>1.5.6</version>-->
        <!--</dependency>-->
        <!--<dependency>-->
            <!--<groupId>net.bytebuddy</groupId>-->
            <!--<artifactId>byte-buddy-agent</artifactId>-->
            <!--<version>1.5.6</version>-->
            <!--<scope>test</scope>-->
        <!--</dependency>-->
        <!-- https://mvnrepository.com/artifact/org.meanbean/meanbean -->
        <dependency>
            <groupId>org.meanbean</groupId>
            <artifactId>meanbean</artifactId>
            <version>2.0.3</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/nl.jqno.equalsverifier/equalsverifier -->
        <dependency>
            <groupId>nl.jqno.equalsverifier</groupId>
            <artifactId>equalsverifier</artifactId>
            <version>3.5.5</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>

    </dependencies>

domain

package cn.itcast.powermock.domain;

import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Objects;

/**
 * @ClassName: Student
 * @Auther: GZ
 * @Date: 2021/11/27 23:36
 * @Description:
 */

public class Student implements Serializable {
    private static final long serialVersionUID = 6170536066049208199L;
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

测试domain代码

package cn.itcast.powermock.domain;

import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class StudentTest {
    private Student student;
    private Student student1;

    @Before
    public void setUp() throws Exception {
        student = new Student();
        student.setName("Job");
        student.setAge(23);
        student1= new Student("1220499",29);
    }

    @Test
    public void beanIsSerializable() {
        //序列化,并行化
        final byte[] serializedMyBean = SerializationUtils.serialize(student);
        final Student deserializedMyBean =  SerializationUtils.deserialize(serializedMyBean);
        assertEquals(student, deserializedMyBean);
    }

    @Test
    public void getName() {
        String name = student.getName();
        assertEquals("Job",name);
    }

    @Test
    public void getAge() {
        int age= student.getAge();
        assertEquals(23,age);
    }

    @Test
    public void equalsAndHashCodeContract() throws Exception {
        EqualsVerifier.forClass(Student.class).suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS).verify();
    }
    @Test
    public void testtoString(){
        assertEquals("Student{name='Job', age=23}",student.toString());
    }


}

Service

package cn.itcast.powermock.service;

import cn.itcast.powermock.dao.StudentDao;
import cn.itcast.powermock.domain.Student;

/**
 * @ClassName: StudentService
 * @Auther: GZ
 * @Date: 2021/11/27 23:40
 * @Description:
 */

public class StudentService {
    private StudentDao studentDao;

    public StudentService(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    public int getTotalEmployee(){
        return studentDao.getTotal();
    }
}

测试代码Service

package cn.itcast.powermock.service;

import cn.itcast.powermock.dao.StudentDao;
import org.junit.Test;
import org.junit.platform.commons.util.StringUtils;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.mock;

@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*"})
@PrepareForTest({StringUtils.class})
@SpringBootTest()
public class StudentServiceTest {

    @Test
    public void getTotalEmployee() throws Exception {
        StudentDao studentDao = mock(StudentDao.class);
        PowerMockito.when(studentDao.getTotal()).thenReturn(10);
        StudentService studentService = new StudentService(studentDao);
        int total = studentService.getTotalEmployee();
        assertEquals(10, total);
    }

}

Utils

package cn.itcast.powermock.util;

/**
 * @ClassName: StudentUtils
 * @Auther: GZ
 * @Date: 2021/11/28 16:32
 * @Description:
 */

public class StudentUtils {
    public static void findAll(){
        throw new RuntimeException();
    }
}

测试用例 utils

package cn.itcast.powermock.util;

import cn.itcast.powermock.dao.StudentDao;
import org.junit.Before;
import org.junit.Test;
import org.junit.platform.commons.util.StringUtils;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.tests.utils.PowerMockTestNotifier;
import org.springframework.boot.test.context.SpringBootTest;

@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*"})
@PrepareForTest({StringUtils.class,StudentUtils.class})
@SpringBootTest()
public class StudentUtilsTest  {
//NoSuchMethodError
//    @Before
//    public void setUp() {
//       PowerMockito.mockStatic(StudentUtils.class);
//    }

    @Test(expected = RuntimeException.class)
    public void testFindall() {
       StudentUtils.findAll();
    }
}

dao

package cn.itcast.powermock.dao;

/**
 * @ClassName: StudentDao
 * @Auther: GZ
 * @Date: 2021/11/27 23:38
 * @Description:
 */

public class StudentDao {
    public int getTotal() {
        throw new UnsupportedOperationException();
    }
}

测试用例:dao

package cn.itcast.powermock.dao;
 
import org.junit.Test;

public class StudentDaoTest {
    
    @Test(expected = UnsupportedOperationException.class)
    public void getTotal() {
//        try {
//             new StudentDao().getTotal();
//           // fail("Expected an UnsupportedOperationException to be thrown");
//        } catch (UnsupportedOperationException e) {
//            e.printStackTrace();
//        }
        new StudentDao().getTotal();
    }
}

启动项

package cn.itcast.powermock;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PowermockApplication {

    public static void main(String[] args) {
        SpringApplication.run(PowermockApplication.class, args);
    }

}

测试用例:启动项

package cn.itcast.powermock;


import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.boot.test.context.SpringBootTest;
import sun.misc.JavaUtilZipFileAccess;

import java.sql.PreparedStatement;

@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*"})
@PrepareForTest({StringUtils.class})
@SpringBootTest
class PowermockApplicationTests {
    PowermockApplication powermockApplication;

    @Before
    public void setUp() {
        PowerMockito.mockStatic(PowermockApplication.class);
}

    @Test
    void contextLoadsMock() {
        PowerMockito.verifyStatic(PowermockApplication.class);
       PowermockApplication.main(new String[]{Mockito.anyString()});
    }
}


 类似资料: