Powermockito和Mockito单元测试框架实战

本文详细介绍了PowerMockito和Mockito在单元测试中的应用,通过一个简单的Spring Boot应用展示了如何配置Maven依赖、创建Java代码以及编写单元测试。在测试中,注意到了对静态方法的模拟以及处理内部方法调用的策略,并强调了避免模拟私有方法的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Powermockito和Mockito之间的关系可以参考我的另一篇博客

Powermockito和Mockito测试框架分析以及一个简单的脚手架+单测的注意事项

2.maven依赖配置

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.19.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.java 代码准备

@Repository
public interface UserDAO {
    UserDTO getById(Long userId);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDTO {
    private Long userId;
    private String username;
}
@Service
public class UserService {
    @Resource
    private UserDAO userDAO;

    public UserDTO getById(Long userId) {
        if (Objects.isNull(userId) || userId == 0l) {
            return new UserDTO(1l, "zxliuyu");
        }
        return userDAO.getById(userId);
    }
     public UserDTO getByIdAllowException(Long userId) {
        if (Objects.isNull(userId) || userId == 0l) {
            throw new RuntimeException("用户Id不能为空");
        }

        return userDAO.getById(userId);
    }
    public UserDTO getByIdUseStaticMethod(Long userId) {
        userId = HttpClient.getUserId();
        return userDAO.getById(userId);
    }
    public UserDTO getByIdContainInternalCall(Long userId) {
        userId = getUserId();
        return userDAO.getById(userId);
    }

    public Long getUserId() {
        return 1l;
    }
}

4.单元测试代码

@RunWith(PowerMockRunner.class)
@PrepareForTest(HttpClient.class)
public class UserServiceTest {
    @InjectMocks
    private UserService userService;
    @Mock
    private UserDAO userDAO;
    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        PowerMockito.mockStatic(HttpClient.class);
    }

    @Test
    public void testGetByIdUserIdIsNull() {
        // Give
        Long userId = null;
        long expectedUserId = 1l;

        // When
        UserDTO user = userService.getById(userId);

        // Then
        Mockito.verify(userDAO, Mockito.times(0)).getById(any());
        Assertions.assertThat(user.getUserId()).isEqualTo(expectedUserId);
    }

    @Test
    public void testGetById() {
        // Give
        Long userId = 1l;
        long expectedUserId = 1l;

        // When
        when(userDAO.getById(any())).thenReturn(new UserDTO(1l, "zxliuyu"));
        UserDTO user = userService.getById(userId);

        // Then
        Mockito.verify(userDAO, Mockito.times(1)).getById(any());
        Assertions.assertThat(user.getUserId()).isEqualTo(expectedUserId);
    }

    @Test
    public void testGetByIdAllowExceptionUserIdIsNull() {
        // Give
        Long userId = null;

        // When
        exception.expect(RuntimeException.class);
        exception.expectMessage("用户Id不能为空");
        userService.getByIdAllowException(userId);

        // Then 如果是抛异常的可以没有then
    }

    @Test
    public void testGetByIdAllowException() {
        // Give
        Long userId = 1l;
        long expectedUserId = 1l;

        // When
        when(userDAO.getById(any())).thenReturn(new UserDTO(1l, "zxliuyu"));
        UserDTO user = userService.getByIdAllowException(userId);

        // Then
        Mockito.verify(userDAO, Mockito.times(1)).getById(any());
        Assertions.assertThat(user.getUserId()).isEqualTo(expectedUserId);
    }

    @Test
    public void testGetByIdUseStaticMethod() {
        // Give
        Long userId = 1l;
        long expectedUserId = 1l;

        // When
        when(userDAO.getById(any())).thenReturn(new UserDTO(1l, "zxliuyu"));
        when(HttpClient.getUserId()).thenReturn(userId);
        UserDTO user = userService.getByIdUseStaticMethod(userId);

        // Then
        Mockito.verify(userDAO, Mockito.times(1)).getById(any());
        Assertions.assertThat(user.getUserId()).isEqualTo(expectedUserId);
    }

    @Test
    public void testGetByIdContainInternalCall() {
        // Give
        Long userId = 1l;
        long expectedUserId = 1l;

        // When 如果出现方法内部调用,需要使用spy进行打桩,然后该类所有的方法都用打桩后的对象调用
        UserService userServiceSpy = PowerMockito.spy(userService);
        when(userDAO.getById(any())).thenReturn(new UserDTO(1l, "zxliuyu"));
        doReturn(userId).when(userServiceSpy).getUserId();
        UserDTO user = userServiceSpy.getByIdContainInternalCall(userId);

        // Then
        Mockito.verify(userDAO, Mockito.times(1)).getById(any());
        Assertions.assertThat(user.getUserId()).isEqualTo(expectedUserId);
    }
}

执行结果
在这里插入图片描述

5.注意事项

1.如果出现方法内部调用,需要使用spy进行打桩,然后该类所有的方法都用打桩后的对象调用

doReturn(userId).when(userServiceSpy).getUserId();

2.尽量不要mock使用私有方法,会有一些问题,如果私有方法需要单元测试,建议改成公共方法,加上VisibleForTesting代表这个方法是为了测试才改成公共方法

	@VisibleForTesting
    public Long getUserId() {
        return 1l;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

特特专属

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值