MockIto插桩常规单元测试

发布于:2024-08-14 ⋅ 阅读:(59) ⋅ 点赞:(0)

业务场景

针对MessageSendServiceImpl完成相关方法的单元测试用例

常规service方法

常规sercive方法 implements MessageSendService,没有继承MybatisServiceImpl,因为成员变量都是被final修饰,Test方法中通过new构造函数的方法完成注入

@Slf4j
@Service
@AllArgsConstructor
public class MessageSendServiceImpl implements MessageSendService {
    
    /**
     * 消息渠道管理服务.
     */
    private final MessagexxxManager messagexxManager;
    
    /**
     * 消息模板管理服务.
     */
    private final MessageyyeManager messageyyManager;
    
    /**
     * kafka操作template.
     */
    private final KafkaTemplate<String, String> kafkaTemplate;
    
   
    @Override
    public ApiResultDto<String> sendMessage(MessageSendDto messageSendDto) {
        log.info("receive a request to send message with parameter : {}", messageSendDto);
        
        // 必要参数非空验证.
        if (!necessaryNotNull(messageSendDto)) {
            return ApiResultDto.failed(ApiErrorCode.VALID_FAILED, "消息参数错误");
        }
        xxx
        return ApiResultDto.success(kafkaParam.getBatchId());
    }
}

单元测试

@Slf4j
@ExtendWith(MockitoExtension.class)
@SuppressWarnings("checkstyle:all")
class MessageSendServiceImplTest {
    
    /**
     * 消息渠道管理服务.
     */
    @Mock
    private MessagexxxManager messagexxxManager;
    
    /**
     * 消息模板管理服务.
     */
    @Mock
    private MessageyyyManager messageyyyManager;
    
    /**
     * kafka操作template.
     */
    @Mock
    private KafkaTemplate<String, String> kafkaTemplate;
   
    /**
     * 消息发送Service.
     */
    private MessageSendServiceImpl messageSendService;
 
    @BeforeEach
    void initialMessageSendService() {
        this.messageSendService = new MessageSendServiceImpl(messageChannelManager, messageTemplateManager, kafkaTemplate);
    }

      @Test
    @DisplayName("测试发送消息")
    void testSendByMessageId_Success_thirdParty() {
        // Arrange
        MessageChannelEntity messageChannel = JacksonUtils.tryStr2Bean("xxx", MessageChannelEntity.class);
        MessageTemplateEntity messageTemplate = JacksonUtils.tryStr2Bean("xx", MessageTemplateEntity.class);
        Mockito.doReturn(messageChannel).when(messageChannelManager).getById(any());
        Mockito.doReturn(messageTemplate).when(messageTemplateManager).getById(any());
        Mockito.doReturn(new ThirdPartyApiProcessor(apiCallService, callChainService)).when(processorFactory).getMessageProcessor(any());
        // Act
        MessageSendDto messageSendDto = getThirdPartyMessageSendDto();
        messageSendDto.setTemplateId(UUID.randomUUID());
        ApiResultDto<String> result = messageSendService.sendMessage(messageSendDto);
        // Assert
        assertThat(result.getEr()).isEqualTo(ApiErrorCode.SUCCESS.getCode());
    }
  }