单元测试mockito使用

mockito单元测试

  • 1、引入maven依赖
  • 2、测试
    • 2.1、单元测试初始化
    • 2.2、测试类属性注入
    • 2.3、静态方法模拟
    • 2.4、模拟异常

1、引入maven依赖

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>4.4.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-inline</artifactId>
        <version>4.4.0</version>
        <scope>test</scope>
    </dependency>

2、测试

 @Autowired
    private UserMapper userMapper;

    @Value("${user.mockFlag}")
    private String mockFlag;

    @Override
    public User getUser(String userId) {
        try {
            if ("true".equals(mockFlag)){
                int a = 1/0;
                return null;
            }
            User user = userMapper.selectById(userId);
            return user;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }

2.1、单元测试初始化

@InjectMocks
private UserServiceImpl userService;

@Mock
private UserMapper userMapper;

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}

2.2、测试类属性注入

ReflectionTestUtils.setField(userService,"mockFlag","false");

2.3、静态方法模拟

//生成HttpUtil静态模拟类
MockedStatic<ClientUtil> clientUtilMockedStatic = mockStatic(ClientUtil.class);

clientUtilMockedStatic.when(() -> ClientUtil.doGet(any(),any(),any())).thenReturn("response结果");

//最后必须关闭静态模拟
clientUtilMockedStatic.close();

2.4、模拟异常

//方式1: selectById方法必须有返回值
when(userMapper.selectById(any())).thenThrow(InterruptedException.class);

//方式2: selectById方法有无返回值均可
doThrow(Exception.class).when(userMapper).selectById(any());

//测试被方法抛出异常需assert
assertThatThrownBy(() ->userService.getUser("1")).isInstanceOf(Exception.class);

//若被测试方法处理了异常,则无需assert
userService.getUser("1")

参考
Mockito单元测试:https://blog.csdn.net/qq_45950109/article/details/121273429

你可能感兴趣的:(java)