springboot2.x版本PowerMockRunner和SpringBootTest单元测试

1.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.test</groupId>
    <artifactId>server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>server</name>
    <description>server for test</description>
    <properties>
        <java.version>1.8</java.version>
        <jacoco.dataFile>${project.build.directory}/coverage.exec</jacoco.dataFile>
    </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>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

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

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.7</version>
        </dependency>
        <dependency>
            <groupId>org.jacoco</groupId>
            <artifactId>org.jacoco.agent</artifactId>
            <version>0.8.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>objenesis</artifactId>
                    <groupId>org.objenesis</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.1</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>asm</artifactId>
                    <groupId>org.ow2.asm</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>commons-beanutils</artifactId>
                    <groupId>commons-beanutils</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>guava</artifactId>
                    <groupId>com.google.guava</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>swagger-models</artifactId>
                    <groupId>io.swagger</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>ch.netzwerg</groupId>
            <artifactId>paleo-core</artifactId>
            <version>0.10.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>javaslang</artifactId>
                    <groupId>io.javaslang</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.vavr</groupId>
            <artifactId>vavr</artifactId>
            <version>0.9.2</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.7</version>
                <configuration>
                    <includes>
                        <include>com/**/*</include>
                    </includes>
                    <excludes>
                        <exclude>com/test/demo/model/*</exclude>
                    </excludes>
                </configuration>
                <executions>
                    <execution>
                        <id>default-instrument</id>
                        <goals>
                            <goal>instrument</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>default-restore-instrumented-classes</id>
                        <goals>
                            <goal>restore-instrumented-classes</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.dataFile}</dataFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <argLine>-Dfile.encoding=UTF-8</argLine>
                    <testFailureIgnore>true</testFailureIgnore>
                    <systemPropertyVariables>
                        <jacoco-agent.destfile>${jacoco.dataFile}</jacoco-agent.destfile>
                    </systemPropertyVariables>
                    <skipTests>true</skipTests>
                    <includes>
                        <include>**/*Test.java</include>
                        <include>**/*Tests.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>report</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
        </plugins>
    </reporting>

</project>

2.springbootTest方式

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RcloneServiceTest {

    @Autowired
    private TestService  testService;
    
 private void printPrettyJson(Object object) {
        String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
        System.out.println(pretty);
    }


    @Test
    public void dirCopy() {
        DirCopyReq dirCopyReq = new DirCopyReq();
        dirCopyReq.setAsync(true);
        dirCopyReq.setCreateEmptySrcDirs(true);
        dirCopyReq.setSrcPath("minio:test/data1");
        dirCopyReq.setRemote("minio:test/data2");
        Long aLong = testService.dirCopy(dirCopyReq);
        System.out.println(aLong);
    }
  
 @Test
    public void listImagesTest() {
        JSONObject res = RestTemplateUtils.restGet("http://127.0.0.1:8888/images/json?all=true");
        if (res.getString("message").equals("success")) {
            JSONArray result = JSON.parseArray(res.getString("result"));
            System.out.println(result);
        } else {
            System.out.println(res.getString("message"));
        }
    }

    @Test
    public void connectNetworkTest() throws Exception {
        final String host = "127.0.0.1:8888";
        final String id = "network1";
        final String container = "renameTest001001";
        JSONObject result = testService.connectNetwork(host, id, container);
        printPrettyJson(result);
    }

}  

3.PowerMockRunner方式

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.test.demo.model.*")
public class RcloneServiceMock {

    @Mock
    private TestServiceImpl  testServiceImpl;
    
    @InjectMocks
    GroupsEntityServiceImpl groupsEntityService;

    @Mock
    GroupsEntityMapper groupsEntityMapper;

    @Mock
    HostEntityMapper hostEntityMapper;

    @Test
    public void addGroupsTest() {
        GroupsEntity groupsReq = new GroupsEntity();
        groupsReq.setName("name");
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("name", groupsReq.getName());
        List<GroupsEntity> groupsEntities = new ArrayList<>();
        PowerMockito.when(groupsEntityMapper.selectByMap(queryMap)).thenReturn(groupsEntities);
        groupsEntityService.addGroups(groupsReq);

        GroupsEntity groupsEntity = new GroupsEntity();
        groupsEntity.setName("name");
        groupsEntities.add(groupsEntity);
        PowerMockito.when(groupsEntityMapper.selectByMap(queryMap)).thenReturn(groupsEntities);
        groupsEntityService.addGroups(groupsReq);
    }

    @Test
    @SneakyThrows
    public void dirCopy() {
        DirCopyReq dirCopyReq = new DirCopyReq();
        dirCopyReq.setAsync(true);
        dirCopyReq.setCreateEmptySrcDirs(true);
        dirCopyReq.setSrcPath("minio:test/data1");
        dirCopyReq.setRemote("minio:test/data2");
        PowerMockito.when(testServiceImpl.dirCopy(dirCopyReq)).thenReturn(1L);
    }
    @Test
    public void findAllTest() {
        HostReq hostReq = new HostReq();
        hostReq.setName("name");
        hostReq.setUrl("url");
        hostReq.setTag("tag");
        hostReq.setGroups("groups");
        hostReq.setStatus((byte) 0);
        hostReq.setPageNum(1L);
        hostReq.setPageSize(5L);
        Page page = PowerMockito.mock(Page.class);
        QueryWrapper queryWrapper = PowerMockito.mock(QueryWrapper.class);
        try {
            PowerMockito.whenNew(Page.class).withArguments(hostReq.getPageNum(), hostReq.getPageSize()).thenReturn(page);
            PowerMockito.whenNew(QueryWrapper.class).withNoArguments().thenReturn(queryWrapper);
            PowerMockito.when(hostEntityMapper.selectPage(page, queryWrapper)).thenReturn(new Page());
        } catch (Exception e) {
            e.printStackTrace();
        }
        hostEntityService.findAll(hostReq);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值