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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot 3.x中进行单元测试的步骤如下: 1. 首先,在你的项目中,创建一个单元测试类。你可以通过在测试文件夹中创建一个新的Java类来完成这一步骤。 2. 在单元测试类中,添加所需的测试代码。你可以使用JUnit框架提供的断言方法来验证代码的正确性。你可以在测试方法上使用`@Test`注解来标记它们是测试方法。 3. 在单元测试类上,添加`@SpringBootTest`注解。这个注解告诉Spring Boot将运行这个测试类,并且会加载整个应用程序上下文。 4. 运行单元测试。你可以在你的开发环境中使用相应的工具或IDE来运行单元测试,也可以使用构建工具如Maven或Gradle来运行单元测试。 下面是一个简单的示例,展示了一个使用Spring Boot进行单元测试的类: ```java @SpringBootTest class MyUnitTest { @Autowired private MyService myService; @Test void testSomething() { // 测试代码 // 使用断言验证结果 assertEquals("expected", myService.doSomething()); } } ``` 在这个示例中,我们使用了`@SpringBootTest`注解来加载应用程序上下文,并使用`@Autowired`注解来注入需要测试的服务。然后,在`testSomething()`方法中,我们编写了测试代码,并使用`assertEquals()`方法进行断言验证。 注意,这只是一个简单的示例,你可以根据你的项目需求编写更复杂的单元测试。 总结起来,使用Spring Boot进行单元测试的步骤包括:创建单元测试类,添加测试代码,使用`@SpringBootTest`注解标记测试类,运行单元测试。记得在测试代码中使用断言方法来验证结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值