2026-06-24 f4bd1f3c89d906131495a0aca5aaf82966378510
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package cn.iocoder.yudao.module.iot.service.rule.data.action;
 
import cn.iocoder.yudao.module.iot.enums.rule.IotDataSinkTypeEnum;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.core.JdbcTemplate;
 
import javax.sql.DataSource;
 
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
 
/**
 * {@link IotDatabaseDataRuleAction} 的单元测试
 *
 * @author HUIHUI
 */
class IotDatabaseDataRuleActionTest {
 
    private IotDatabaseDataRuleAction databaseDataRuleAction;
 
    @Mock
    private JdbcTemplate jdbcTemplate;
 
    @BeforeEach
    public void setUp() {
        MockitoAnnotations.openMocks(this);
        databaseDataRuleAction = new IotDatabaseDataRuleAction();
    }
 
    @Test
    public void testGetType() {
        // 调用 & 断言:返回 Database 类型枚举值
        assertEquals(IotDataSinkTypeEnum.DATABASE.getType(), databaseDataRuleAction.getType());
    }
 
    @Test
    public void testCloseProducer_whenHikari() throws Exception {
        // 准备:底层是 HikariDataSource
        HikariDataSource hikari = mock(HikariDataSource.class);
        when(jdbcTemplate.getDataSource()).thenReturn(hikari);
 
        // 调用
        databaseDataRuleAction.closeProducer(jdbcTemplate);
 
        // 断言:HikariDataSource 被关闭
        verify(hikari, times(1)).close();
    }
 
    @Test
    public void testCloseProducer_whenNotHikari() throws Exception {
        // 准备:底层不是 HikariDataSource,避免误调 close
        DataSource other = mock(DataSource.class);
        when(jdbcTemplate.getDataSource()).thenReturn(other);
 
        // 调用 & 断言:不抛异常,且不会尝试关闭非 Hikari 数据源
        assertDoesNotThrow(() -> databaseDataRuleAction.closeProducer(jdbcTemplate));
        verifyNoInteractions(other);
    }
 
}