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里发请求了。