• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
金大鑫要坚持
博客园    首页    新随笔    联系   管理    订阅  订阅

【dubbo】如何测试一个dubbo服务呢?

rpc服务框架——dubbo

https://cn.dubbo.apache.org/zh-cn/blog/2023/02/23/一文帮你快速了解-dubbo-核心能力/
自制项目:
https://github.com/Jinwenxin/rpc.git

1. 单元测试

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.;
import static org.junit.Assert.
;

public class MyDubboServiceTest {

@InjectMocks
private MyDubboService myDubboService;

@Mock
private DependencyService dependencyService;

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

@Test
public void testServiceMethod() {
    // Arrange
    when(dependencyService.someMethod()).thenReturn("Mocked Result");

// 当你这几个接口里,调用什么依赖的服务的方法,那么我们用这个句话让那个方法按照预期的返回,也就是假定依赖正常工作的情况下。

    // Act
    String result = myDubboService.serviceMethod();

    // Assert
    assertEquals("Expected Result", result);
}

}

2. 集成测试

import org.apache.dubbo.config.annotation.DubboReference;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
public class MyDubboServiceIntegrationTest {

@DubboReference
private MyDubboService myDubboService;

@Test
public void testServiceMethod() {
    String result = myDubboService.serviceMethod();
    assertEquals("Expected Result", result);
}

}
怎么理解这个和集成的区别呢?就是让dubbo接口去调用真实环境的依赖,而不是像单元测试中的mock。

3. 写个APIGateway项目(consumer)去测试

另外写一个项目,写个controller,方法中去调用dubbo service的API。
跟我在其他项目中去调用该服务是一样的。
package com.jinwenxin.controller;

import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.springboot.demo.DemoService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/anotherApi")
public class AnotherDubboController {

@DubboReference
private DemoService myDubboService;

@GetMapping("/serviceMethod/{param}")
public String callServiceMethod(@PathVariable String param) {
    return myDubboService.sayHello(param);
}

}
然后就可以在postman或者jmeter里发请求了。

posted @ 2024-05-31 15:39  金大鑫要坚持  阅读(261)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3