Skip to content

Commit 707b301

Browse files
po-168Aias00
andauthored
[Improve]MotanServiceEventListenerTest case optimization(#5743) (#5745)
* [improve] code according to code specifications(#5725) * [Improve]Test case optimization(#5743) * [Improve]MotanServiceEventListenerTest case optimization(#5743) --------- Co-authored-by: aias00 <[email protected]>
1 parent 134b48d commit 707b301

File tree

2 files changed

+110
-83
lines changed

2 files changed

+110
-83
lines changed

shenyu-client/shenyu-client-motan/src/main/java/org/apache/shenyu/client/motan/MotanServiceEventListener.java

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,15 @@
1919

2020
import com.weibo.api.motan.config.springsupport.BasicServiceConfigBean;
2121
import com.weibo.api.motan.config.springsupport.annotation.MotanService;
22+
import java.lang.annotation.Annotation;
23+
import java.lang.reflect.Method;
24+
import java.util.ArrayList;
25+
import java.util.Arrays;
26+
import java.util.List;
27+
import java.util.Map;
28+
import java.util.Objects;
29+
import java.util.Optional;
30+
import java.util.stream.Collectors;
2231
import org.apache.commons.lang3.StringUtils;
2332
import org.apache.commons.lang3.tuple.Pair;
2433
import org.apache.shenyu.client.core.client.AbstractContextRefreshedEventListener;
@@ -39,25 +48,16 @@
3948
import org.springframework.context.ApplicationContext;
4049
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
4150
import org.springframework.core.annotation.AnnotatedElementUtils;
51+
import org.springframework.lang.NonNull;
4252
import org.springframework.lang.Nullable;
4353
import org.springframework.util.ReflectionUtils;
4454

45-
import java.lang.annotation.Annotation;
46-
import java.lang.reflect.Method;
47-
import java.util.ArrayList;
48-
import java.util.Arrays;
49-
import java.util.List;
50-
import java.util.Map;
51-
import java.util.Objects;
52-
import java.util.Optional;
53-
import java.util.stream.Collectors;
54-
5555
/**
5656
* Motan Service Event Listener.
5757
*/
5858
public class MotanServiceEventListener extends AbstractContextRefreshedEventListener<Object, ShenyuMotanClient> {
5959

60-
private static final String BASE_SERVICE_CONFIG = "baseServiceConfig";
60+
protected static final String BASE_SERVICE_CONFIG = "baseServiceConfig";
6161

6262
private final StandardReflectionParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new StandardReflectionParameterNameDiscoverer();
6363

@@ -128,7 +128,7 @@ protected Class<ShenyuMotanClient> getAnnotationType() {
128128

129129
@Override
130130
protected MetaDataRegisterDTO buildMetaDataDTO(final Object bean,
131-
final ShenyuMotanClient shenyuMotanClient,
131+
@NonNull final ShenyuMotanClient shenyuMotanClient,
132132
final String path,
133133
final Class<?> clazz,
134134
final Method method,
@@ -142,17 +142,7 @@ protected MetaDataRegisterDTO buildMetaDataDTO(final Object bean,
142142
Class<?>[] parameterTypesClazz = method.getParameterTypes();
143143
String parameterTypes = Arrays.stream(parameterTypesClazz).map(Class::getName)
144144
.collect(Collectors.joining(","));
145-
String serviceName;
146-
if (void.class.equals(service.interfaceClass())) {
147-
if (clazz.getInterfaces().length > 0) {
148-
serviceName = clazz.getInterfaces()[0].getName();
149-
} else {
150-
throw new ShenyuClientIllegalArgumentException("Failed to export remote service class " + clazz.getName()
151-
+ ", cause: The @Service undefined interfaceClass or interfaceName, and the service class unimplemented any interfaces.");
152-
}
153-
} else {
154-
serviceName = service.interfaceClass().getName();
155-
}
145+
String serviceName = getServiceName(clazz, service);
156146
String protocol = StringUtils.isNotEmpty(service.protocol()) ? service.protocol() : (getProtocolFromExport());
157147
return MetaDataRegisterDTO.builder()
158148
.appName(this.getAppName())
@@ -225,4 +215,19 @@ private String getProtocolFromExport() {
225215
}
226216
return "motan2";
227217
}
218+
219+
private String getServiceName(final Class<?> clazz, @Nullable final MotanService service) {
220+
String serviceName;
221+
if (void.class.equals(service.interfaceClass())) {
222+
if (clazz.getInterfaces().length > 0) {
223+
serviceName = clazz.getInterfaces()[0].getName();
224+
} else {
225+
throw new ShenyuClientIllegalArgumentException("Failed to export remote service class " + clazz.getName()
226+
+ ", cause: The @Service undefined interfaceClass or interfaceName, and the service class unimplemented any interfaces.");
227+
}
228+
} else {
229+
serviceName = service.interfaceClass().getName();
230+
}
231+
return serviceName;
232+
}
228233
}

shenyu-client/shenyu-client-motan/test/MotanServiceEventListenerTest.java renamed to shenyu-client/shenyu-client-motan/src/test/java/org/apache/shenyu/client/motan/MotanServiceEventListenerTest.java

Lines changed: 82 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -18,38 +18,44 @@
1818
package org.apache.shenyu.client.motan;
1919

2020
import com.weibo.api.motan.config.springsupport.BasicServiceConfigBean;
21+
import com.weibo.api.motan.config.springsupport.annotation.MotanService;
22+
import java.lang.annotation.Annotation;
23+
import java.lang.reflect.Method;
24+
import java.util.Collections;
25+
import java.util.HashMap;
26+
import java.util.LinkedHashMap;
27+
import java.util.Map;
28+
import java.util.Properties;
2129
import org.apache.shenyu.client.core.register.ShenyuClientRegisterRepositoryFactory;
2230
import org.apache.shenyu.client.motan.common.annotation.ShenyuMotanClient;
31+
import org.apache.shenyu.common.constant.Constants;
2332
import org.apache.shenyu.common.enums.RpcTypeEnum;
24-
import org.apache.shenyu.register.common.config.PropertiesConfig;
33+
import org.apache.shenyu.register.common.config.ShenyuClientConfig;
34+
import org.apache.shenyu.register.common.config.ShenyuClientConfig.ClientPropertiesConfig;
2535
import org.apache.shenyu.register.common.config.ShenyuRegisterCenterConfig;
2636
import org.apache.shenyu.register.common.dto.MetaDataRegisterDTO;
2737
import org.apache.shenyu.register.common.dto.URIRegisterDTO;
2838
import org.apache.shenyu.register.common.enums.EventType;
39+
import org.jetbrains.annotations.NotNull;
40+
import static org.junit.jupiter.api.Assertions.assertEquals;
41+
import static org.junit.jupiter.api.Assertions.assertNull;
2942
import org.junit.jupiter.api.Test;
3043
import org.junit.jupiter.api.extension.ExtendWith;
44+
import static org.mockito.BDDMockito.given;
3145
import org.mockito.InjectMocks;
3246
import org.mockito.Mock;
33-
import org.mockito.junit.jupiter.MockitoExtension;
34-
import org.springframework.context.ApplicationContext;
35-
import org.springframework.context.event.ContextRefreshedEvent;
36-
37-
import java.lang.reflect.Method;
38-
import java.util.HashMap;
39-
import java.util.Map;
40-
import java.util.Properties;
41-
42-
import static org.mockito.BDDMockito.given;
43-
import static org.junit.jupiter.api.Assertions.assertEquals;
44-
import static org.mockito.Mockito.doReturn;
47+
import static org.mockito.Mockito.mock;
4548
import static org.mockito.Mockito.times;
4649
import static org.mockito.Mockito.verify;
50+
import org.mockito.junit.jupiter.MockitoExtension;
51+
import org.springframework.context.ApplicationContext;
52+
import org.springframework.util.ReflectionUtils;
4753

4854
/**
4955
* Test for {@link MotanServiceEventListener}.
5056
*/
5157
@ExtendWith(MockitoExtension.class)
52-
public class MotanServiceEventListenerTest {
58+
public final class MotanServiceEventListenerTest {
5359

5460
private static final String CONTEXT_PATH = "/motan";
5561

@@ -77,12 +83,6 @@ public class MotanServiceEventListenerTest {
7783

7884
private static final String CONFIG_RULE_NAME = "configRuleName";
7985

80-
private static final String LOAD_BALANCE = "loadBalance";
81-
82-
private static final int RETRY_TIME = 0;
83-
84-
private static final int TIME_OUT = 0;
85-
8686
private static final boolean ENABLED = true;
8787

8888
@InjectMocks
@@ -98,16 +98,20 @@ public class MotanServiceEventListenerTest {
9898
private Method method;
9999

100100
@Mock
101-
private ServiceFactoryBean serviceFactoryBean;
102-
103-
@Mock
104-
private ContextRefreshedEvent contextRefreshedEvent;
101+
private BasicServiceConfigBean basicServiceConfigBean;
105102

106103
@Test
107104
public void testGetBeans() {
108-
motanServiceEventListener.getBeans(applicationContext);
109-
110-
verify(applicationContext, times(1)).getBeansOfType(ShenyuMotanclient.class);
105+
given(applicationContext.getBean(MotanServiceEventListener.BASE_SERVICE_CONFIG)).willReturn(basicServiceConfigBean);
106+
given(basicServiceConfigBean.getGroup()).willReturn("testGroup");
107+
Map<String, Object> mockBeans = new HashMap<>();
108+
mockBeans.put("bean1", new Object());
109+
given(applicationContext.getBeansWithAnnotation(ShenyuMotanClient.class)).willReturn(mockBeans);
110+
Map<String, Object> result = motanServiceEventListener.getBeans(applicationContext);
111+
112+
assertEquals(mockBeans, result);
113+
verify(applicationContext, times(1)).getBean(MotanServiceEventListener.BASE_SERVICE_CONFIG);
114+
verify(applicationContext, times(1)).getBeansWithAnnotation(ShenyuMotanClient.class);
111115
}
112116

113117
@Test
@@ -119,9 +123,10 @@ public void testBuildURIRegisterDTO() {
119123
.eventType(EventType.REGISTER)
120124
.host(HOST)
121125
.port(Integer.parseInt(PORT))
126+
.namespaceId(Constants.SYS_DEFAULT_NAMESPACE_ID)
122127
.build();
123-
Map<String,Object> beans = new HashMap<>();
124-
URIRegisterDTO realURIRegisterDTO = motanServiceEventListener.buildURIRegisterDTO(applicationContext, beans);
128+
Map<String, Object> beans = new HashMap<>();
129+
URIRegisterDTO realURIRegisterDTO = motanServiceEventListener.buildURIRegisterDTO(applicationContext, beans, Constants.SYS_DEFAULT_NAMESPACE_ID);
125130

126131
assertEquals(expectedURIRegisterDTO, realURIRegisterDTO);
127132
}
@@ -164,41 +169,32 @@ public void testGetAnnotationType() {
164169

165170
@Test
166171
public void testBuildMetaDataDTOForMotan() throws NoSuchMethodException {
167-
168-
Method method = MotanServiceEventListener.class.getDeclaredMethod(METHOD_NAME, ApplicationContext.class, Map.class);
169-
170-
171172
given(shenyuMotanClient.desc()).willReturn(DESC);
172173
given(shenyuMotanClient.ruleName()).willReturn(CONFIG_RULE_NAME);
173174
given(shenyuMotanClient.enabled()).willReturn(ENABLED);
174-
given(shenyuMotanClient.loadBalance()).willReturn(LOAD_BALANCE);
175-
given(shenyuMotanClient.retries()).willReturn(RETRY_TIME);
176-
given(shenyuMotanClient.timeout()).willReturn(TIME_OUT);
177-
178-
179-
BasicServiceConfigBean basicServiceConfigBean = mock(BasicServiceConfigBean.class);
180175
given(basicServiceConfigBean.getRequestTimeout()).willReturn(1000);
181-
given(applicationContext.getBean(BASE_SERVICE_CONFIG)).willReturn(basicServiceConfigBean);
182-
183-
184-
String expectedParameterTypes = "org.springframework.context.ApplicationContext,java.util.Map,com.alipay.motan.runtime.spring.factory.Object";
185-
String expectedPath = "/motan/findByIdsAndName/path";
186-
String expectedRpcExt ="{\"loadbalance\":\"loadBalance\",\"retries\":0,\"timeout\":0}";
187-
188-
176+
given(applicationContext.getBean(MotanServiceEventListener.BASE_SERVICE_CONFIG)).willReturn(basicServiceConfigBean);
177+
178+
final String expectedParameterTypes = "org.springframework.context.ApplicationContext,java.util.Map,java.lang.String";
179+
final String expectedRpcExt = "{\"methodInfo\":[{\"methodName\":\"buildURIRegisterDTO\","
180+
+ "\"params\":[{\"left\":\"org.springframework.context.ApplicationContext\",\"right\":\"context\"},"
181+
+ "{\"left\":\"java.util.Map\",\"right\":\"beans\"},{\"left\":\"java.lang.String\",\"right\":\"namespaceId\"}]}],\"timeout\":1000,\"rpcProtocol\":\"motan2\"}";
182+
Method method = MotanServiceEventListener.class.getDeclaredMethod(METHOD_NAME, ApplicationContext.class, Map.class, String.class);
183+
189184
MetaDataRegisterDTO realMetaDataRegisterDTO = motanServiceEventListener.buildMetaDataDTO(
190-
Object,
185+
null,
191186
shenyuMotanClient,
192187
SUPER_PATH_NOT_CONTAINS_STAR,
193-
MotanServiceEventListener.class,
194-
method);
188+
MockMotanServiceClass.class,
189+
method,
190+
Constants.SYS_DEFAULT_NAMESPACE_ID);
195191

196192
MetaDataRegisterDTO expectedMetaDataRegisterDTO = MetaDataRegisterDTO.builder()
197193
.appName(APP_NAME)
198194
.serviceName(SERVICE_NAME)
199195
.methodName(METHOD_NAME)
200196
.contextPath(CONTEXT_PATH)
201-
.path(expectedPath)
197+
.path(SUPER_PATH_NOT_CONTAINS_STAR)
202198
.port(Integer.parseInt(PORT))
203199
.host(HOST)
204200
.ruleName(CONFIG_RULE_NAME)
@@ -207,6 +203,7 @@ public void testBuildMetaDataDTOForMotan() throws NoSuchMethodException {
207203
.rpcType(RpcTypeEnum.MOTAN.getName())
208204
.rpcExt(expectedRpcExt)
209205
.enabled(ENABLED)
206+
.namespaceId(Constants.SYS_DEFAULT_NAMESPACE_ID)
210207
.build();
211208

212209
assertEquals(expectedMetaDataRegisterDTO, realMetaDataRegisterDTO);
@@ -217,16 +214,16 @@ public void testBuildMetaDataDTOForMotan() throws NoSuchMethodException {
217214
@Test
218215
public void testBuildApiPathSuperPathContainsStar() {
219216
given(method.getName()).willReturn(METHOD_NAME);
220-
String realApiPath = motanServiceEventListener.buildApiPath(method, SUPER_PATH_CONTAINS_STAR, methodShenyuClient);
217+
String realApiPath = motanServiceEventListener.buildApiPath(method, SUPER_PATH_CONTAINS_STAR, shenyuMotanClient);
221218
String expectedApiPath = "/motan/demo/buildURIRegisterDTO";
222219

223220
assertEquals(expectedApiPath, realApiPath);
224221
}
225222

226223
@Test
227224
public void testBuildApiPathSuperPathNotContainsStar() {
228-
given( methodShenyuClient.path()).willReturn(PATH);
229-
String realApiPath = motanServiceEventListener.buildApiPath(method, SUPER_PATH_NOT_CONTAINS_STAR, methodShenyuClient);
225+
given(shenyuMotanClient.path()).willReturn(PATH);
226+
String realApiPath = motanServiceEventListener.buildApiPath(method, SUPER_PATH_NOT_CONTAINS_STAR, shenyuMotanClient);
230227
String expectedApiPath = "/motan/findByIdsAndName/path";
231228

232229
assertEquals(expectedApiPath, realApiPath);
@@ -242,15 +239,40 @@ private MotanServiceEventListener buildMotanServiceEventListener() {
242239
properties.setProperty("username", USERNAME);
243240
properties.setProperty("password", PASSWORD);
244241
properties.setProperty("appName", APP_NAME);
245-
PropertiesConfig config = new PropertiesConfig();
242+
ClientPropertiesConfig config = new ClientPropertiesConfig();
246243
config.setProps(properties);
247244

248-
ShenyuRegisterCenterConfig mockRegisterCenter = new ShenyuRegisterCenterConfig();
249-
mockRegisterCenter.setServerLists("http://localhost:58080");
250-
mockRegisterCenter.setRegisterType("http");
251-
mockRegisterCenter.setProps(properties);
245+
ShenyuRegisterCenterConfig shenyuRegisterCenterConfig = new ShenyuRegisterCenterConfig();
246+
shenyuRegisterCenterConfig.setServerLists("http://localhost:58080");
247+
shenyuRegisterCenterConfig.setRegisterType("http");
248+
shenyuRegisterCenterConfig.setProps(properties);
249+
ShenyuClientConfig clientConfig = new ShenyuClientConfig();
250+
Map<String, ShenyuClientConfig.ClientPropertiesConfig> client = new LinkedHashMap<>();
251+
client.put(RpcTypeEnum.MOTAN.getName(), config);
252+
clientConfig.setClient(client);
253+
return new MotanServiceEventListener(clientConfig, ShenyuClientRegisterRepositoryFactory.newInstance(shenyuRegisterCenterConfig));
254+
}
252255

253-
return new MotanServiceEventListener(config, ShenyuClientRegisterRepositoryFactory.newInstance(mockRegisterCenter));
256+
@Test
257+
public void testBuildApiDocSextet() throws NoSuchMethodException {
258+
Method method = MockShenyuMotanClientClass.class.getDeclaredMethod("mockMethod");
259+
ReflectionUtils.makeAccessible(method);
260+
assertNull(motanServiceEventListener.buildApiDocSextet(method, mock(Annotation.class), Collections.emptyMap()));
254261
}
255262

263+
@ShenyuMotanClient
264+
private static class MockShenyuMotanClientClass {
265+
public void mockMethod() {
266+
267+
}
268+
}
269+
270+
271+
@MotanService(interfaceClass = Comparable.class)
272+
private class MockMotanServiceClass implements Comparable {
273+
@Override
274+
public int compareTo(@NotNull final Object o) {
275+
return 0;
276+
}
277+
}
256278
}

0 commit comments

Comments
 (0)