You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shenyu.apache.org by xi...@apache.org on 2021/08/31 07:59:50 UTC
[incubator-shenyu] branch master updated: [ISSUE #1930] Optimize
Exception printing in unit test. (#1970)
This is an automated email from the ASF dual-hosted git repository.
xiaoyu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-shenyu.git
The following commit(s) were added to refs/heads/master by this push:
new 9f2122f [ISSUE #1930] Optimize Exception printing in unit test. (#1970)
9f2122f is described below
commit 9f2122f16e1960aa2731812697bab060844fee7b
Author: ttttangzhen <28...@qq.com>
AuthorDate: Tue Aug 31 15:59:40 2021 +0800
[ISSUE #1930] Optimize Exception printing in unit test. (#1970)
* admin test code polish
* admin test code polish
* admin test code polish
* client test code polish
* web test code polish
* fix ci
* fix ci
* fix ci
* try again fix ci
* try again fix ci
* try again fix ci
* try again fix ci
* try again fix ci
* try again fix ci
* try again fix ci
---
pom.xml | 14 +++++++-
.../admin/config/NacosConfigurationTest.java | 17 +++++++--
.../ShenyuHttpRegistryControllerTest.java | 4 +++
.../admin/exception/ExceptionHandlersTest.java | 41 ++++++++++++++++++++++
.../listener/websocket/WebsocketCollectorTest.java | 38 ++++++++++++++++++--
.../shenyu/admin/service/MetaDataServiceTest.java | 34 +++++++++++++++---
.../admin/service/UpstreamCheckServiceTest.java | 32 +++++++++++++++--
.../AlibabaDubboClientValidatorTest.java | 36 +++++++------------
.../ApacheDubboClientValidationTest.java | 2 --
.../validation/ApacheDubboClientValidatorTest.java | 41 ++++++++--------------
.../init/ContextRegisterListenerTest.java | 4 ---
.../SpringCloudClientBeanPostProcessorTest.java | 2 ++
.../shenyu/web/handler/GlobalErrorHandlerTest.java | 27 ++++++++++++++
13 files changed, 223 insertions(+), 69 deletions(-)
diff --git a/pom.xml b/pom.xml
index 9322767..a6ddbc0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -141,6 +141,7 @@
<frontend-maven-plugin.node.version>v12.14.1</frontend-maven-plugin.node.version>
<bytebuddy.version>1.10.16</bytebuddy.version>
<spring-ldap.version>2.3.4.RELEASE</spring-ldap.version>
+ <jaxb.api.version>2.3.0</jaxb.api.version>
</properties>
<dependencyManagement>
@@ -445,8 +446,19 @@
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-junit4</artifactId>
+ <version>${powermock.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.xml.bind</groupId>
+ <artifactId>jaxb-api</artifactId>
+ <version>${jaxb.api.version}</version>
</dependency>
-
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/config/NacosConfigurationTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/config/NacosConfigurationTest.java
index 8458cc5..60c48fc 100644
--- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/config/NacosConfigurationTest.java
+++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/config/NacosConfigurationTest.java
@@ -23,12 +23,15 @@ import com.alibaba.nacos.api.config.ConfigService;
import org.apache.shenyu.admin.AbstractConfigurationTest;
import org.apache.shenyu.admin.config.properties.NacosProperties;
import org.junit.Test;
-import org.springframework.beans.factory.BeanCreationException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import java.util.Properties;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
/**
* Test cases for NacosConfiguration.
@@ -51,7 +54,7 @@ public final class NacosConfigurationTest extends AbstractConfigurationTest {
assertNotNull(configService);
}
- @Test(expected = BeanCreationException.class)
+ @Test
public void testNacosConfigService() {
String[] inlinedProperties = new String[]{
"shenyu.sync.nacos.url=localhost:8848",
@@ -62,7 +65,15 @@ public final class NacosConfigurationTest extends AbstractConfigurationTest {
"shenyu.sync.nacos.acm.accessKey=accessKey",
"shenyu.sync.nacos.acm.secretKey=secretKey",
};
- load(NacosConfiguration.class, inlinedProperties);
+ try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
+ final ConfigService configServiceMock = Mockito.mock(ConfigService.class);
+ ArgumentCaptor argument = ArgumentCaptor.forClass(Properties.class);
+ nacosFactoryMockedStatic
+ .when(() -> NacosFactory.createConfigService((Properties) argument.capture()))
+ .thenReturn(configServiceMock);
+ load(NacosConfiguration.class, inlinedProperties);
+ assertTrue(((Properties) argument.getValue()).containsKey(PropertyKeyConst.ENDPOINT));
+ }
ConfigService configService = (ConfigService) getContext().getBean("nacosConfigService");
assertNotNull(configService);
}
diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/controller/ShenyuHttpRegistryControllerTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/controller/ShenyuHttpRegistryControllerTest.java
index d7aa2e2..a7095e7 100644
--- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/controller/ShenyuHttpRegistryControllerTest.java
+++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/controller/ShenyuHttpRegistryControllerTest.java
@@ -79,6 +79,7 @@ public final class ShenyuHttpRegistryControllerTest {
public void testRegisterSpringMvc() throws Exception {
final MetaDataRegisterDTO springMvcRegisterDTO = buildSpringMvcRegisterDTO();
given(shenyuClientRegisterSpringMVCService.register(springMvcRegisterDTO)).willReturn("success");
+ given(this.shenyuClientRegisterService.get(springMvcRegisterDTO.getRpcType())).willReturn(this.shenyuClientRegisterSpringMVCService);
this.mockMvc.perform(MockMvcRequestBuilders.post("/shenyu-client/springmvc-register")
.contentType(MediaType.APPLICATION_JSON)
.content(GsonUtils.getInstance().toJson(springMvcRegisterDTO)))
@@ -105,6 +106,7 @@ public final class ShenyuHttpRegistryControllerTest {
public void testRegisterSpringCloud() throws Exception {
final MetaDataRegisterDTO springCloudRegisterDTO = buildCloudRegisterDTO();
given(this.shenyuClientRegisterSpringCloudService.register(springCloudRegisterDTO)).willReturn("success");
+ given(this.shenyuClientRegisterService.get(springCloudRegisterDTO.getRpcType())).willReturn(this.shenyuClientRegisterSpringCloudService);
this.mockMvc.perform(MockMvcRequestBuilders.post("/shenyu-client/springcloud-register")
.contentType(MediaType.APPLICATION_JSON)
.content(GsonUtils.getInstance().toJson(springCloudRegisterDTO)))
@@ -128,6 +130,7 @@ public final class ShenyuHttpRegistryControllerTest {
public void testRegisterRpc() throws Exception {
final MetaDataRegisterDTO metaDataDTO = buildMetaDataDTO("app_dubbo");
given(this.shenyuClientRegisterDubboService.register(metaDataDTO)).willReturn("success");
+ given(this.shenyuClientRegisterService.get(metaDataDTO.getRpcType())).willReturn(this.shenyuClientRegisterDubboService);
this.mockMvc.perform(MockMvcRequestBuilders.post("/shenyu-client/dubbo-register")
.contentType(MediaType.APPLICATION_JSON)
.content(GsonUtils.getInstance().toJson(metaDataDTO)))
@@ -155,6 +158,7 @@ public final class ShenyuHttpRegistryControllerTest {
public void testRegisterSofaRpc() throws Exception {
final MetaDataRegisterDTO metaDataDTO = buildMetaDataDTO("app_sofa");
given(this.shenyuClientRegisterSofaService.register(metaDataDTO)).willReturn("success");
+ given(this.shenyuClientRegisterService.get(metaDataDTO.getRpcType())).willReturn(this.shenyuClientRegisterSofaService);
this.mockMvc.perform(MockMvcRequestBuilders.post("/shenyu-client/sofa-register")
.contentType(MediaType.APPLICATION_JSON)
.content(GsonUtils.getInstance().toJson(metaDataDTO)))
diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/exception/ExceptionHandlersTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/exception/ExceptionHandlersTest.java
index 099a45f..448c151 100644
--- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/exception/ExceptionHandlersTest.java
+++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/exception/ExceptionHandlersTest.java
@@ -22,8 +22,16 @@ import org.apache.shenyu.admin.utils.ShenyuResultMessage;
import org.apache.shenyu.common.exception.CommonErrorCode;
import org.apache.shenyu.common.exception.ShenyuException;
import org.apache.shiro.authz.UnauthorizedException;
+import org.junit.AfterClass;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.MockedStatic;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
@@ -40,16 +48,39 @@ import java.util.Set;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* Test case for {@link ExceptionHandlers}.
*/
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(ExceptionHandlers.class)
public final class ExceptionHandlersTest {
+ private static Logger loggerSpy;
+
+ private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;
+
private ExceptionHandlers exceptionHandlersUnderTest;
+ @BeforeClass
+ public static void beforeClass() {
+ loggerSpy = spy(LoggerFactory.getLogger(ExceptionHandlers.class));
+ loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
+ loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(ExceptionHandlers.class)).thenReturn(loggerSpy);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ loggerFactoryMockedStatic.close();
+ }
+
@Before
public void setUp() {
exceptionHandlersUnderTest = new ExceptionHandlers();
@@ -58,6 +89,7 @@ public final class ExceptionHandlersTest {
@Test
public void testServerExceptionHandlerByException() {
Exception exception = new Exception();
+ doNothing().when(loggerSpy).error(exception.getMessage(), exception);
ShenyuAdminResult result = exceptionHandlersUnderTest.handleExceptionHandler(exception);
assertEquals(result.getCode().intValue(), CommonErrorCode.ERROR);
assertEquals(result.getMessage(), "The system is busy, please try again later");
@@ -66,6 +98,7 @@ public final class ExceptionHandlersTest {
@Test
public void testServerExceptionHandlerByShenyuException() {
Exception shenyuException = new ShenyuException("Test shenyuException message!");
+ doNothing().when(loggerSpy).error(shenyuException.getMessage(), shenyuException);
ShenyuAdminResult result = exceptionHandlersUnderTest.handleExceptionHandler(shenyuException);
assertEquals(result.getCode().intValue(), CommonErrorCode.ERROR);
assertEquals(result.getMessage(), shenyuException.getMessage());
@@ -74,6 +107,7 @@ public final class ExceptionHandlersTest {
@Test
public void testServerExceptionHandlerByDuplicateKeyException() {
DuplicateKeyException duplicateKeyException = new DuplicateKeyException("Test duplicateKeyException message!");
+ doNothing().when(loggerSpy).error(anyString(), eq(duplicateKeyException));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleDuplicateKeyException(duplicateKeyException);
assertEquals(result.getCode().intValue(), CommonErrorCode.ERROR);
assertEquals(result.getMessage(), ShenyuResultMessage.UNIQUE_INDEX_CONFLICT_ERROR);
@@ -82,6 +116,7 @@ public final class ExceptionHandlersTest {
@Test
public void testShiroExceptionHandler() {
UnauthorizedException unauthorizedException = mock(UnauthorizedException.class);
+ doNothing().when(loggerSpy).error(anyString(), eq(unauthorizedException));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleUnauthorizedException(unauthorizedException);
assertEquals(result.getCode().intValue(), CommonErrorCode.TOKEN_NO_PERMISSION);
assertEquals(result.getMessage(), ShenyuResultMessage.TOKEN_HAS_NO_PERMISSION);
@@ -90,6 +125,7 @@ public final class ExceptionHandlersTest {
@Test
public void testNullPointExceptionHandler() {
NullPointerException nullPointerException = mock(NullPointerException.class);
+ doNothing().when(loggerSpy).error(anyString(), eq(nullPointerException));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleNullPointException(nullPointerException);
assertEquals(result.getCode().intValue(), CommonErrorCode.NOT_FOUND_EXCEPTION);
assertEquals(result.getMessage(), ShenyuResultMessage.NOT_FOUND_EXCEPTION);
@@ -98,6 +134,7 @@ public final class ExceptionHandlersTest {
@Test
public void testHandleHttpRequestMethodNotSupportedException() {
HttpRequestMethodNotSupportedException exception = mock(HttpRequestMethodNotSupportedException.class);
+ doNothing().when(loggerSpy).warn(anyString(), eq(exception));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleHttpRequestMethodNotSupportedException(exception);
assertEquals(result.getCode().intValue(), CommonErrorCode.ERROR);
assertThat(result.getMessage(), containsString("method is not supported for this request. Supported methods are"));
@@ -110,6 +147,7 @@ public final class ExceptionHandlersTest {
when(exception.getBindingResult()).thenReturn(bindingResult);
List<FieldError> fieldErrors = mock(List.class);
when(bindingResult.getFieldErrors()).thenReturn(fieldErrors);
+ doNothing().when(loggerSpy).warn(anyString(), eq(exception));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleMethodArgumentNotValidException(exception);
assertEquals(result.getCode().intValue(), CommonErrorCode.ERROR);
assertThat(result.getMessage(), containsString("Request error! invalid argument"));
@@ -118,6 +156,7 @@ public final class ExceptionHandlersTest {
@Test
public void testHandleMissingServletRequestParameterException() {
MissingServletRequestParameterException exception = mock(MissingServletRequestParameterException.class);
+ doNothing().when(loggerSpy).warn(anyString(), eq(exception));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleMissingServletRequestParameterException(exception);
assertEquals(result.getCode().intValue(), CommonErrorCode.ERROR);
assertThat(result.getMessage(), containsString("parameter is missing"));
@@ -128,6 +167,7 @@ public final class ExceptionHandlersTest {
MethodArgumentTypeMismatchException exception = mock(MethodArgumentTypeMismatchException.class);
Class clazz = MethodArgumentTypeMismatchException.class;
when(exception.getRequiredType()).thenReturn(clazz);
+ doNothing().when(loggerSpy).warn(anyString(), eq(exception));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleMethodArgumentTypeMismatchException(exception);
assertEquals(result.getCode().intValue(), CommonErrorCode.ERROR);
assertThat(result.getMessage(), containsString("should be of type"));
@@ -138,6 +178,7 @@ public final class ExceptionHandlersTest {
ConstraintViolationException exception = mock(ConstraintViolationException.class);
Set<ConstraintViolation<?>> violations = mock(Set.class);
when(exception.getConstraintViolations()).thenReturn(violations);
+ doNothing().when(loggerSpy).warn(anyString(), eq(exception));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleConstraintViolationException(exception);
assertEquals(result.getCode().intValue(), CommonErrorCode.ERROR);
}
diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/listener/websocket/WebsocketCollectorTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/listener/websocket/WebsocketCollectorTest.java
index 5f59b53..a4d2aad 100644
--- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/listener/websocket/WebsocketCollectorTest.java
+++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/listener/websocket/WebsocketCollectorTest.java
@@ -21,12 +21,18 @@ import org.apache.shenyu.admin.service.SyncDataService;
import org.apache.shenyu.admin.spring.SpringBeanUtils;
import org.apache.shenyu.admin.utils.ThreadLocalUtil;
import org.apache.shenyu.common.enums.DataEventTypeEnum;
+import org.junit.AfterClass;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.MockedStatic;
import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
@@ -37,15 +43,25 @@ import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.isA;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* Test case for WebsocketCollector.
*/
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(WebsocketCollector.class)
public final class WebsocketCollectorTest {
+ private static Logger loggerSpy;
+
+ private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;
+
private WebsocketCollector websocketCollector;
@Mock
@@ -54,6 +70,19 @@ public final class WebsocketCollectorTest {
@Mock
private SyncDataService syncDataService;
+ @BeforeClass
+ public static void beforeClass() {
+ loggerSpy = spy(LoggerFactory.getLogger(WebsocketCollector.class));
+ loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
+ loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(WebsocketCollector.class)).thenReturn(loggerSpy);
+ loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(loggerSpy);
+ }
+
+ @AfterClass
+ public static void close() {
+ loggerFactoryMockedStatic.close();
+ }
+
@Before
public void setUp() {
websocketCollector = new WebsocketCollector();
@@ -63,6 +92,7 @@ public final class WebsocketCollectorTest {
public void testOnOpen() {
websocketCollector.onOpen(session);
assertEquals(1L, getSessionSetSize());
+ doNothing().when(loggerSpy).warn(anyString(), anyString());
websocketCollector.onClose(session);
}
@@ -76,6 +106,7 @@ public final class WebsocketCollectorTest {
websocketCollector.onMessage(DataEventTypeEnum.MYSELF.name(), session);
assertEquals(1L, getSessionSetSize());
Mockito.verify(syncDataService, Mockito.times(1)).syncAll(DataEventTypeEnum.MYSELF);
+ doNothing().when(loggerSpy).warn(anyString(), anyString());
websocketCollector.onClose(session);
}
@@ -83,6 +114,7 @@ public final class WebsocketCollectorTest {
public void testOnClose() {
websocketCollector.onOpen(session);
assertEquals(1L, getSessionSetSize());
+ doNothing().when(loggerSpy).warn(anyString(), anyString());
websocketCollector.onClose(session);
assertEquals(0L, getSessionSetSize());
assertNull(getSession());
@@ -92,6 +124,7 @@ public final class WebsocketCollectorTest {
public void testOnError() {
websocketCollector.onOpen(session);
assertEquals(1L, getSessionSetSize());
+ doNothing().when(loggerSpy).error(anyString(), anyString(), isA(Throwable.class));
Throwable throwable = mock(Throwable.class);
websocketCollector.onError(session, throwable);
assertEquals(0L, getSessionSetSize());
@@ -111,6 +144,7 @@ public final class WebsocketCollectorTest {
Mockito.verify(basic, Mockito.times(1)).sendText("test_message_1");
WebsocketCollector.send("test_message_2", DataEventTypeEnum.CREATE);
Mockito.verify(basic, Mockito.times(1)).sendText("test_message_2");
+ doNothing().when(loggerSpy).warn(anyString(), anyString());
websocketCollector.onClose(session);
}
diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/MetaDataServiceTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/MetaDataServiceTest.java
index c5166dc..8db26d9 100644
--- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/MetaDataServiceTest.java
+++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/MetaDataServiceTest.java
@@ -30,13 +30,18 @@ import org.apache.shenyu.admin.model.vo.MetaDataVO;
import org.apache.shenyu.common.constant.AdminConstants;
import org.apache.shenyu.common.dto.MetaData;
import org.apache.shenyu.register.common.dto.MetaDataRegisterDTO;
+import org.junit.AfterClass;
import org.junit.Assert;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.MockedStatic;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import java.util.ArrayList;
@@ -45,7 +50,10 @@ import java.util.Map;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -53,16 +61,21 @@ import static org.mockito.Mockito.when;
/**
* Test cases for MetaDataService.
*/
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(MetaDataServiceImpl.class)
public final class MetaDataServiceTest {
+ private static Logger loggerSpy;
+
+ private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;
+
@InjectMocks
private MetaDataServiceImpl metaDataService;
@Mock
private MetaDataMapper metaDataMapper;
- @Spy
+ @Mock
private ApplicationEventPublisher eventPublisher;
@Mock
@@ -71,6 +84,18 @@ public final class MetaDataServiceTest {
@Mock
private MetaDataQuery metaDataQuery;
+ @BeforeClass
+ public static void beforeClass() {
+ loggerSpy = spy(LoggerFactory.getLogger(MetaDataServiceImpl.class));
+ loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
+ loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(MetaDataServiceImpl.class)).thenReturn(loggerSpy);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ loggerFactoryMockedStatic.close();
+ }
+
/**
* Test case for saveOrUpdateMetaData().
*/
@@ -86,6 +111,7 @@ public final class MetaDataServiceTest {
*/
@Test
public void testCreateOrUpdate() {
+ doNothing().when(loggerSpy).error(anyString(), isA(MetaDataDTO.class));
testCreateOrUpdateForParamsError();
testCreateOrUpdateForPathExist();
testCreateOrUpdateForInsert();
diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/UpstreamCheckServiceTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/UpstreamCheckServiceTest.java
index 0b2bd8e..eb31b46 100644
--- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/UpstreamCheckServiceTest.java
+++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/UpstreamCheckServiceTest.java
@@ -30,14 +30,19 @@ import org.apache.shenyu.common.dto.convert.ZombieUpstream;
import org.apache.shenyu.common.enums.PluginEnum;
import org.apache.shenyu.common.utils.UpstreamCheckUtils;
import org.apache.shenyu.register.common.config.ShenyuRegisterCenterConfig;
+import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.test.util.ReflectionTestUtils;
@@ -54,13 +59,17 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* Test cases for UpstreamCheckService.
*/
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(UpstreamCheckService.class)
public final class UpstreamCheckServiceTest {
private static final String MOCK_SELECTOR_NAME = "mockSelectorName";
@@ -71,6 +80,10 @@ public final class UpstreamCheckServiceTest {
private static final String MOCK_PLUGIN_ID = "mockPluginId";
+ private static Logger loggerSpy;
+
+ private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;
+
private UpstreamCheckService upstreamCheckService;
@Mock
@@ -91,6 +104,19 @@ public final class UpstreamCheckServiceTest {
private Set<ZombieUpstream> zombieSet;
+ @BeforeClass
+ public static void beforeClass() {
+ loggerSpy = spy(LoggerFactory.getLogger(UpstreamCheckService.class));
+ loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
+ loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(UpstreamCheckService.class)).thenReturn(loggerSpy);
+ loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(loggerSpy);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ loggerFactoryMockedStatic.close();
+ }
+
@Before
public void setUp() {
shenyuRegisterCenterConfig.setRegisterType("http");
@@ -104,6 +130,8 @@ public final class UpstreamCheckServiceTest {
@Test
public void testScheduled() {
+ doNothing().when(loggerSpy).error(anyString(), isNull(Object.class));
+
PluginDO pluginDO = PluginDO.builder()
.name(PluginEnum.DIVIDE.getName())
.id(MOCK_PLUGIN_ID)
diff --git a/shenyu-client/shenyu-client-dubbo/shenyu-client-alibaba-dubbo/src/test/java/org/apache/shenyu/client/alibaba/dubbo/validation/AlibabaDubboClientValidatorTest.java b/shenyu-client/shenyu-client-dubbo/shenyu-client-alibaba-dubbo/src/test/java/org/apache/shenyu/client/alibaba/dubbo/validation/AlibabaDubboClientValidatorTest.java
index 039d7c0..60429c7 100644
--- a/shenyu-client/shenyu-client-dubbo/shenyu-client-alibaba-dubbo/src/test/java/org/apache/shenyu/client/alibaba/dubbo/validation/AlibabaDubboClientValidatorTest.java
+++ b/shenyu-client/shenyu-client-dubbo/shenyu-client-alibaba-dubbo/src/test/java/org/apache/shenyu/client/alibaba/dubbo/validation/AlibabaDubboClientValidatorTest.java
@@ -19,7 +19,6 @@ package org.apache.shenyu.client.alibaba.dubbo.validation;
import com.alibaba.dubbo.common.URL;
import org.apache.shenyu.client.alibaba.dubbo.validation.mock.MockValidationParameter;
-import org.junit.Ignore;
import org.junit.Test;
import javax.validation.ValidationException;
@@ -28,27 +27,20 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.hamcrest.Matchers.instanceOf;
-import static org.junit.Assert.assertThat;
-
/**
* Test case for {@link AlibabaDubboClientValidation}.
*/
-@Ignore
public final class AlibabaDubboClientValidatorTest {
- private static final String MOCK_SERVICE_URL =
+ private static final String MOCK_SERVICE_URL =
"mock://test:28000/org.apache.shenyu.client.alibaba.dubbo.validation.mock.MockValidatorTarget";
- @Test
- public void testItWithNonExistMethod() {
- try {
- final URL url = URL.valueOf(MOCK_SERVICE_URL);
- new AlibabaDubboClientValidation().getValidator(url)
- .validate("nonExistingMethod", new Class<?>[]{String.class}, new Object[]{"arg1"});
- } catch (Exception e) {
- assertThat(e, instanceOf(NoSuchMethodException.class));
- }
+ @Test(expected = NoSuchMethodException.class)
+ public void testItWithNonExistMethod() throws Exception {
+ final URL url = URL.valueOf(MOCK_SERVICE_URL);
+ new AlibabaDubboClientValidation().getValidator(url)
+ .validate("nonExistingMethod", new Class<?>[]{String.class}, new Object[]{"arg1"});
+
}
@Test
@@ -58,15 +50,11 @@ public final class AlibabaDubboClientValidatorTest {
.validate("method1", new Class<?>[]{String.class}, new Object[]{"anything"});
}
- @Test
- public void testValidateWhenMeetsConstraintThenValidationFailed() {
- try {
- final URL url = URL.valueOf(MOCK_SERVICE_URL);
- new AlibabaDubboClientValidation().getValidator(url)
- .validate("method2", new Class<?>[]{MockValidationParameter.class}, new Object[]{new MockValidationParameter("NotBeNull")});
- } catch (Exception e) {
- assertThat(e, instanceOf(ValidationException.class));
- }
+ @Test(expected = ValidationException.class)
+ public void testValidateWhenMeetsConstraintThenValidationFailed() throws Exception {
+ final URL url = URL.valueOf(MOCK_SERVICE_URL);
+ new AlibabaDubboClientValidation().getValidator(url)
+ .validate("method2", new Class<?>[]{MockValidationParameter.class}, new Object[]{new MockValidationParameter("NotBeNull")});
}
@Test
diff --git a/shenyu-client/shenyu-client-dubbo/shenyu-client-apache-dubbo/src/test/java/org/apache/shenyu/client/apache/dubbo/validation/ApacheDubboClientValidationTest.java b/shenyu-client/shenyu-client-dubbo/shenyu-client-apache-dubbo/src/test/java/org/apache/shenyu/client/apache/dubbo/validation/ApacheDubboClientValidationTest.java
index 22946bc..b4e170d 100644
--- a/shenyu-client/shenyu-client-dubbo/shenyu-client-apache-dubbo/src/test/java/org/apache/shenyu/client/apache/dubbo/validation/ApacheDubboClientValidationTest.java
+++ b/shenyu-client/shenyu-client-dubbo/shenyu-client-apache-dubbo/src/test/java/org/apache/shenyu/client/apache/dubbo/validation/ApacheDubboClientValidationTest.java
@@ -19,13 +19,11 @@ package org.apache.shenyu.client.apache.dubbo.validation;
import org.apache.dubbo.common.URL;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
/**
* Test case for {@link ApacheDubboClientValidation}.
*/
-@Ignore
public final class ApacheDubboClientValidationTest {
private ApacheDubboClientValidation apacheDubboClientValidationUnderTest;
diff --git a/shenyu-client/shenyu-client-dubbo/shenyu-client-apache-dubbo/src/test/java/org/apache/shenyu/client/apache/dubbo/validation/ApacheDubboClientValidatorTest.java b/shenyu-client/shenyu-client-dubbo/shenyu-client-apache-dubbo/src/test/java/org/apache/shenyu/client/apache/dubbo/validation/ApacheDubboClientValidatorTest.java
index 88212c3..cf8859d 100644
--- a/shenyu-client/shenyu-client-dubbo/shenyu-client-apache-dubbo/src/test/java/org/apache/shenyu/client/apache/dubbo/validation/ApacheDubboClientValidatorTest.java
+++ b/shenyu-client/shenyu-client-dubbo/shenyu-client-apache-dubbo/src/test/java/org/apache/shenyu/client/apache/dubbo/validation/ApacheDubboClientValidatorTest.java
@@ -22,7 +22,6 @@ import org.apache.dubbo.validation.Validator;
import org.apache.shenyu.client.apache.dubbo.validation.mock.MockValidationParameter;
import org.apache.shenyu.client.apache.dubbo.validation.service.TestService;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import javax.validation.ValidationException;
@@ -31,14 +30,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.hamcrest.Matchers.instanceOf;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-
/**
* Test case for {@link ApacheDubboClientValidator}.
*/
-@Ignore
public final class ApacheDubboClientValidatorTest {
private static final String MOCK_SERVICE_URL =
@@ -50,7 +44,7 @@ public final class ApacheDubboClientValidatorTest {
* test method {@link ApacheDubboClientValidator#validate(java.lang.String, java.lang.Class[], java.lang.Object[])}.
*/
@Test
- public void validate() {
+ public void validate() throws Exception {
URL url = URL.valueOf("dubbo://127.0.0.1:20880/org.apache.shenyu"
+ ".client.apache.dubbo.validation.service.TestService"
+ "?accepts=500&anyhost=true&application=shenyu-proxy"
@@ -61,13 +55,10 @@ public final class ApacheDubboClientValidatorTest {
+ "&side=provider&threadpool=fixed&threads=500&timeout=20000"
+ "×tamp=1608119259859&validation=shenyuValidation");
Validator apacheDubboClientValidator = new ApacheDubboClientValidation().getValidator(url);
- try {
- apacheDubboClientValidator.validate("test",
- new Class[]{TestService.TestObject.class},
- new Object[]{new TestService.TestObject(1)});
- } catch (Exception e) {
- assertThat("age cannot be null.", is(e.getMessage()));
- }
+
+ apacheDubboClientValidator.validate("test",
+ new Class[]{TestService.TestObject.class},
+ new Object[]{new TestService.TestObject(1)});
}
@Before
@@ -92,17 +83,13 @@ public final class ApacheDubboClientValidatorTest {
.validate("methodOne", new Class<?>[]{String.class}, new Object[]{"anything"});
}
- @Test
- public void testValidateWhenMeetsConstraintThenValidationFailed() {
- try {
- apacheDubboClientValidatorUnderTest
- .validate(
- "methodTwo",
- new Class<?>[]{MockValidationParameter.class},
- new Object[]{new MockValidationParameter("NotBeNull")});
- } catch (Exception e) {
- assertThat(e, instanceOf(ValidationException.class));
- }
+ @Test(expected = ValidationException.class)
+ public void testValidateWhenMeetsConstraintThenValidationFailed() throws Exception {
+ apacheDubboClientValidatorUnderTest
+ .validate(
+ "methodTwo",
+ new Class<?>[]{MockValidationParameter.class},
+ new Object[]{new MockValidationParameter("NotBeNull")});
}
@Test
@@ -117,8 +104,8 @@ public final class ApacheDubboClientValidatorTest {
public void testItWithCollectionArg() throws Exception {
apacheDubboClientValidatorUnderTest
.validate(
- "methodFour",
- new Class<?>[]{List.class},
+ "methodFour",
+ new Class<?>[]{List.class},
new Object[]{Collections.singletonList("parameter")});
}
diff --git a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListenerTest.java b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListenerTest.java
index ce67209..f23bd7e 100644
--- a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListenerTest.java
+++ b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/ContextRegisterListenerTest.java
@@ -20,7 +20,6 @@ package org.apache.shenyu.client.springcloud.init;
import org.apache.shenyu.client.core.register.ShenyuClientRegisterRepositoryFactory;
import org.apache.shenyu.register.common.config.ShenyuRegisterCenterConfig;
import org.junit.FixMethodOrder;
-import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
@@ -32,7 +31,6 @@ import org.springframework.core.env.Environment;
import java.util.Properties;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
/**
* Test case for {@link ContextRegisterListener}.
@@ -45,14 +43,12 @@ public final class ContextRegisterListenerTest {
private static Environment env;
@Test
- @Ignore
public void testNotFullRegister() {
Properties properties = new Properties();
ShenyuRegisterCenterConfig mockRegisterCenter = new ShenyuRegisterCenterConfig();
mockRegisterCenter.setServerLists("http://127.0.0.1:58080");
mockRegisterCenter.setRegisterType("http");
mockRegisterCenter.setProps(properties);
- when(env.getProperty("spring.application.name")).thenReturn("spring-cloud-test");
ContextRegisterListener contextRegisterListener = new ContextRegisterListener(mockRegisterCenter, env, ShenyuClientRegisterRepositoryFactory.newInstance(mockRegisterCenter));
ContextRefreshedEvent contextRefreshedEvent = mock(ContextRefreshedEvent.class);
contextRegisterListener.onApplicationEvent(contextRefreshedEvent);
diff --git a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientBeanPostProcessorTest.java b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientBeanPostProcessorTest.java
index a50e2b4..b21a6d5 100644
--- a/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientBeanPostProcessorTest.java
+++ b/shenyu-client/shenyu-client-http/shenyu-client-springcloud/src/test/java/org/apache/shenyu/client/springcloud/init/SpringCloudClientBeanPostProcessorTest.java
@@ -100,6 +100,8 @@ public final class SpringCloudClientBeanPostProcessorTest {
Properties properties = new Properties();
properties.setProperty("contextPath", "/test");
properties.setProperty("isFull", full + "");
+ properties.setProperty("ip", "127.0.0.1");
+ properties.setProperty("port", "8081");
ShenyuRegisterCenterConfig mockRegisterCenter = new ShenyuRegisterCenterConfig();
mockRegisterCenter.setServerLists("http://127.0.0.1:8080");
mockRegisterCenter.setRegisterType("http");
diff --git a/shenyu-web/src/test/java/org/apache/shenyu/web/handler/GlobalErrorHandlerTest.java b/shenyu-web/src/test/java/org/apache/shenyu/web/handler/GlobalErrorHandlerTest.java
index 7ff87cf..fa46383 100644
--- a/shenyu-web/src/test/java/org/apache/shenyu/web/handler/GlobalErrorHandlerTest.java
+++ b/shenyu-web/src/test/java/org/apache/shenyu/web/handler/GlobalErrorHandlerTest.java
@@ -20,10 +20,15 @@ package org.apache.shenyu.web.handler;
import org.apache.shenyu.plugin.api.result.DefaultShenyuResult;
import org.apache.shenyu.plugin.api.result.ShenyuResult;
import org.apache.shenyu.plugin.api.utils.SpringBeanUtils;
+import org.junit.AfterClass;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.MockedStatic;
import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebApplicationContext;
@@ -48,7 +53,11 @@ import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
@@ -58,8 +67,25 @@ import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class GlobalErrorHandlerTest {
+ private static Logger loggerSpy;
+
+ private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;
+
private GlobalErrorHandler globalErrorHandler;
+ @BeforeClass
+ public static void beforeClass() {
+ loggerSpy = spy(LoggerFactory.getLogger(GlobalErrorHandler.class));
+ loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
+ loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(GlobalErrorHandler.class)).thenReturn(loggerSpy);
+ loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(loggerSpy);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ loggerFactoryMockedStatic.close();
+ }
+
@Before
public void setUp() {
ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class);
@@ -78,6 +104,7 @@ public class GlobalErrorHandlerTest {
@Test
public void getErrorAttributes() {
+ doNothing().when(loggerSpy).error(anyString());
ServerWebExchange webExchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost:8080/favicon.ico"));
NullPointerException nullPointerException = new NullPointerException("nullPointerException");
MockServerRequest serverRequest = MockServerRequest.builder()