diff --git a/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java b/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java index e4b53de1097..302cd0e278d 100644 --- a/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java @@ -25,57 +25,60 @@ import com.alibaba.nacos.api.remote.response.Response; import com.alibaba.nacos.client.naming.remote.TestConnection; import com.alibaba.nacos.common.remote.ConnectionType; -import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.Connection; +import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientConfig; import com.alibaba.nacos.common.remote.client.ServerListFactory; import com.alibaba.nacos.common.remote.client.ServerRequestHandler; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + import java.util.HashMap; import java.util.List; import java.util.Map; -public class AbilityTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class AbilityTest { private RpcClient rpcClient; private Connection connection; @Test - public void testReceive() throws Exception { + void testReceive() throws Exception { rpcClient = new RpcClient(new RpcClientConfig() { @Override public String name() { return "test"; } - + @Override public int retryTimes() { return 1; } - + @Override public long timeOutMills() { return 3000L; } - + @Override public long connectionKeepAlive() { return 5000L; } - + @Override public int healthCheckRetryTimes() { return 1; } - + @Override public long healthCheckTimeOut() { return 3000L; } - + @Override public Map labels() { return new HashMap<>(); @@ -86,12 +89,12 @@ public Map labels() { public ConnectionType getConnectionType() { return null; } - + @Override public int rpcPortOffset() { return 0; } - + @Override public Connection connectToServer(ServerInfo serverInfo) throws Exception { connection = new Connection(new RpcClient.ServerInfo()) { @@ -101,33 +104,34 @@ public Connection connectToServer(ServerInfo serverInfo) throws Exception { super.abilityTable.put(AbilityKey.SERVER_TEST_1.getName(), true); super.abilityTable.put(AbilityKey.SERVER_TEST_2.getName(), false); } - + @Override public Response request(Request request, long timeoutMills) throws NacosException { return null; } - + @Override public RequestFuture requestFuture(Request request) throws NacosException { return null; } - + @Override public void asyncRequest(Request request, RequestCallBack requestCallBack) throws NacosException { - + } - + @Override public void close() { - + } - };; + }; + ; return connection; } }; rpcClient.start(); // test not ready - Assert.assertNull(rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1)); + assertNull(rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1)); // test ready rpcClient.serverListFactory(new ServerListFactory() { @@ -136,12 +140,12 @@ public void close() { public String genNextServer() { return "localhost:8848"; } - + @Override public String getCurrentServer() { return "localhost:8848"; } - + @Override public List getServerList() { return null; @@ -149,24 +153,26 @@ public List getServerList() { }); rpcClient.start(); // if connect successfully - Assert.assertEquals(rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertEquals(rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_2), AbilityStatus.NOT_SUPPORTED); + assertEquals(AbilityStatus.SUPPORTED, rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.NOT_SUPPORTED, rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_2)); } - @After - public void testServerRequestAbility() { + @AfterEach + void testServerRequestAbility() { //test support ServerRequestHandler serverRequestHandler = (request, connection) -> { - Assert.assertEquals(connection.getConnectionAbility(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertEquals(connection.getConnectionAbility(AbilityKey.SERVER_TEST_2), AbilityStatus.NOT_SUPPORTED); - return new Response() { }; + assertEquals(AbilityStatus.SUPPORTED, connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.NOT_SUPPORTED, connection.getConnectionAbility(AbilityKey.SERVER_TEST_2)); + return new Response() { + }; }; serverRequestHandler.requestReply(null, connection); - + // test no ability table serverRequestHandler = (request, connection) -> { - Assert.assertEquals(connection.getConnectionAbility(AbilityKey.SERVER_TEST_1), AbilityStatus.UNKNOWN); - return new Response() { }; + assertEquals(AbilityStatus.UNKNOWN, connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)); + return new Response() { + }; }; serverRequestHandler.requestReply(null, new TestConnection(new RpcClient.ServerInfo())); } diff --git a/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java index c31378f0d75..c0473dcc8d3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java @@ -18,25 +18,25 @@ import com.alibaba.nacos.api.ability.constant.AbilityKey; import com.alibaba.nacos.api.ability.constant.AbilityMode; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ClientAbilityControlManagerTest { +class ClientAbilityControlManagerTest { ClientAbilityControlManager clientAbilityControlManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { clientAbilityControlManager = new ClientAbilityControlManager(); } @Test - public void testInitCurrentNodeAbilities() { + void testInitCurrentNodeAbilities() { Map> actual = clientAbilityControlManager.initCurrentNodeAbilities(); assertEquals(1, actual.size()); assertTrue(actual.containsKey(AbilityMode.SDK_CLIENT)); @@ -45,7 +45,7 @@ public void testInitCurrentNodeAbilities() { } @Test - public void testGetPriority() { + void testGetPriority() { assertEquals(0, clientAbilityControlManager.getPriority()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java index 11fe0ce83c1..a2312d8b984 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java @@ -20,21 +20,24 @@ import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.param.Header; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class NacosClientAuthServiceImplTest { +class NacosClientAuthServiceImplTest { @Test - public void testLoginSuccess() throws Exception { + void testLoginSuccess() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); @@ -53,11 +56,11 @@ public void testLoginSuccess() throws Exception { //when boolean ret = nacosClientAuthService.login(properties); //then - Assert.assertTrue(ret); + assertTrue(ret); } @Test - public void testTestLoginFailCode() throws Exception { + void testTestLoginFailCode() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setCode(400); @@ -67,16 +70,16 @@ public void testTestLoginFailCode() throws Exception { properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); boolean ret = nacosClientAuthService.login(properties); - Assert.assertFalse(ret); + assertFalse(ret); } @Test - public void testTestLoginFailHttp() throws Exception { + void testTestLoginFailHttp() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); when(nacosRestTemplate.postForm(any(), (Header) any(), any(), any(), any())).thenThrow(new Exception()); Properties properties = new Properties(); @@ -84,17 +87,17 @@ public void testTestLoginFailHttp() throws Exception { properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); boolean ret = nacosClientAuthService.login(properties); - Assert.assertFalse(ret); + assertFalse(ret); } @Test - public void testTestLoginServerListSuccess() throws Exception { + void testTestLoginServerListSuccess() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); @@ -107,16 +110,16 @@ public void testTestLoginServerListSuccess() throws Exception { List serverList = new ArrayList<>(); serverList.add("localhost"); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); boolean ret = nacosClientAuthService.login(properties); - Assert.assertTrue(ret); + assertTrue(ret); } @Test - public void testTestLoginServerListLoginInWindow() throws Exception { + void testTestLoginServerListLoginInWindow() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); @@ -136,12 +139,12 @@ public void testTestLoginServerListLoginInWindow() throws Exception { nacosClientAuthService.login(properties); //then boolean ret = nacosClientAuthService.login(properties); - Assert.assertTrue(ret); + assertTrue(ret); } - + @Test - public void testGetAccessToken() throws Exception { + void testGetAccessToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setData("{\"accessToken\":\"abc\",\"tokenTtl\":1000}"); @@ -150,21 +153,22 @@ public void testGetAccessToken() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); - + List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when - Assert.assertTrue(nacosClientAuthService.login(properties)); + assertTrue(nacosClientAuthService.login(properties)); //then - Assert.assertEquals("abc", nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertEquals("abc", + nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } @Test - public void testGetAccessEmptyToken() throws Exception { + void testGetAccessEmptyToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setData("{\"accessToken\":\"\",\"tokenTtl\":1000}"); @@ -181,13 +185,14 @@ public void testGetAccessEmptyToken() throws Exception { nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when - Assert.assertTrue(nacosClientAuthService.login(properties)); + assertTrue(nacosClientAuthService.login(properties)); //then - Assert.assertEquals("", nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertEquals("", + nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } @Test - public void testGetAccessTokenWithoutToken() throws Exception { + void testGetAccessTokenWithoutToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setData("{\"tokenTtl\":1000}"); @@ -196,21 +201,22 @@ public void testGetAccessTokenWithoutToken() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); - + List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when - Assert.assertTrue(nacosClientAuthService.login(properties)); + assertTrue(nacosClientAuthService.login(properties)); //then - Assert.assertNull(nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertNull( + nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } @Test - public void testGetAccessTokenWithInvalidTtl() throws Exception { + void testGetAccessTokenWithInvalidTtl() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setData("{\"accessToken\":\"abc\",\"tokenTtl\":\"abc\"}"); @@ -219,14 +225,14 @@ public void testGetAccessTokenWithInvalidTtl() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); - + List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when - Assert.assertFalse(nacosClientAuthService.login(properties)); + assertFalse(nacosClientAuthService.login(properties)); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java index 6613a62ef6d..a7a577af4c4 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java @@ -17,27 +17,27 @@ package com.alibaba.nacos.client.auth.ram; import com.alibaba.nacos.api.PropertyKeyConst; -import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.client.auth.ram.injector.AbstractResourceInjector; -import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.common.utils.ReflectUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; +import com.alibaba.nacos.plugin.auth.api.RequestResource; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Map; import java.util.Properties; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class RamClientAuthServiceImplTest { +@ExtendWith(MockitoExtension.class) +class RamClientAuthServiceImplTest { private static final String MOCK = "mock"; @@ -54,11 +54,11 @@ public class RamClientAuthServiceImplTest { private RequestResource resource; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { ramClientAuthService = new RamClientAuthServiceImpl(); - Map resourceInjectors = (Map) ReflectUtils - .getFieldValue(ramClientAuthService, "resourceInjectors"); + Map resourceInjectors = (Map) ReflectUtils.getFieldValue( + ramClientAuthService, "resourceInjectors"); resourceInjectors.clear(); resourceInjectors.put(MOCK, mockResourceInjector); ramContext = (RamContext) ReflectUtils.getFieldValue(ramClientAuthService, "ramContext"); @@ -71,7 +71,7 @@ public void setUp() throws Exception { } @Test - public void testLoginWithAkSk() { + void testLoginWithAkSk() { assertTrue(ramClientAuthService.login(akSkProperties)); assertEquals(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey()); assertEquals(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); @@ -83,26 +83,26 @@ public void testLoginWithAkSk() { } @Test - public void testLoginWithRoleName() { + void testLoginWithRoleName() { assertTrue(ramClientAuthService.login(roleProperties)); - assertNull(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey()); - assertNull(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); + assertNull(ramContext.getAccessKey(), PropertyKeyConst.ACCESS_KEY); + assertNull(ramContext.getSecretKey(), PropertyKeyConst.SECRET_KEY); assertEquals(PropertyKeyConst.RAM_ROLE_NAME, ramContext.getRamRoleName()); assertTrue(ramClientAuthService.login(akSkProperties)); - assertNull(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey()); - assertNull(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); + assertNull(ramContext.getAccessKey(), PropertyKeyConst.ACCESS_KEY); + assertNull(ramContext.getSecretKey(), PropertyKeyConst.SECRET_KEY); assertEquals(PropertyKeyConst.RAM_ROLE_NAME, ramContext.getRamRoleName()); } @Test - public void testGetLoginIdentityContextWithoutLogin() { + void testGetLoginIdentityContextWithoutLogin() { LoginIdentityContext actual = ramClientAuthService.getLoginIdentityContext(resource); assertTrue(actual.getAllKey().isEmpty()); verify(mockResourceInjector, never()).doInject(resource, ramContext, actual); } @Test - public void testGetLoginIdentityContextWithoutInjector() { + void testGetLoginIdentityContextWithoutInjector() { ramClientAuthService.login(akSkProperties); LoginIdentityContext actual = ramClientAuthService.getLoginIdentityContext(resource); assertTrue(actual.getAllKey().isEmpty()); @@ -110,7 +110,7 @@ public void testGetLoginIdentityContextWithoutInjector() { } @Test - public void testGetLoginIdentityContextWithInjector() { + void testGetLoginIdentityContextWithInjector() { ramClientAuthService.login(akSkProperties); resource.setType(MOCK); LoginIdentityContext actual = ramClientAuthService.getLoginIdentityContext(resource); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java index 0e371c64749..4f56bcb77c8 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java @@ -18,49 +18,49 @@ package com.alibaba.nacos.client.auth.ram.identify; -import junit.framework.TestCase; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class CredentialServiceTest extends TestCase { +class CredentialServiceTest { private static final String APP_NAME = "app"; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { System.clearProperty(IdentifyConstants.PROJECT_NAME_PROPERTY); CredentialService.freeInstance(); CredentialService.freeInstance(APP_NAME); } @Test - public void testGetInstance() { + void testGetInstance() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.getInstance(); - Assert.assertEquals(credentialService1, credentialService2); + assertEquals(credentialService1, credentialService2); } @Test - public void testGetInstance2() { + void testGetInstance2() { CredentialService credentialService1 = CredentialService.getInstance(APP_NAME); CredentialService credentialService2 = CredentialService.getInstance(APP_NAME); - Assert.assertEquals(credentialService1, credentialService2); + assertEquals(credentialService1, credentialService2); } @Test - public void testGetInstance3() throws NoSuchFieldException, IllegalAccessException { + void testGetInstance3() throws NoSuchFieldException, IllegalAccessException { System.setProperty(IdentifyConstants.PROJECT_NAME_PROPERTY, APP_NAME); CredentialService credentialService1 = CredentialService.getInstance(); Field appNameField = credentialService1.getClass().getDeclaredField("appName"); @@ -70,21 +70,21 @@ public void testGetInstance3() throws NoSuchFieldException, IllegalAccessExcepti } @Test - public void testFreeInstance() { + void testFreeInstance() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.freeInstance(); - Assert.assertEquals(credentialService1, credentialService2); + assertEquals(credentialService1, credentialService2); } @Test - public void testFreeInstance2() { + void testFreeInstance2() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.freeInstance(); - Assert.assertEquals(credentialService1, credentialService2); + assertEquals(credentialService1, credentialService2); } @Test - public void testFree() throws NoSuchFieldException, IllegalAccessException { + void testFree() throws NoSuchFieldException, IllegalAccessException { CredentialService credentialService1 = CredentialService.getInstance(); CredentialWatcher mockWatcher = mock(CredentialWatcher.class); Field watcherField = CredentialService.class.getDeclaredField("watcher"); @@ -97,24 +97,24 @@ public void testFree() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testGetCredential() { + void testGetCredential() { CredentialService credentialService1 = CredentialService.getInstance(); Credentials credential = credentialService1.getCredential(); - Assert.assertNotNull(credential); + assertNotNull(credential); } @Test - public void testSetCredential() { + void testSetCredential() { CredentialService credentialService1 = CredentialService.getInstance(); Credentials credential = new Credentials(); //when credentialService1.setCredential(credential); //then - Assert.assertEquals(credential, credentialService1.getCredential()); + assertEquals(credential, credentialService1.getCredential()); } @Test - public void testSetStaticCredential() throws NoSuchFieldException, IllegalAccessException { + void testSetStaticCredential() throws NoSuchFieldException, IllegalAccessException { CredentialService credentialService1 = CredentialService.getInstance(); CredentialWatcher mockWatcher = mock(CredentialWatcher.class); Field watcherField = CredentialService.class.getDeclaredField("watcher"); @@ -124,12 +124,12 @@ public void testSetStaticCredential() throws NoSuchFieldException, IllegalAccess //when credentialService1.setStaticCredential(credential); //then - Assert.assertEquals(credential, credentialService1.getCredential()); + assertEquals(credential, credentialService1.getCredential()); verify(mockWatcher, times(1)).stop(); } @Test - public void testRegisterCredentialListener() { + void testRegisterCredentialListener() { CredentialListener expect = mock(CredentialListener.class); CredentialService credentialService1 = CredentialService.getInstance(); credentialService1.registerCredentialListener(expect); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java index c99077b05af..11d51d9f474 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java @@ -16,13 +16,12 @@ package com.alibaba.nacos.client.auth.ram.identify; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.BufferedWriter; import java.io.File; @@ -39,16 +38,17 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class CredentialWatcherTest { +@ExtendWith(MockitoExtension.class) +class CredentialWatcherTest { @Mock private CredentialService credentialService; @@ -59,18 +59,18 @@ public class CredentialWatcherTest { private Method loadCredentialFromPropertiesMethod; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { credentialWatcher = new CredentialWatcher("testApp", credentialService); loadCredentialMethod = CredentialWatcher.class.getDeclaredMethod("loadCredential", boolean.class); loadCredentialMethod.setAccessible(true); - loadCredentialFromPropertiesMethod = CredentialWatcher.class - .getDeclaredMethod("loadCredentialFromProperties", InputStream.class, boolean.class, Credentials.class); + loadCredentialFromPropertiesMethod = CredentialWatcher.class.getDeclaredMethod("loadCredentialFromProperties", + InputStream.class, boolean.class, Credentials.class); loadCredentialFromPropertiesMethod.setAccessible(true); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { credentialWatcher.stop(); System.clearProperty("spas.identity"); System.clearProperty(IdentifyConstants.ENV_ACCESS_KEY); @@ -79,16 +79,16 @@ public void tearDown() throws Exception { } @Test - public void testStop() throws NoSuchFieldException, IllegalAccessException { + void testStop() throws NoSuchFieldException, IllegalAccessException { credentialWatcher.stop(); Field executorField = CredentialWatcher.class.getDeclaredField("executor"); executorField.setAccessible(true); ScheduledExecutorService executor = (ScheduledExecutorService) executorField.get(credentialWatcher); - Assert.assertTrue(executor.isShutdown()); + assertTrue(executor.isShutdown()); } @Test - public void testLoadCredentialByEnv() throws InvocationTargetException, IllegalAccessException { + void testLoadCredentialByEnv() throws InvocationTargetException, IllegalAccessException { System.setProperty(IdentifyConstants.ENV_ACCESS_KEY, "testAk"); System.setProperty(IdentifyConstants.ENV_SECRET_KEY, "testSk"); final AtomicReference readAk = new AtomicReference<>(""); @@ -108,7 +108,7 @@ public void testLoadCredentialByEnv() throws InvocationTargetException, IllegalA } @Test - public void testLoadCredentialByIdentityFile() throws InvocationTargetException, IllegalAccessException { + void testLoadCredentialByIdentityFile() throws InvocationTargetException, IllegalAccessException { URL url = CredentialWatcherTest.class.getResource("/spas.identity"); System.setProperty("spas.identity", url.getPath()); final AtomicReference readAk = new AtomicReference<>(""); @@ -128,7 +128,7 @@ public void testLoadCredentialByIdentityFile() throws InvocationTargetException, } @Test - public void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetException, IllegalAccessException { + void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetException, IllegalAccessException { URL url = CredentialWatcherTest.class.getResource("/spas_invalid.identity"); System.setProperty("spas.identity", url.getPath()); final AtomicReference readAk = new AtomicReference<>(""); @@ -151,7 +151,7 @@ public void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetExc * The docker file is need /etc permission, which depend environment. So use mock InputStream to test. */ @Test - public void testLoadCredentialByDockerFile() + void testLoadCredentialByDockerFile() throws FileNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { URL url = CredentialWatcherTest.class.getResource("/spas_docker.identity"); InputStream propertiesIS = new FileInputStream(url.getPath()); @@ -166,7 +166,7 @@ public void testLoadCredentialByDockerFile() } @Test - public void testLoadCredentialByFileWithIoException() + void testLoadCredentialByFileWithIoException() throws IOException, InvocationTargetException, IllegalAccessException { InputStream propertiesIS = mock(InputStream.class); when(propertiesIS.read(any())).thenThrow(new IOException("test")); @@ -179,8 +179,7 @@ public void testLoadCredentialByFileWithIoException() } @Test - public void testReLoadCredential() - throws InvocationTargetException, IllegalAccessException, InterruptedException { + void testReLoadCredential() throws InvocationTargetException, IllegalAccessException, InterruptedException { URL url = CredentialWatcherTest.class.getResource("/spas_modified.identity"); modifiedFile(url, true); System.setProperty("spas.identity", url.getPath()); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java index 919aacf0582..51f831e11c1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java @@ -18,26 +18,28 @@ package com.alibaba.nacos.client.auth.ram.identify; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CredentialsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CredentialsTest { @Test - public void testGetter() { + void testGetter() { // given String ak = "ak"; String sk = "sk"; String tenantId = "100"; Credentials credentials = new Credentials(ak, sk, tenantId); // when then - Assert.assertEquals(ak, credentials.getAccessKey()); - Assert.assertEquals(sk, credentials.getSecretKey()); - Assert.assertEquals(tenantId, credentials.getTenantId()); + assertEquals(ak, credentials.getAccessKey()); + assertEquals(sk, credentials.getSecretKey()); + assertEquals(tenantId, credentials.getTenantId()); } @Test - public void testSetter() { + void testSetter() { //given String ak = "ak"; String sk = "sk"; @@ -48,13 +50,13 @@ public void testSetter() { credentials.setSecretKey(sk); credentials.setTenantId(tenantId); //then - Assert.assertEquals(ak, credentials.getAccessKey()); - Assert.assertEquals(sk, credentials.getSecretKey()); - Assert.assertEquals(tenantId, credentials.getTenantId()); + assertEquals(ak, credentials.getAccessKey()); + assertEquals(sk, credentials.getSecretKey()); + assertEquals(tenantId, credentials.getTenantId()); } @Test - public void testValid() { + void testValid() { //given String ak = "ak"; String sk = "sk"; @@ -63,11 +65,11 @@ public void testValid() { //when boolean actual = credentials.valid(); //then - Assert.assertTrue(actual); + assertTrue(actual); } @Test - public void testIdentical() { + void testIdentical() { //given String ak = "ak"; String sk = "sk"; @@ -77,6 +79,6 @@ public void testIdentical() { //then boolean actual = credentials1.identical(credentials2); //then - Assert.assertTrue(actual); + assertTrue(actual); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsConfigTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsConfigTest.java index fdfa26070da..c735f04aca1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsConfigTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsConfigTest.java @@ -16,17 +16,21 @@ package com.alibaba.nacos.client.auth.ram.identify; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -public class StsConfigTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class StsConfigTest { - @After - public void after() { + private static void resetStsConfig() { StsConfig.getInstance().setRamRoleName(null); StsConfig.getInstance().setTimeToRefreshInMillisecond(3 * 60 * 1000); StsConfig.getInstance().setCacheSecurityCredentials(true); @@ -39,73 +43,83 @@ public void after() { System.clearProperty(IdentifyConstants.SECURITY_CACHE_PROPERTY); } + @BeforeEach + void before() { + resetStsConfig(); + } + + @AfterEach + void after() { + resetStsConfig(); + } + @Test - public void testGetInstance() { + void testGetInstance() { StsConfig instance1 = StsConfig.getInstance(); StsConfig instance2 = StsConfig.getInstance(); - Assert.assertEquals(instance1, instance2); + assertEquals(instance1, instance2); } @Test - public void testGetRamRoleName() { + void testGetRamRoleName() { StsConfig.getInstance().setRamRoleName("test"); - Assert.assertEquals("test", StsConfig.getInstance().getRamRoleName()); + assertEquals("test", StsConfig.getInstance().getRamRoleName()); } @Test - public void testGetTimeToRefreshInMillisecond() { - Assert.assertEquals(3 * 60 * 1000, StsConfig.getInstance().getTimeToRefreshInMillisecond()); + void testGetTimeToRefreshInMillisecond() { + assertEquals(3 * 60 * 1000, StsConfig.getInstance().getTimeToRefreshInMillisecond()); StsConfig.getInstance().setTimeToRefreshInMillisecond(3000); - Assert.assertEquals(3000, StsConfig.getInstance().getTimeToRefreshInMillisecond()); + assertEquals(3000, StsConfig.getInstance().getTimeToRefreshInMillisecond()); } @Test - public void testGetSecurityCredentialsUrl() { - Assert.assertNull(StsConfig.getInstance().getSecurityCredentialsUrl()); + void testGetSecurityCredentialsUrl() { + assertNull(StsConfig.getInstance().getSecurityCredentialsUrl()); String expect = "localhost"; StsConfig.getInstance().setSecurityCredentialsUrl(expect); - Assert.assertEquals(expect, StsConfig.getInstance().getSecurityCredentialsUrl()); + assertEquals(expect, StsConfig.getInstance().getSecurityCredentialsUrl()); } @Test - public void testGetSecurityCredentialsUrlDefault() { + void testGetSecurityCredentialsUrlDefault() { StsConfig.getInstance().setRamRoleName("test"); - Assert.assertEquals("http://100.100.100.200/latest/meta-data/ram/security-credentials/test", + assertEquals("http://100.100.100.200/latest/meta-data/ram/security-credentials/test", StsConfig.getInstance().getSecurityCredentialsUrl()); } @Test - public void testGetSecurityCredentials() { - Assert.assertNull(StsConfig.getInstance().getSecurityCredentials()); + void testGetSecurityCredentials() { + assertNull(StsConfig.getInstance().getSecurityCredentials()); String expect = "abc"; StsConfig.getInstance().setSecurityCredentials(expect); - Assert.assertEquals(expect, StsConfig.getInstance().getSecurityCredentials()); + assertEquals(expect, StsConfig.getInstance().getSecurityCredentials()); } @Test - public void testIsCacheSecurityCredentials() { - Assert.assertTrue(StsConfig.getInstance().isCacheSecurityCredentials()); + void testIsCacheSecurityCredentials() { + assertTrue(StsConfig.getInstance().isCacheSecurityCredentials()); StsConfig.getInstance().setCacheSecurityCredentials(false); - Assert.assertFalse(StsConfig.getInstance().isCacheSecurityCredentials()); + assertFalse(StsConfig.getInstance().isCacheSecurityCredentials()); } @Test - public void testIsOnFalse() { + void testIsOnFalse() { boolean stsOn = StsConfig.getInstance().isStsOn(); - Assert.assertFalse(stsOn); + assertFalse(stsOn); } @Test - public void testIsOnTrue() { + void testIsOnTrue() { StsConfig.getInstance().setSecurityCredentials("abc"); boolean stsOn = StsConfig.getInstance().isStsOn(); - Assert.assertTrue(stsOn); + assertTrue(stsOn); } @Test - public void testFromEnv() + void testFromEnv() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor constructor = StsConfig.class.getDeclaredConstructor(); constructor.setAccessible(true); @@ -115,11 +129,11 @@ public void testFromEnv() System.setProperty(IdentifyConstants.SECURITY_URL_PROPERTY, "localhost"); System.setProperty(IdentifyConstants.SECURITY_CACHE_PROPERTY, "false"); StsConfig stsConfig = constructor.newInstance(); - Assert.assertEquals("test", stsConfig.getRamRoleName()); - Assert.assertEquals(3000, stsConfig.getTimeToRefreshInMillisecond()); - Assert.assertEquals("abc", stsConfig.getSecurityCredentials()); - Assert.assertEquals("localhost", stsConfig.getSecurityCredentialsUrl()); - Assert.assertFalse(stsConfig.isCacheSecurityCredentials()); + assertEquals("test", stsConfig.getRamRoleName()); + assertEquals(3000, stsConfig.getTimeToRefreshInMillisecond()); + assertEquals("abc", stsConfig.getSecurityCredentials()); + assertEquals("localhost", stsConfig.getSecurityCredentialsUrl()); + assertFalse(stsConfig.isCacheSecurityCredentials()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java index 6cbd2744ceb..4ca79c2be36 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java @@ -23,24 +23,25 @@ import com.alibaba.nacos.common.http.client.response.HttpClientResponse; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.utils.JacksonUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.ByteArrayInputStream; import java.lang.reflect.Field; import java.util.Date; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class StsCredentialHolderTest { +@ExtendWith(MockitoExtension.class) +class StsCredentialHolderTest { private String securityCredentialsUrl; @@ -49,8 +50,8 @@ public class StsCredentialHolderTest { @Mock private HttpClientRequest mockRest; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { securityCredentialsUrl = StsConfig.getInstance().getSecurityCredentialsUrl(); StsConfig.getInstance().setSecurityCredentialsUrl("url"); Field field = NacosRestTemplate.class.getDeclaredField("requestClient"); @@ -59,8 +60,8 @@ public void setUp() throws Exception { field.set(ConfigHttpClientManager.getInstance().getNacosRestTemplate(), mockRest); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { StsConfig.getInstance().setSecurityCredentials(null); StsConfig.getInstance().setSecurityCredentialsUrl(securityCredentialsUrl); Field field = NacosRestTemplate.class.getDeclaredField("requestClient"); @@ -77,7 +78,7 @@ private void clearForSts() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testGetStsCredentialFromCache() throws NoSuchFieldException, IllegalAccessException { + void testGetStsCredentialFromCache() throws NoSuchFieldException, IllegalAccessException { StsCredential stsCredential = buildMockStsCredential(); setStsCredential(stsCredential); assertEquals(stsCredential, StsCredentialHolder.getInstance().getStsCredential()); @@ -90,14 +91,14 @@ private void setStsCredential(StsCredential stsCredential) throws NoSuchFieldExc } @Test - public void testGetStsCredentialFromStringCache() throws NoSuchFieldException, IllegalAccessException { + void testGetStsCredentialFromStringCache() throws NoSuchFieldException, IllegalAccessException { StsCredential stsCredential = buildMockStsCredential(); StsConfig.getInstance().setSecurityCredentials(JacksonUtils.toJson(stsCredential)); assertEquals(stsCredential.toString(), StsCredentialHolder.getInstance().getStsCredential().toString()); } @Test - public void testGetStsCredentialFromRequest() throws Exception { + void testGetStsCredentialFromRequest() throws Exception { StsCredential stsCredential = buildMockStsCredential(); HttpClientResponse response = mock(HttpClientResponse.class); when(response.getStatusCode()).thenReturn(200); @@ -107,20 +108,24 @@ public void testGetStsCredentialFromRequest() throws Exception { assertEquals(stsCredential.toString(), StsCredentialHolder.getInstance().getStsCredential().toString()); } - @Test(expected = NacosRuntimeException.class) - public void testGetStsCredentialFromRequestFailure() throws Exception { - HttpClientResponse response = mock(HttpClientResponse.class); - when(response.getStatusCode()).thenReturn(500); - when(response.getHeaders()).thenReturn(Header.newInstance()); - when(response.getBody()).thenReturn(new ByteArrayInputStream(new byte[0])); - when(mockRest.execute(any(), any(), any())).thenReturn(response); - StsCredentialHolder.getInstance().getStsCredential(); + @Test + void testGetStsCredentialFromRequestFailure() throws Exception { + assertThrows(NacosRuntimeException.class, () -> { + HttpClientResponse response = mock(HttpClientResponse.class); + when(response.getStatusCode()).thenReturn(500); + when(response.getHeaders()).thenReturn(Header.newInstance()); + when(response.getBody()).thenReturn(new ByteArrayInputStream(new byte[0])); + when(mockRest.execute(any(), any(), any())).thenReturn(response); + StsCredentialHolder.getInstance().getStsCredential(); + }); } - @Test(expected = NacosRuntimeException.class) - public void testGetStsCredentialFromRequestException() throws Exception { - when(mockRest.execute(any(), any(), any())).thenThrow(new RuntimeException("test")); - StsCredentialHolder.getInstance().getStsCredential(); + @Test + void testGetStsCredentialFromRequestException() throws Exception { + assertThrows(NacosRuntimeException.class, () -> { + when(mockRest.execute(any(), any(), any())).thenThrow(new RuntimeException("test")); + StsCredentialHolder.getInstance().getStsCredential(); + }); } private StsCredential buildMockStsCredential() { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java index ac11121e8c4..4af02b0a162 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java @@ -16,23 +16,24 @@ package com.alibaba.nacos.client.auth.ram.injector; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class AbstractResourceInjectorTest { +class AbstractResourceInjectorTest { AbstractResourceInjector injector; - @Before - public void setUp() { - injector = new AbstractResourceInjector() { }; + @BeforeEach + void setUp() { + injector = new AbstractResourceInjector() { + }; } /** * TODO, fill test case after AbstractResourceInjector include default logic. */ @Test - public void testDoInject() { + void testDoInject() { injector.doInject(null, null, null); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java index 13a1c742143..fdd780f71f3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java @@ -25,15 +25,17 @@ import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.plugin.auth.constant.SignType; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Date; -public class ConfigResourceInjectorTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConfigResourceInjectorTest { private ConfigResourceInjector configResourceInjector; @@ -47,8 +49,8 @@ public class ConfigResourceInjectorTest { private StsCredential stsCredential; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { configResourceInjector = new ConfigResourceInjector(); ramContext = new RamContext(); ramContext.setAccessKey(PropertyKeyConst.ACCESS_KEY); @@ -64,66 +66,66 @@ public void setUp() throws Exception { stsCredential = new StsCredential(); } - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { StsConfig.getInstance().setSecurityCredentialsUrl(cachedSecurityCredentialsUrl); StsConfig.getInstance().setSecurityCredentials(cachedSecurityCredentials); clearForSts(); } @Test - public void testDoInjectWithFullResource() throws Exception { + void testDoInjectWithFullResource() throws Exception { LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } @Test - public void testDoInjectWithTenant() throws Exception { + void testDoInjectWithTenant() throws Exception { resource.setGroup(""); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } @Test - public void testDoInjectWithGroup() throws Exception { + void testDoInjectWithGroup() throws Exception { resource.setNamespace(""); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } @Test - public void testDoInjectWithoutResource() throws Exception { + void testDoInjectWithoutResource() throws Exception { resource = new RequestResource(); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } @Test - public void testDoInjectForSts() throws NoSuchFieldException, IllegalAccessException { + void testDoInjectForSts() throws NoSuchFieldException, IllegalAccessException { prepareForSts(); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(4, actual.getAllKey().size()); - Assert.assertEquals("test-sts-ak", actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); - Assert.assertTrue(actual.getAllKey().contains(IdentifyConstants.SECURITY_TOKEN_HEADER)); + assertEquals(4, actual.getAllKey().size()); + assertEquals("test-sts-ak", actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertTrue(actual.getAllKey().contains(IdentifyConstants.SECURITY_TOKEN_HEADER)); } private void prepareForSts() throws NoSuchFieldException, IllegalAccessException { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java index 9c51266e8ce..33b8b473e6a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java @@ -24,15 +24,17 @@ import com.alibaba.nacos.client.auth.ram.utils.SignUtil; import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.plugin.auth.api.RequestResource; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Date; -public class NamingResourceInjectorTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NamingResourceInjectorTest { private NamingResourceInjector namingResourceInjector; @@ -42,8 +44,8 @@ public class NamingResourceInjectorTest { private StsCredential stsCredential; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { namingResourceInjector = new NamingResourceInjector(); ramContext = new RamContext(); ramContext.setAccessKey(PropertyKeyConst.ACCESS_KEY); @@ -52,81 +54,81 @@ public void setUp() throws Exception { StsConfig.getInstance().setRamRoleName(null); } - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { clearForSts(); } @Test - public void testDoInjectWithEmpty() throws Exception { + void testDoInjectWithEmpty() throws Exception { resource = RequestResource.namingBuilder().setResource("").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); + assertTrue(Long.parseLong(actual.getParameter("data")) - System.currentTimeMillis() < 100); String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); - Assert.assertTrue(Long.parseLong(actual.getParameter("data")) - System.currentTimeMillis() < 100); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(expectSign, actual.getParameter("signature")); } @Test - public void testDoInjectWithGroup() throws Exception { + void testDoInjectWithGroup() throws Exception { resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); + assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); - Assert.assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(expectSign, actual.getParameter("signature")); } @Test - public void testDoInjectWithoutGroup() throws Exception { + void testDoInjectWithoutGroup() throws Exception { resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); - Assert.assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); + assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(expectSign, actual.getParameter("signature")); } @Test - public void testDoInjectWithGroupForSts() throws Exception { + void testDoInjectWithGroupForSts() throws Exception { prepareForSts(); resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); + assertEquals(4, actual.getAllKey().size()); + assertEquals("test-sts-ak", actual.getParameter("ak")); + assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk"); - Assert.assertEquals(4, actual.getAllKey().size()); - Assert.assertEquals("test-sts-ak", actual.getParameter("ak")); - Assert.assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(expectSign, actual.getParameter("signature")); } @Test - public void testDoInjectWithoutGroupForSts() throws Exception { + void testDoInjectWithoutGroupForSts() throws Exception { prepareForSts(); resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); + assertEquals(4, actual.getAllKey().size()); + assertEquals("test-sts-ak", actual.getParameter("ak")); + assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk"); - Assert.assertEquals(4, actual.getAllKey().size()); - Assert.assertEquals("test-sts-ak", actual.getParameter("ak")); - Assert.assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(expectSign, actual.getParameter("signature")); } @Test - public void testDoInjectForStsWithException() throws Exception { + void testDoInjectForStsWithException() throws Exception { prepareForSts(); stsCredential.setExpiration(new Date()); resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(0, actual.getAllKey().size()); + assertEquals(0, actual.getAllKey().size()); } private void prepareForSts() throws NoSuchFieldException, IllegalAccessException { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java index 01141a40d2e..a9eef88a8fd 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java @@ -16,26 +16,32 @@ package com.alibaba.nacos.client.auth.ram.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; -public class SignUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SignUtilTest { @Test - public void testSign() throws Exception { + void testSign() throws Exception { String actual = SignUtil.sign("aaa", "b"); - Assert.assertEquals("DxyaKScrqL26yXYOuHXE3OwfQ0Y=", actual); + assertEquals("DxyaKScrqL26yXYOuHXE3OwfQ0Y=", actual); } - @Test(expected = Exception.class) - public void testSignWithException() throws Exception { - SignUtil.sign(null, "b"); + @Test + void testSignWithException() throws Exception { + assertThrows(Exception.class, () -> { + SignUtil.sign(null, "b"); + }); } - @Test(expected = Exception.class) - public void testSignWithException2() throws Exception { - SignUtil.sign("aaa".getBytes(StandardCharsets.UTF_8), "b".getBytes(StandardCharsets.UTF_8), null); + @Test + void testSignWithException2() throws Exception { + assertThrows(Exception.class, () -> { + SignUtil.sign("aaa".getBytes(StandardCharsets.UTF_8), "b".getBytes(StandardCharsets.UTF_8), null); + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java index 097bebf3e71..eb19570bedf 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java @@ -16,73 +16,76 @@ package com.alibaba.nacos.client.auth.ram.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -public class SpasAdapterTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SpasAdapterTest { @Test - public void test() { - Assert.assertNull(SpasAdapter.getAk()); - Assert.assertNull(SpasAdapter.getSk()); - try { + void test() { + assertNull(SpasAdapter.getAk()); + assertNull(SpasAdapter.getSk()); + Assertions.assertDoesNotThrow(() -> { SpasAdapter.freeCredentialInstance(); - } catch (Exception e) { - Assert.fail(); - } + }); } @Test - public void testSign() { + void testSign() { - Assert.assertNull(SpasAdapter.getSignHeaders("", "", "123")); + assertNull(SpasAdapter.getSignHeaders("", "", "123")); final Map map1 = SpasAdapter.getSignHeaders("aa", "bb", "123"); - Assert.assertEquals(2, map1.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), + assertEquals(2, map1.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), map1.get("Spas-Signature")); final Map map2 = SpasAdapter.getSignHeaders("aa", "", "123"); - Assert.assertEquals(2, map2.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa" + "+" + map2.get("Timestamp"), "123"), + assertEquals(2, map2.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa" + "+" + map2.get("Timestamp"), "123"), map2.get("Spas-Signature")); final Map map3 = SpasAdapter.getSignHeaders("", "bb", "123"); - Assert.assertEquals(2, map3.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt(map3.get("Timestamp"), "123"), - map3.get("Spas-Signature")); + assertEquals(2, map3.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt(map3.get("Timestamp"), "123"), map3.get("Spas-Signature")); } @Test - public void testSign2() { + void testSign2() { - Assert.assertNull(SpasAdapter.getSignHeaders((Map) null, "123")); + assertNull(SpasAdapter.getSignHeaders((Map) null, "123")); Map param1 = new HashMap<>(); param1.put("tenant", "bb"); param1.put("group", "aa"); final Map map1 = SpasAdapter.getSignHeaders(param1, "123"); - Assert.assertEquals(2, map1.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), + assertEquals(2, map1.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), map1.get("Spas-Signature")); } @Test - public void testGetSignHeadersWithoutTenant() { + void testGetSignHeadersWithoutTenant() { Map param1 = new HashMap<>(); param1.put("group", "aa"); final Map map1 = SpasAdapter.getSignHeaders(param1, "123"); - Assert.assertEquals(2, map1.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa+" + map1.get("Timestamp"), "123"), + assertEquals(2, map1.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa+" + map1.get("Timestamp"), "123"), map1.get("Spas-Signature")); } - @Test(expected = Exception.class) - public void testSignWithHmacSha1EncryptWithException() { - SpasAdapter.signWithHmacSha1Encrypt(null, "123"); + @Test + void testSignWithHmacSha1EncryptWithException() { + assertThrows(Exception.class, () -> { + SpasAdapter.signWithHmacSha1Encrypt(null, "123"); + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java index 134cd986860..3cc54107c4a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java @@ -25,25 +25,27 @@ import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor; import com.alibaba.nacos.client.config.impl.ServerListManager; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.Executor; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) -public class NacosConfigServiceTest { +@ExtendWith(MockitoExtension.class) +class NacosConfigServiceTest { private NacosConfigService nacosConfigService; @@ -56,8 +58,8 @@ private void setFinal(Field field, Object ins, Object newValue) throws Exception } - @Before - public void mock() throws Exception { + @BeforeEach + void mock() throws Exception { final Properties properties = new Properties(); properties.put("serverAddr", "1.1.1.1"); nacosConfigService = new NacosConfigService(properties); @@ -65,13 +67,13 @@ public void mock() throws Exception { setFinal(NacosConfigService.class.getDeclaredField("worker"), nacosConfigService, mockWoker); } - @After - public void clean() { + @AfterEach + void clean() { LocalConfigInfoProcessor.cleanAllSnapshot(); } @Test - public void testGetConfigFromServer() throws NacosException { + void testGetConfigFromServer() throws NacosException { final String dataId = "1"; final String group = "2"; final String tenant = ""; @@ -81,57 +83,52 @@ public void testGetConfigFromServer() throws NacosException { response.setConfigType("bb"); Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenReturn(response); final String config = nacosConfigService.getConfig(dataId, group, timeout); - Assert.assertEquals("aa", config); + assertEquals("aa", config); Mockito.verify(mockWoker, Mockito.times(1)).getServerConfig(dataId, group, tenant, timeout, false); } @Test - public void testGetConfigFromFailOver() throws NacosException { + void testGetConfigFromFailOver() throws NacosException { final String dataId = "1failover"; final String group = "2"; final String tenant = ""; - MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic( - LocalConfigInfoProcessor.class); + MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor.class); try { String contentFailOver = "failOverContent" + System.currentTimeMillis(); - localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + localConfigInfoProcessorMockedStatic.when(() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(contentFailOver); final int timeout = 3000; final String config = nacosConfigService.getConfig(dataId, group, timeout); - Assert.assertEquals(contentFailOver, config); + assertEquals(contentFailOver, config); } finally { localConfigInfoProcessorMockedStatic.close(); } } @Test - public void testGetConfigFromLocalCache() throws NacosException { + void testGetConfigFromLocalCache() throws NacosException { final String dataId = "1localcache"; final String group = "2"; final String tenant = ""; - MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic( - LocalConfigInfoProcessor.class); + MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor.class); try { String contentFailOver = "localCacheContent" + System.currentTimeMillis(); //fail over null - localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + localConfigInfoProcessorMockedStatic.when(() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(null); //snapshot content - localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getSnapshot(any(), eq(dataId), eq(group), eq(tenant))) + localConfigInfoProcessorMockedStatic.when(() -> LocalConfigInfoProcessor.getSnapshot(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(contentFailOver); //form server error. final int timeout = 3000; Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenThrow(new NacosException()); final String config = nacosConfigService.getConfig(dataId, group, timeout); - Assert.assertEquals(contentFailOver, config); + assertEquals(contentFailOver, config); } finally { localConfigInfoProcessorMockedStatic.close(); } @@ -139,17 +136,15 @@ public void testGetConfigFromLocalCache() throws NacosException { } @Test - public void testGetConfig403() throws NacosException { + void testGetConfig403() throws NacosException { final String dataId = "1localcache403"; final String group = "2"; final String tenant = ""; - MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic( - LocalConfigInfoProcessor.class); + MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor.class); try { //fail over null - localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + localConfigInfoProcessorMockedStatic.when(() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(null); //form server error. @@ -158,9 +153,9 @@ public void testGetConfig403() throws NacosException { .thenThrow(new NacosException(NacosException.NO_RIGHT, "no right")); try { nacosConfigService.getConfig(dataId, group, timeout); - Assert.assertTrue(false); + assertTrue(false); } catch (NacosException e) { - Assert.assertEquals(NacosException.NO_RIGHT, e.getErrCode()); + assertEquals(NacosException.NO_RIGHT, e.getErrCode()); } } finally { localConfigInfoProcessorMockedStatic.close(); @@ -168,7 +163,7 @@ public void testGetConfig403() throws NacosException { } @Test - public void testGetConfigAndSignListener() throws NacosException { + void testGetConfigAndSignListener() throws NacosException { final String dataId = "1"; final String group = "2"; final String tenant = ""; @@ -214,8 +209,8 @@ public void removeCache(String dataId, String group) { } @Override - public ConfigResponse queryConfig(String dataId, String group, String tenant, long readTimeous, - boolean notify) throws NacosException { + public ConfigResponse queryConfig(String dataId, String group, String tenant, long readTimeous, boolean notify) + throws NacosException { ConfigResponse configResponse = new ConfigResponse(); configResponse.setContent(content); configResponse.setDataId(dataId); @@ -225,9 +220,8 @@ public ConfigResponse queryConfig(String dataId, String group, String tenant, lo } @Override - public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag, - String betaIps, String content, String encryptedDataKey, String casMd5, String type) - throws NacosException { + public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag, String betaIps, + String content, String encryptedDataKey, String casMd5, String type) throws NacosException { return false; } @@ -238,14 +232,13 @@ public boolean removeConfig(String dataId, String group, String tenant, String t }); final String config = nacosConfigService.getConfigAndSignListener(dataId, group, timeout, listener); - Assert.assertEquals(content, config); + assertEquals(content, config); - Mockito.verify(mockWoker, Mockito.times(1)) - .addTenantListenersWithContent(dataId, group, content, null, Arrays.asList(listener)); + Mockito.verify(mockWoker, Mockito.times(1)).addTenantListenersWithContent(dataId, group, content, null, Arrays.asList(listener)); } @Test - public void testAddListener() throws NacosException { + void testAddListener() throws NacosException { String dataId = "1"; String group = "2"; Listener listener = new Listener() { @@ -265,42 +258,38 @@ public void receiveConfigInfo(String configInfo) { } @Test - public void testPublishConfig() throws NacosException { + void testPublishConfig() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; String namespace = ""; String type = ConfigType.getDefaultType().getType(); - Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type)) - .thenReturn(true); + Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type)).thenReturn(true); final boolean b = nacosConfigService.publishConfig(dataId, group, content); - Assert.assertTrue(b); + assertTrue(b); - Mockito.verify(mockWoker, Mockito.times(1)) - .publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); + Mockito.verify(mockWoker, Mockito.times(1)).publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); } @Test - public void testPublishConfig2() throws NacosException { + void testPublishConfig2() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; String namespace = ""; String type = ConfigType.PROPERTIES.getType(); - Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type)) - .thenReturn(true); + Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type)).thenReturn(true); final boolean b = nacosConfigService.publishConfig(dataId, group, content, type); - Assert.assertTrue(b); + assertTrue(b); - Mockito.verify(mockWoker, Mockito.times(1)) - .publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); + Mockito.verify(mockWoker, Mockito.times(1)).publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); } @Test - public void testPublishConfigCas() throws NacosException { + void testPublishConfigCas() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; @@ -308,18 +297,16 @@ public void testPublishConfigCas() throws NacosException { String casMd5 = "96147704e3cb8be8597d55d75d244a02"; String type = ConfigType.getDefaultType().getType(); - Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type)) - .thenReturn(true); + Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type)).thenReturn(true); final boolean b = nacosConfigService.publishConfigCas(dataId, group, content, casMd5); - Assert.assertTrue(b); + assertTrue(b); - Mockito.verify(mockWoker, Mockito.times(1)) - .publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); + Mockito.verify(mockWoker, Mockito.times(1)).publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); } @Test - public void testPublishConfigCas2() throws NacosException { + void testPublishConfigCas2() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; @@ -327,18 +314,16 @@ public void testPublishConfigCas2() throws NacosException { String casMd5 = "96147704e3cb8be8597d55d75d244a02"; String type = ConfigType.PROPERTIES.getType(); - Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type)) - .thenReturn(true); + Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type)).thenReturn(true); final boolean b = nacosConfigService.publishConfigCas(dataId, group, content, casMd5, type); - Assert.assertTrue(b); + assertTrue(b); - Mockito.verify(mockWoker, Mockito.times(1)) - .publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); + Mockito.verify(mockWoker, Mockito.times(1)).publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); } @Test - public void testRemoveConfig() throws NacosException { + void testRemoveConfig() throws NacosException { String dataId = "1"; String group = "2"; String tenant = ""; @@ -346,13 +331,13 @@ public void testRemoveConfig() throws NacosException { Mockito.when(mockWoker.removeConfig(dataId, group, tenant, null)).thenReturn(true); final boolean b = nacosConfigService.removeConfig(dataId, group); - Assert.assertTrue(b); + assertTrue(b); Mockito.verify(mockWoker, Mockito.times(1)).removeConfig(dataId, group, tenant, null); } @Test - public void testRemoveListener() { + void testRemoveListener() { String dataId = "1"; String group = "2"; Listener listener = new Listener() { @@ -372,23 +357,21 @@ public void receiveConfigInfo(String configInfo) { } @Test - public void testGetServerStatus() { + void testGetServerStatus() { Mockito.when(mockWoker.isHealthServer()).thenReturn(true); - Assert.assertEquals("UP", nacosConfigService.getServerStatus()); + assertEquals("UP", nacosConfigService.getServerStatus()); Mockito.verify(mockWoker, Mockito.times(1)).isHealthServer(); Mockito.when(mockWoker.isHealthServer()).thenReturn(false); - Assert.assertEquals("DOWN", nacosConfigService.getServerStatus()); + assertEquals("DOWN", nacosConfigService.getServerStatus()); Mockito.verify(mockWoker, Mockito.times(2)).isHealthServer(); } @Test - public void testShutDown() { - try { + void testShutDown() { + Assertions.assertDoesNotThrow(() -> { nacosConfigService.shutDown(); - } catch (Exception e) { - Assert.fail(); - } + }); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java b/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java index d35167b38c3..e5bfd1992ac 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java @@ -16,68 +16,72 @@ package com.alibaba.nacos.client.config.common; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -public class GroupKeyTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class GroupKeyTest { @Test - public void testGetKey() { - Assert.assertEquals("1+foo", GroupKey.getKey("1", "foo")); - Assert.assertEquals("1+foo+bar", GroupKey.getKey("1", "foo", "bar")); - Assert.assertEquals("1+f%2Boo+b%25ar", GroupKey.getKey("1", "f+oo", "b%ar")); + void testGetKey() { + assertEquals("1+foo", GroupKey.getKey("1", "foo")); + assertEquals("1+foo+bar", GroupKey.getKey("1", "foo", "bar")); + assertEquals("1+f%2Boo+b%25ar", GroupKey.getKey("1", "f+oo", "b%ar")); } @Test - public void testGetKeyTenant() { - Assert.assertEquals("1+foo+bar", GroupKey.getKeyTenant("1", "foo", "bar")); + void testGetKeyTenant() { + assertEquals("1+foo+bar", GroupKey.getKeyTenant("1", "foo", "bar")); } @Test - public void testParseKey() { - Assert.assertArrayEquals(new String[] {"a", "f+oo", null}, GroupKey.parseKey("a+f%2Boo")); - Assert.assertArrayEquals(new String[] {"b", "f%oo", null}, GroupKey.parseKey("b+f%25oo")); - Assert.assertArrayEquals(new String[] {"a", "b", "c"}, GroupKey.parseKey("a+b+c")); + void testParseKey() { + assertArrayEquals(new String[] {"a", "f+oo", null}, GroupKey.parseKey("a+f%2Boo")); + assertArrayEquals(new String[] {"b", "f%oo", null}, GroupKey.parseKey("b+f%25oo")); + assertArrayEquals(new String[] {"a", "b", "c"}, GroupKey.parseKey("a+b+c")); } @Test - public void testParseKeyIllegalArgumentException1() { - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey(""); + void testParseKeyIllegalArgumentException1() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey(""); + }); } @Test - public void testParseKeyIllegalArgumentException2() { - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey("f%oo"); + void testParseKeyIllegalArgumentException2() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey("f%oo"); + }); } @Test - public void testParseKeyIllegalArgumentException3() { - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey("f+o+o+bar"); + void testParseKeyIllegalArgumentException3() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey("f+o+o+bar"); + }); } @Test - public void testParseKeyIllegalArgumentException4() { - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey("f++bar"); + void testParseKeyIllegalArgumentException4() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey("f++bar"); + }); } @Test - public void testGetKeyDatIdParam() { - thrown.expect(IllegalArgumentException.class); - GroupKey.getKey("", "a"); + void testGetKeyDatIdParam() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.getKey("", "a"); + }); } @Test - public void testGetKeyGroupParam() { - thrown.expect(IllegalArgumentException.class); - GroupKey.getKey("a", ""); + void testGetKeyGroupParam() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.getKey("a", ""); + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java index 47acff2c38d..5796a000427 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java @@ -16,13 +16,14 @@ package com.alibaba.nacos.client.config.filter.impl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ConfigContextTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigContextTest { @Test - public void testParameter() { + void testParameter() { ConfigContext context = new ConfigContext(); String key = "key"; String v = "v"; @@ -30,7 +31,7 @@ public void testParameter() { String actual = (String) context.getParameter(key); - Assert.assertEquals(v, actual); + assertEquals(v, actual); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java index fa6c5463252..98f84a21a1b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java @@ -18,21 +18,22 @@ import com.alibaba.nacos.api.config.filter.IConfigFilterChain; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * ConfigCryptoFilterTest. * * @author lixiaoshuang */ -@RunWith(MockitoJUnitRunner.class) -public class ConfigEncryptionFilterTest { +@ExtendWith(MockitoExtension.class) +class ConfigEncryptionFilterTest { private ConfigEncryptionFilter configEncryptionFilter; @@ -45,25 +46,25 @@ public class ConfigEncryptionFilterTest { @Mock private IConfigFilterChain iConfigFilterChain; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { configEncryptionFilter = new ConfigEncryptionFilter(); - - Mockito.when(configRequest.getDataId()).thenReturn("cipher-aes-test"); - Mockito.when(configRequest.getContent()).thenReturn("nacos"); - - Mockito.when(configResponse.getDataId()).thenReturn("test-dataid"); - Mockito.when(configResponse.getContent()).thenReturn("nacos"); - Mockito.when(configResponse.getEncryptedDataKey()).thenReturn("1234567890"); } @Test - public void testDoFilter() throws NacosException { + void doFilter() throws NacosException { + Mockito.when(configRequest.getDataId()).thenReturn("cipher-aes-test"); + Mockito.when(configRequest.getContent()).thenReturn("nacos"); + configEncryptionFilter.doFilter(configRequest, null, iConfigFilterChain); Mockito.verify(configRequest, Mockito.atLeast(1)).getDataId(); Mockito.verify(configRequest, Mockito.atLeast(1)).getContent(); + Mockito.when(configResponse.getDataId()).thenReturn("test-dataid"); + Mockito.when(configResponse.getContent()).thenReturn("nacos"); + Mockito.when(configResponse.getEncryptedDataKey()).thenReturn("1234567890"); + configEncryptionFilter.doFilter(null, configResponse, iConfigFilterChain); Mockito.verify(configResponse, Mockito.atLeast(1)).getDataId(); @@ -72,8 +73,8 @@ public void testDoFilter() throws NacosException { } @Test - public void testGetOrder() { + void testGetOrder() { int order = configEncryptionFilter.getOrder(); - Assert.assertEquals(order, 0); + assertEquals(0, order); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java index 34566ebf640..c4685baed5a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java @@ -21,22 +21,22 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; +import org.apache.commons.codec.binary.Base64; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; -import org.apache.commons.codec.binary.Base64; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * AES encryption algorithm testing dataId with prefix cipher. @@ -45,8 +45,8 @@ * @Date 2023/12/23 9:45 PM * @Version 1.0 */ -@RunWith(MockitoJUnitRunner.class) -public class ConfigEncryptionFilterTest1 { +@ExtendWith(MockitoExtension.class) +class ConfigEncryptionFilterTest1 { private ConfigEncryptionFilter configEncryptionFilter; @@ -55,8 +55,8 @@ public class ConfigEncryptionFilterTest1 { @Mock private IConfigFilterChain iConfigFilterChain; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mockEncryptionPluginService = new EncryptionPluginService() { private static final String ALGORITHM = "AES"; @@ -150,30 +150,32 @@ private String aesDecrypt(String content, String key) { } @Test - public void testDoFilterEncryptedData() throws NacosException { + void testDoFilterEncryptedData() throws NacosException { String dataId = "cipher-aes-test"; String content = "nacos"; - final String encryptionContent = mockEncryptionPluginService.encrypt(mockEncryptionPluginService.generateSecretKey(), content); - final String theKeyOfContentKey = mockEncryptionPluginService.encryptSecretKey(mockEncryptionPluginService.generateSecretKey()); + final String encryptionContent = mockEncryptionPluginService.encrypt( + mockEncryptionPluginService.generateSecretKey(), content); + final String theKeyOfContentKey = mockEncryptionPluginService.encryptSecretKey( + mockEncryptionPluginService.generateSecretKey()); ConfigRequest configRequest = new ConfigRequest(); configRequest.setDataId(dataId); configRequest.setContent(content); configEncryptionFilter.doFilter(configRequest, null, iConfigFilterChain); - Assert.assertEquals(configRequest.getContent(), encryptionContent); - Assert.assertEquals(configRequest.getEncryptedDataKey(), theKeyOfContentKey); + assertEquals(configRequest.getContent(), encryptionContent); + assertEquals(configRequest.getEncryptedDataKey(), theKeyOfContentKey); ConfigResponse configResponse = new ConfigResponse(); configResponse.setDataId(dataId); configResponse.setContent(encryptionContent); configResponse.setEncryptedDataKey(theKeyOfContentKey); configEncryptionFilter.doFilter(null, configResponse, iConfigFilterChain); - Assert.assertEquals(configResponse.getContent(), content); - Assert.assertEquals(configResponse.getEncryptedDataKey(), mockEncryptionPluginService.generateSecretKey()); + assertEquals(configResponse.getContent(), content); + assertEquals(configResponse.getEncryptedDataKey(), mockEncryptionPluginService.generateSecretKey()); } @Test - public void testDoFilter() throws NacosException { + void testDoFilter() throws NacosException { String dataId = "test"; String content = "nacos"; @@ -181,21 +183,21 @@ public void testDoFilter() throws NacosException { configRequest.setDataId(dataId); configRequest.setContent(content); configEncryptionFilter.doFilter(configRequest, null, iConfigFilterChain); - Assert.assertEquals(configRequest.getContent(), content); - Assert.assertEquals(configRequest.getEncryptedDataKey(), ""); + assertEquals(configRequest.getContent(), content); + assertEquals("", configRequest.getEncryptedDataKey()); ConfigResponse configResponse = new ConfigResponse(); configResponse.setDataId(dataId); configResponse.setContent(content); configResponse.setEncryptedDataKey(""); configEncryptionFilter.doFilter(null, configResponse, iConfigFilterChain); - Assert.assertEquals(configResponse.getContent(), content); - Assert.assertEquals(configResponse.getEncryptedDataKey(), ""); + assertEquals(configResponse.getContent(), content); + assertEquals("", configResponse.getEncryptedDataKey()); } @Test - public void testGetOrder() { + void testGetOrder() { int order = configEncryptionFilter.getOrder(); - Assert.assertEquals(order, 0); + assertEquals(0, order); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java index ef74f305b8e..b610c72c6aa 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java @@ -22,15 +22,63 @@ import com.alibaba.nacos.api.config.filter.IConfigRequest; import com.alibaba.nacos.api.config.filter.IConfigResponse; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; -public class ConfigFilterChainManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigFilterChainManagerTest { + + @Test + void testAddFilterOrder() throws NacosException { + final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); + MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); + MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); + MyIConfigFilter filter3 = new MyIConfigFilter("filter3", 3); + + //random order + configFilterChainManager.addFilter(filter2); + configFilterChainManager.addFilter(filter1); + configFilterChainManager.addFilter(filter3); + + ConfigRequest configRequest = new ConfigRequest(); + + configFilterChainManager.doFilter(configRequest, new ConfigResponse()); + + IConfigContext configContext = configRequest.getConfigContext(); + + // doFilter works + assertEquals(1, configContext.getParameter("filter1")); + assertEquals(2, configContext.getParameter("filter2")); + assertEquals(3, configContext.getParameter("filter3")); + + //order + List orders = (List) configContext.getParameter("orders"); + assertEquals(Arrays.asList(1, 2, 3), orders); + } + + @Test + void testAddFilterNotRepeat() throws NacosException { + final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); + MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); + MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); + MyIConfigFilter repeatFilter = new MyIConfigFilter("filter1", 1); + + configFilterChainManager.addFilter(filter2); + configFilterChainManager.addFilter(filter1); + configFilterChainManager.addFilter(repeatFilter); + + ConfigRequest configRequest = new ConfigRequest(); + configFilterChainManager.doFilter(configRequest, new ConfigResponse()); + + IConfigContext configContext = configRequest.getConfigContext(); + + assertEquals(2, configContext.getParameter("filterCount")); + } private static class MyIConfigFilter implements IConfigFilter { @@ -83,51 +131,4 @@ public String getFilterName() { return name; } } - - @Test - public void testAddFilterOrder() throws NacosException { - final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); - MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); - MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); - MyIConfigFilter filter3 = new MyIConfigFilter("filter3", 3); - - //random order - configFilterChainManager.addFilter(filter2); - configFilterChainManager.addFilter(filter1); - configFilterChainManager.addFilter(filter3); - - ConfigRequest configRequest = new ConfigRequest(); - - configFilterChainManager.doFilter(configRequest, new ConfigResponse()); - - IConfigContext configContext = configRequest.getConfigContext(); - - // doFilter works - Assert.assertEquals(1, configContext.getParameter("filter1")); - Assert.assertEquals(2, configContext.getParameter("filter2")); - Assert.assertEquals(3, configContext.getParameter("filter3")); - - //order - List orders = (List) configContext.getParameter("orders"); - Assert.assertEquals(Arrays.asList(1, 2, 3), orders); - } - - @Test - public void testAddFilterNotRepeat() throws NacosException { - final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); - MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); - MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); - MyIConfigFilter repeatFilter = new MyIConfigFilter("filter1", 1); - - configFilterChainManager.addFilter(filter2); - configFilterChainManager.addFilter(filter1); - configFilterChainManager.addFilter(repeatFilter); - - ConfigRequest configRequest = new ConfigRequest(); - configFilterChainManager.doFilter(configRequest, new ConfigResponse()); - - IConfigContext configContext = configRequest.getConfigContext(); - - Assert.assertEquals(2, configContext.getParameter("filterCount")); - } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java index 379bd1af051..e831c796439 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java @@ -17,13 +17,14 @@ package com.alibaba.nacos.client.config.filter.impl; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ConfigFilterChainTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigFilterChainTest { @Test - public void testConfigFilterChain() { + void testConfigFilterChain() { ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(null); configFilterChainManager.addFilter(new DemoFilter1()); configFilterChainManager.addFilter(new DemoFilter2()); @@ -31,8 +32,8 @@ public void testConfigFilterChain() { ConfigResponse configResponse = new ConfigResponse(); try { configFilterChainManager.doFilter(configRequest, configResponse); - Assert.assertEquals(DemoFilter1.class.getName(), configRequest.getParameter("filter1")); - Assert.assertEquals(DemoFilter2.class.getName(), configRequest.getParameter("filter2")); + assertEquals(DemoFilter1.class.getName(), configRequest.getParameter("filter1")); + assertEquals(DemoFilter2.class.getName(), configRequest.getParameter("filter2")); } catch (NacosException e) { e.printStackTrace(); } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java index 35c9c0bf718..a2e58bd7512 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java @@ -17,13 +17,15 @@ package com.alibaba.nacos.client.config.filter.impl; import com.alibaba.nacos.api.config.filter.IConfigContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ConfigRequestTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ConfigRequestTest { @Test - public void testGetterAndSetter() { + void testGetterAndSetter() { ConfigRequest configRequest = new ConfigRequest(); String dataId = "id"; String group = "group"; @@ -37,16 +39,16 @@ public void testGetterAndSetter() { configRequest.setTenant(tenant); configRequest.setType(type); - Assert.assertEquals(dataId, configRequest.getDataId()); - Assert.assertEquals(group, configRequest.getGroup()); - Assert.assertEquals(tenant, configRequest.getTenant()); - Assert.assertEquals(content, configRequest.getContent()); - Assert.assertEquals(type, configRequest.getType()); + assertEquals(dataId, configRequest.getDataId()); + assertEquals(group, configRequest.getGroup()); + assertEquals(tenant, configRequest.getTenant()); + assertEquals(content, configRequest.getContent()); + assertEquals(type, configRequest.getType()); } @Test - public void testGetParameter() { + void testGetParameter() { ConfigRequest configRequest = new ConfigRequest(); String dataId = "id"; String group = "group"; @@ -58,16 +60,16 @@ public void testGetParameter() { configRequest.setGroup(group); configRequest.setTenant(tenant); - Assert.assertEquals(dataId, configRequest.getParameter("dataId")); - Assert.assertEquals(group, configRequest.getParameter("group")); - Assert.assertEquals(tenant, configRequest.getParameter("tenant")); - Assert.assertEquals(content, configRequest.getParameter("content")); + assertEquals(dataId, configRequest.getParameter("dataId")); + assertEquals(group, configRequest.getParameter("group")); + assertEquals(tenant, configRequest.getParameter("tenant")); + assertEquals(content, configRequest.getParameter("content")); } @Test - public void testGetConfigContext() { + void testGetConfigContext() { ConfigRequest configRequest = new ConfigRequest(); IConfigContext configContext = configRequest.getConfigContext(); - Assert.assertNotNull(configContext); + assertNotNull(configContext); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java index 12b01064c72..ae49404fa88 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java @@ -17,13 +17,15 @@ package com.alibaba.nacos.client.config.filter.impl; import com.alibaba.nacos.api.config.filter.IConfigContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ConfigResponseTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ConfigResponseTest { @Test - public void testGetterAndSetter() { + void testGetterAndSetter() { ConfigResponse configResponse = new ConfigResponse(); String dataId = "id"; String group = "group"; @@ -37,15 +39,15 @@ public void testGetterAndSetter() { configResponse.setTenant(tenant); configResponse.setConfigType(type); - Assert.assertEquals(dataId, configResponse.getDataId()); - Assert.assertEquals(group, configResponse.getGroup()); - Assert.assertEquals(tenant, configResponse.getTenant()); - Assert.assertEquals(content, configResponse.getContent()); - Assert.assertEquals(type, configResponse.getConfigType()); + assertEquals(dataId, configResponse.getDataId()); + assertEquals(group, configResponse.getGroup()); + assertEquals(tenant, configResponse.getTenant()); + assertEquals(content, configResponse.getContent()); + assertEquals(type, configResponse.getConfigType()); } @Test - public void getParameter() { + void getParameter() { ConfigResponse configResponse = new ConfigResponse(); String dataId = "id"; String group = "group"; @@ -59,17 +61,17 @@ public void getParameter() { configResponse.setTenant(tenant); configResponse.putParameter(custom, custom); - Assert.assertEquals(dataId, configResponse.getParameter("dataId")); - Assert.assertEquals(group, configResponse.getParameter("group")); - Assert.assertEquals(tenant, configResponse.getParameter("tenant")); - Assert.assertEquals(content, configResponse.getParameter("content")); - Assert.assertEquals(custom, configResponse.getParameter("custom")); + assertEquals(dataId, configResponse.getParameter("dataId")); + assertEquals(group, configResponse.getParameter("group")); + assertEquals(tenant, configResponse.getParameter("tenant")); + assertEquals(content, configResponse.getParameter("content")); + assertEquals(custom, configResponse.getParameter("custom")); } @Test - public void getConfigContext() { + void getConfigContext() { ConfigResponse configResponse = new ConfigResponse(); IConfigContext configContext = configResponse.getConfigContext(); - Assert.assertNotNull(configContext); + assertNotNull(configContext); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java b/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java index ef56426aebf..cc048de9354 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java @@ -19,13 +19,67 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.param.Header; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -public class MetricsHttpAgentTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MetricsHttpAgentTest { + + @Test + void testGetter() { + String name = "name"; + String encode = "UTF-8"; + String tenant = "aaa"; + String namespace = "aaa"; + final HttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); + final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); + + assertEquals(name, metricsHttpAgent.getName()); + assertEquals(encode, metricsHttpAgent.getEncode()); + assertEquals(tenant, metricsHttpAgent.getTenant()); + assertEquals(namespace, metricsHttpAgent.getNamespace()); + } + + @Test + void testLifeCycle() throws NacosException { + String name = "name"; + String encode = "UTF-8"; + String tenant = "aaa"; + String namespace = "aaa"; + final MockHttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); + final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); + + metricsHttpAgent.start(); + assertTrue(mockHttpAgent.isStart()); + + metricsHttpAgent.shutdown(); + assertTrue(mockHttpAgent.isShutdown()); + } + + @Test + void testHttpMethod() throws Exception { + String name = "name"; + String encode = "UTF-8"; + String tenant = "aaa"; + String namespace = "aaa"; + final MockHttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); + final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); + + final HttpRestResult result1 = metricsHttpAgent.httpGet("/aa", new HashMap(), + new HashMap(), "UTF-8", 1L); + assertEquals("get /aa", result1.getMessage()); + final HttpRestResult result2 = metricsHttpAgent.httpPost("/aa", new HashMap(), + new HashMap(), "UTF-8", 1L); + assertEquals("post /aa", result2.getMessage()); + + final HttpRestResult result3 = metricsHttpAgent.httpDelete("/aa", new HashMap(), + new HashMap(), "UTF-8", 1L); + assertEquals("delete /aa", result3.getMessage()); + } private static class MockHttpAgent implements HttpAgent { @@ -104,56 +158,4 @@ public boolean isShutdown() { return shutdown; } } - - @Test - public void testGetter() { - String name = "name"; - String encode = "UTF-8"; - String tenant = "aaa"; - String namespace = "aaa"; - final HttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); - final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); - - Assert.assertEquals(name, metricsHttpAgent.getName()); - Assert.assertEquals(encode, metricsHttpAgent.getEncode()); - Assert.assertEquals(tenant, metricsHttpAgent.getTenant()); - Assert.assertEquals(namespace, metricsHttpAgent.getNamespace()); - } - - @Test - public void testLifeCycle() throws NacosException { - String name = "name"; - String encode = "UTF-8"; - String tenant = "aaa"; - String namespace = "aaa"; - final MockHttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); - final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); - - metricsHttpAgent.start(); - Assert.assertTrue(mockHttpAgent.isStart()); - - metricsHttpAgent.shutdown(); - Assert.assertTrue(mockHttpAgent.isShutdown()); - } - - @Test - public void testHttpMethod() throws Exception { - String name = "name"; - String encode = "UTF-8"; - String tenant = "aaa"; - String namespace = "aaa"; - final MockHttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); - final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); - - final HttpRestResult result1 = metricsHttpAgent - .httpGet("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - Assert.assertEquals("get /aa", result1.getMessage()); - final HttpRestResult result2 = metricsHttpAgent - .httpPost("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - Assert.assertEquals("post /aa", result2.getMessage()); - - final HttpRestResult result3 = metricsHttpAgent - .httpDelete("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - Assert.assertEquals("delete /aa", result3.getMessage()); - } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java b/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java index c394e2485dc..6f512437222 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java @@ -24,14 +24,16 @@ import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.lang.reflect.Field; import java.net.ConnectException; @@ -41,13 +43,19 @@ import java.util.Iterator; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ServerHttpAgentTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class ServerHttpAgentTest { private static final String SERVER_ADDRESS_1 = "http://1.1.1.1:8848"; @@ -67,8 +75,8 @@ public class ServerHttpAgentTest { ServerHttpAgent serverHttpAgent; - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { serverHttpAgent = new ServerHttpAgent(serverListManager, new Properties()); injectRestTemplate(); when(serverListManager.getCurrentServerAddr()).thenReturn(SERVER_ADDRESS_1); @@ -82,49 +90,49 @@ private void injectRestTemplate() throws NoSuchFieldException, IllegalAccessExce restTemplateField.set(serverHttpAgent, nacosRestTemplate); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { serverHttpAgent.shutdown(); } @Test - public void testConstruct() throws NacosException { + void testConstruct() throws NacosException { ServerListManager server = new ServerListManager(); final ServerHttpAgent serverHttpAgent1 = new ServerHttpAgent(server); - Assert.assertNotNull(serverHttpAgent1); + assertNotNull(serverHttpAgent1); final ServerHttpAgent serverHttpAgent2 = new ServerHttpAgent(server, new Properties()); - Assert.assertNotNull(serverHttpAgent2); + assertNotNull(serverHttpAgent2); final Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1"); final ServerHttpAgent serverHttpAgent3 = new ServerHttpAgent(properties); - Assert.assertNotNull(serverHttpAgent3); + assertNotNull(serverHttpAgent3); } @Test - public void testGetterAndSetter() throws NacosException { + void testGetterAndSetter() throws NacosException { ServerListManager server = new ServerListManager("aaa", "namespace1"); final ServerHttpAgent serverHttpAgent = new ServerHttpAgent(server, new Properties()); final String appname = ServerHttpAgent.getAppname(); //set by AppNameUtils, init in ParamUtils static block - Assert.assertEquals("unknown", appname); + assertEquals("unknown", appname); final String encode = serverHttpAgent.getEncode(); final String namespace = serverHttpAgent.getNamespace(); final String tenant = serverHttpAgent.getTenant(); final String name = serverHttpAgent.getName(); - Assert.assertNull(encode); - Assert.assertEquals("namespace1", namespace); - Assert.assertEquals("namespace1", tenant); - Assert.assertEquals("custom-aaa_8080_nacos_serverlist_namespace1", name); + assertNull(encode); + assertEquals("namespace1", namespace); + assertEquals("namespace1", tenant); + assertEquals("custom-aaa_8080_nacos_serverlist_namespace1", name); } @Test - public void testLifCycle() throws NacosException { + void testLifCycle() throws NacosException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "aaa"); ServerListManager server = Mockito.mock(ServerListManager.class); @@ -133,148 +141,164 @@ public void testLifCycle() throws NacosException { serverHttpAgent.start(); Mockito.verify(server).start(); - try { + Assertions.assertDoesNotThrow(() -> { serverHttpAgent.shutdown(); - } catch (NullPointerException e) { - Assert.fail(); - } + }); } @Test - public void testHttpGetSuccess() throws Exception { + void testHttpGetSuccess() throws Exception { when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), + "UTF-8", 1000); + assertEquals(mockResult, actual); } - @Test(expected = ConnectException.class) - public void testHttpGetFailed() throws Exception { - when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); - when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); - serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + @Test + void testHttpGetFailed() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); + when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - @Test(expected = NacosException.class) - public void testHttpWithRequestException() throws Exception { - when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); - serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + @Test + void testHttpWithRequestException() throws Exception { + assertThrows(NacosException.class, () -> { + when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException(), + new SocketTimeoutException(), new NacosException()); + serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } @Test - public void testRetryWithNewServer() throws Exception { + void testRetryWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException()); when(nacosRestTemplate.get(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), + "UTF-8", 1000); + assertEquals(mockResult, actual); } - @Test(expected = ConnectException.class) - public void testRetryTimeout() throws Exception { - when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException()); - serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + @Test + void testRetryTimeout() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException()); + serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + }); } @Test - public void testHttpPostSuccess() throws Exception { + void testHttpPostSuccess() throws Exception { when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpPost("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); + assertEquals(mockResult, actual); } - @Test(expected = ConnectException.class) - public void testHttpPostFailed() throws Exception { - when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); - when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); - serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + @Test + void testHttpPostFailed() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); + when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - @Test(expected = NacosException.class) - public void testHttpPostWithRequestException() throws Exception { - when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), anyMap(), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); - serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + @Test + void testHttpPostWithRequestException() throws Exception { + assertThrows(NacosException.class, () -> { + when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), anyMap(), eq(String.class))).thenThrow(new ConnectException(), + new SocketTimeoutException(), new NacosException()); + serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } @Test - public void testRetryPostWithNewServer() throws Exception { + void testRetryPostWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenThrow(new ConnectException()); when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpPost("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); + assertEquals(mockResult, actual); } - @Test(expected = ConnectException.class) - public void testRetryPostTimeout() throws Exception { - when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), anyMap(), eq(String.class))).thenThrow(new SocketTimeoutException()); - serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + @Test + void testRetryPostTimeout() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), anyMap(), eq(String.class))).thenThrow(new SocketTimeoutException()); + serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + }); } @Test - public void testHttpDeleteSuccess() throws Exception { + void testHttpDeleteSuccess() throws Exception { when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpDelete("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); + assertEquals(mockResult, actual); } - @Test(expected = ConnectException.class) - public void testHttpDeleteFailed() throws Exception { - when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); - when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); - serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + @Test + void testHttpDeleteFailed() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); + when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - @Test(expected = NacosException.class) - public void testHttpDeleteWithRequestException() throws Exception { - when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); - serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + @Test + void testHttpDeleteWithRequestException() throws Exception { + assertThrows(NacosException.class, () -> { + when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException(), + new SocketTimeoutException(), new NacosException()); + serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } @Test - public void testRetryDeleteWithNewServer() throws Exception { + void testRetryDeleteWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException()); when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpDelete("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); + assertEquals(mockResult, actual); } - @Test(expected = ConnectException.class) - public void testRetryDeleteTimeout() throws Exception { - when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException()); - serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + @Test + void testRetryDeleteTimeout() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException()); + serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + }); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java index 7ff7116345b..3d0fb134393 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java @@ -27,8 +27,7 @@ import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.common.utils.MD5Utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Date; @@ -37,34 +36,40 @@ import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; -public class CacheDataTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CacheDataTest { @Test - public void testConstructorAndEquals() { + void testConstructorAndEquals() { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData cacheData1 = new CacheData(filter, "name1", "key", "group", "tenant"); - Assert.assertEquals("CacheData [key, group]", cacheData1.toString()); + assertEquals("CacheData [key, group]", cacheData1.toString()); final CacheData cacheData2 = new CacheData(filter, "name2", "key", "group"); - Assert.assertEquals(cacheData1, cacheData2); - Assert.assertEquals(cacheData1.hashCode(), cacheData2.hashCode()); + assertEquals(cacheData1, cacheData2); + assertEquals(cacheData1.hashCode(), cacheData2.hashCode()); final CacheData cacheData3 = new CacheData(filter, "name2", "key3", "group", "tenant"); - Assert.assertNotEquals(cacheData1, cacheData3); + assertNotEquals(cacheData1, cacheData3); } @Test - public void testGetter() { + void testGetter() { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData cacheData1 = new CacheData(filter, "name1", "key", "group", "tenant"); - Assert.assertTrue(cacheData1.isInitializing()); - Assert.assertNull(cacheData1.getContent()); - Assert.assertEquals(0, cacheData1.getTaskId()); - Assert.assertFalse(cacheData1.isConsistentWithServer()); - Assert.assertFalse(cacheData1.isUseLocalConfigInfo()); - Assert.assertEquals(0, cacheData1.getLastModifiedTs().intValue()); - Assert.assertEquals(0, cacheData1.getLocalConfigInfoVersion()); + assertTrue(cacheData1.isInitializing()); + assertNull(cacheData1.getContent()); + assertEquals(0, cacheData1.getTaskId()); + assertFalse(cacheData1.isConsistentWithServer()); + assertFalse(cacheData1.isUseLocalConfigInfo()); + assertEquals(0, cacheData1.getLastModifiedTs().intValue()); + assertEquals(0, cacheData1.getLocalConfigInfoVersion()); cacheData1.setInitializing(false); cacheData1.setContent("123"); @@ -76,30 +81,30 @@ public void testGetter() { cacheData1.setUseLocalConfigInfo(true); cacheData1.setLocalConfigInfoVersion(timeStamp); - Assert.assertFalse(cacheData1.isInitializing()); - Assert.assertEquals("123", cacheData1.getContent()); - Assert.assertEquals(MD5Utils.md5Hex("123", "UTF-8"), cacheData1.getMd5()); + assertFalse(cacheData1.isInitializing()); + assertEquals("123", cacheData1.getContent()); + assertEquals(MD5Utils.md5Hex("123", "UTF-8"), cacheData1.getMd5()); - Assert.assertEquals(123, cacheData1.getTaskId()); - Assert.assertTrue(cacheData1.isConsistentWithServer()); - Assert.assertEquals("123", cacheData1.getType()); - Assert.assertTrue(cacheData1.isUseLocalConfigInfo()); - Assert.assertEquals(timeStamp, cacheData1.getLastModifiedTs().longValue()); - Assert.assertEquals(timeStamp, cacheData1.getLocalConfigInfoVersion()); + assertEquals(123, cacheData1.getTaskId()); + assertTrue(cacheData1.isConsistentWithServer()); + assertEquals("123", cacheData1.getType()); + assertTrue(cacheData1.isUseLocalConfigInfo()); + assertEquals(timeStamp, cacheData1.getLastModifiedTs().longValue()); + assertEquals(timeStamp, cacheData1.getLocalConfigInfoVersion()); } @Test - public void testNotifyWarnTimeout() { + void testNotifyWarnTimeout() { System.setProperty("nacos.listener.notify.warn.timeout", "5000"); long notifyWarnTimeout = CacheData.initNotifyWarnTimeout(); - Assert.assertEquals(5000, notifyWarnTimeout); + assertEquals(5000, notifyWarnTimeout); System.setProperty("nacos.listener.notify.warn.timeout", "1bf000abc"); long notifyWarnTimeout2 = CacheData.initNotifyWarnTimeout(); - Assert.assertEquals(60000, notifyWarnTimeout2); + assertEquals(60000, notifyWarnTimeout2); } @Test - public void testListener() throws NacosException { + void testListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData cacheData1 = new CacheData(filter, "name1", "key", "group", "tenant"); @@ -114,16 +119,16 @@ public void receiveConfigInfo(String configInfo) { } }; cacheData1.addListener(listener); - Assert.assertEquals(1, cacheData1.getListeners().size()); - Assert.assertEquals(listener, cacheData1.getListeners().get(0)); + assertEquals(1, cacheData1.getListeners().size()); + assertEquals(listener, cacheData1.getListeners().get(0)); cacheData1.removeListener(listener); - Assert.assertEquals(0, cacheData1.getListeners().size()); + assertEquals(0, cacheData1.getListeners().size()); } @Test - public void testCheckListenerMd5() throws NacosException { + void testCheckListenerMd5() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData data = new CacheData(filter, "name1", "key", "group", "tenant"); final List list = new ArrayList<>(); @@ -140,22 +145,22 @@ public void receiveConfigInfo(String configInfo) { }; data.addListener(listener); data.checkListenerMd5(); - Assert.assertTrue(data.checkListenersMd5Consistent()); - Assert.assertEquals(0, list.size()); + assertTrue(data.checkListenersMd5Consistent()); + assertEquals(0, list.size()); data.setContent("new"); - Assert.assertFalse(data.checkListenersMd5Consistent()); + assertFalse(data.checkListenersMd5Consistent()); data.checkListenerMd5(); - Assert.assertEquals(1, list.size()); - Assert.assertEquals("new", list.get(0)); + assertEquals(1, list.size()); + assertEquals("new", list.get(0)); } @Test - public void testCheckListenerMd5NotifyTimeouts() throws NacosException { + void testCheckListenerMd5NotifyTimeouts() throws NacosException { System.setProperty("nacos.listener.notify.warn.timeout", "1000"); long notifyWarnTimeout = CacheData.initNotifyWarnTimeout(); - Assert.assertEquals(1000, notifyWarnTimeout); + assertEquals(1000, notifyWarnTimeout); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData data = new CacheData(filter, "name1", "keytimeouts", "group", "tenant"); Listener listener = new Listener() { @@ -192,12 +197,12 @@ public Class subscribeType() { data.addListener(listener); data.setContent("new"); data.checkListenerMd5(); - Assert.assertTrue(data.checkListenersMd5Consistent()); - Assert.assertEquals("keytimeouts", dataIdNotifyTimeouts.get()); + assertTrue(data.checkListenersMd5Consistent()); + assertEquals("keytimeouts", dataIdNotifyTimeouts.get()); } @Test - public void testAbstractSharedListener() throws NacosException { + void testAbstractSharedListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData data = new CacheData(filter, "name1", "keyshare", "group", "tenant"); @@ -223,14 +228,14 @@ public void innerReceive(String dataId, String group, String configInfo) { String content = "content" + System.currentTimeMillis(); data.setContent(content); data.checkListenerMd5(); - Assert.assertTrue(data.checkListenersMd5Consistent()); - Assert.assertEquals(dataIdReceive[0], "keyshare"); - Assert.assertEquals(groupReceive[0], "group"); - Assert.assertEquals(contentReceive[0], content); + assertTrue(data.checkListenersMd5Consistent()); + assertEquals("keyshare", dataIdReceive[0]); + assertEquals("group", groupReceive[0]); + assertEquals(contentReceive[0], content); } @Test - public void testAbstractConfigChangeListener() throws NacosException { + void testAbstractConfigChangeListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData data = new CacheData(filter, "name1", "keyshare", "group", "tenant"); data.setType("properties"); @@ -253,10 +258,10 @@ public Executor getExecutor() { String content = "b=b\nc=abc\nd=d"; data.setContent(content); data.checkListenerMd5(); - Assert.assertTrue(data.checkListenersMd5Consistent()); - Assert.assertEquals(PropertyChangeType.DELETED, changeItemReceived.get().getChangeItem("a").getType()); - Assert.assertEquals(PropertyChangeType.MODIFIED, changeItemReceived.get().getChangeItem("c").getType()); - Assert.assertEquals(PropertyChangeType.ADDED, changeItemReceived.get().getChangeItem("d").getType()); + assertTrue(data.checkListenersMd5Consistent()); + assertEquals(PropertyChangeType.DELETED, changeItemReceived.get().getChangeItem("a").getType()); + assertEquals(PropertyChangeType.MODIFIED, changeItemReceived.get().getChangeItem("c").getType()); + assertEquals(PropertyChangeType.ADDED, changeItemReceived.get().getChangeItem("d").getType()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java index 5c780ebbc9d..0b60d704224 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java @@ -42,15 +42,14 @@ import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.MD5Utils; import com.fasterxml.jackson.databind.JsonNode; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.lang.reflect.Field; @@ -66,9 +65,12 @@ import java.util.concurrent.atomic.AtomicReference; import static com.alibaba.nacos.api.annotation.NacosProperties.NAMESPACE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -76,24 +78,24 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; -@RunWith(MockitoJUnitRunner.class) -public class ClientWorkerTest { +@ExtendWith(MockitoExtension.class) +class ClientWorkerTest { + + private static final String TEST_NAMESPACE = "TEST_NAMESPACE"; MockedStatic rpcClientFactoryMockedStatic; MockedStatic localConfigInfoProcessorMockedStatic; - private static final String TEST_NAMESPACE = "TEST_NAMESPACE"; + @Mock + RpcClient rpcClient; private ClientWorker clientWorker; private ClientWorker clientWorkerSpy; - @Mock - RpcClient rpcClient; - - @Before - public void before() { + @BeforeEach + void before() { rpcClientFactoryMockedStatic = Mockito.mockStatic(RpcClientFactory.class); rpcClientFactoryMockedStatic.when( @@ -116,25 +118,25 @@ public void before() { clientWorkerSpy = Mockito.spy(clientWorker); } - @After - public void after() { + @AfterEach + void after() { rpcClientFactoryMockedStatic.close(); localConfigInfoProcessorMockedStatic.close(); } @Test - public void testConstruct() throws NacosException { + void testConstruct() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties); - Assert.assertNotNull(clientWorker); + assertNotNull(clientWorker); } @Test - public void testAddListenerWithoutTenant() throws NacosException { + void testAddListenerWithoutTenant() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -149,22 +151,22 @@ public void testAddListenerWithoutTenant() throws NacosException { public void receiveConfigInfo(String configInfo) { } }; - + clientWorker.addListeners(dataId, group, Collections.singletonList(listener)); List listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(1, listeners.size()); - Assert.assertEquals(listener, listeners.get(0)); + assertEquals(1, listeners.size()); + assertEquals(listener, listeners.get(0)); clientWorker.removeListener(dataId, group, listener); listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(0, listeners.size()); + assertEquals(0, listeners.size()); CacheData cacheData = clientWorker.addCacheDataIfAbsent(dataId, group); - Assert.assertEquals(cacheData, clientWorker.getCache(dataId, group)); + assertEquals(cacheData, clientWorker.getCache(dataId, group)); } @Test - public void testListenerWithTenant() throws NacosException { + void testListenerWithTenant() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -180,37 +182,37 @@ public void receiveConfigInfo(String configInfo) { String dataId = "a"; String group = "b"; - + clientWorker.addTenantListeners(dataId, group, Collections.singletonList(listener)); List listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(1, listeners.size()); - Assert.assertEquals(listener, listeners.get(0)); + assertEquals(1, listeners.size()); + assertEquals(listener, listeners.get(0)); clientWorker.removeTenantListener(dataId, group, listener); listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(0, listeners.size()); + assertEquals(0, listeners.size()); String content = "d"; clientWorker.addTenantListenersWithContent(dataId, group, content, null, Collections.singletonList(listener)); listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(1, listeners.size()); - Assert.assertEquals(listener, listeners.get(0)); + assertEquals(1, listeners.size()); + assertEquals(listener, listeners.get(0)); clientWorker.removeTenantListener(dataId, group, listener); listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(0, listeners.size()); + assertEquals(0, listeners.size()); String tenant = "c"; CacheData cacheData = clientWorker.addCacheDataIfAbsent(dataId, group, tenant); - Assert.assertEquals(cacheData, clientWorker.getCache(dataId, group, tenant)); + assertEquals(cacheData, clientWorker.getCache(dataId, group, tenant)); clientWorker.removeCache(dataId, group, tenant); - Assert.assertNull(clientWorker.getCache(dataId, group, tenant)); + assertNull(clientWorker.getCache(dataId, group, tenant)); } @Test - public void testPublishConfigSuccess() throws NacosException { + void testPublishConfigSuccess() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -234,12 +236,12 @@ public void testPublishConfigSuccess() throws NacosException { .thenReturn(new ConfigPublishResponse()); boolean b = clientWorker.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, null, casMd5, type); - Assert.assertTrue(b); + assertTrue(b); } @Test - public void testPublishConfigFail() throws NacosException { + void testPublishConfigFail() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -263,12 +265,12 @@ public void testPublishConfigFail() throws NacosException { .thenReturn(ConfigPublishResponse.buildFailResponse(503, "over limit")); boolean b = clientWorker.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, null, casMd5, type); - Assert.assertFalse(b); + assertFalse(b); } @Test - public void testPublishConfigException() throws NacosException { + void testPublishConfigException() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -291,12 +293,12 @@ public void testPublishConfigException() throws NacosException { Mockito.when(rpcClient.request(any(ConfigPublishRequest.class), anyLong())).thenThrow(new NacosException()); boolean b = clientWorker.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, null, casMd5, type); - Assert.assertFalse(b); + assertFalse(b); } @Test - public void testRemoveConfig() throws NacosException { + void testRemoveConfig() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); @@ -315,16 +317,16 @@ public void testRemoveConfig() throws NacosException { .thenThrow(new NacosException(503, "overlimit")); clientWorker.removeConfig(dataId, group, tenant, tag); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("overlimit", e.getErrMsg()); - Assert.assertEquals(503, e.getErrCode()); + assertEquals("overlimit", e.getErrMsg()); + assertEquals(503, e.getErrCode()); } } @Test - public void testGeConfigConfigSuccess() throws NacosException { + void testGeConfigConfigSuccess() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -340,14 +342,14 @@ public void testGeConfigConfigSuccess() throws NacosException { .thenReturn(ConfigQueryResponse.buildSuccessResponse(content)); ConfigResponse configResponse = clientWorker.getServerConfig(dataId, group, tenant, 100, true); - Assert.assertEquals(content, configResponse.getContent()); + assertEquals(content, configResponse.getContent()); localConfigInfoProcessorMockedStatic.verify( () -> LocalConfigInfoProcessor.saveSnapshot(eq(clientWorker.getAgentName()), eq(dataId), eq(group), eq(tenant), eq(content)), times(1)); } @Test - public void testHandleConfigChangeReqeust() throws Exception { + void testHandleConfigChangeReqeust() throws Exception { Properties prop = new Properties(); String tenant = "c"; @@ -377,7 +379,7 @@ public void testHandleConfigChangeReqeust() throws Exception { } @Test - public void testHandleClientMetricsReqeust() throws Exception { + void testHandleClientMetricsReqeust() throws Exception { Properties prop = new Properties(); String tenant = "c"; @@ -418,15 +420,15 @@ public void testHandleClientMetricsReqeust() throws Exception { String metricValues = jsonNode.get("metricValues") .get(ClientConfigMetricRequest.MetricsKey.build(ClientConfigMetricRequest.MetricsKey.CACHE_DATA, GroupKey.getKeyTenant(dataId, group, tenant)).toString()).textValue(); - + int colonIndex = metricValues.lastIndexOf(":"); - Assert.assertEquals(content, metricValues.substring(0, colonIndex)); - Assert.assertEquals(md5, metricValues.substring(colonIndex + 1, metricValues.length())); + assertEquals(content, metricValues.substring(0, colonIndex)); + assertEquals(md5, metricValues.substring(colonIndex + 1, metricValues.length())); } @Test - public void testGeConfigConfigNotFound() throws NacosException { + void testGeConfigConfigNotFound() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -441,7 +443,7 @@ public void testGeConfigConfigNotFound() throws NacosException { Mockito.when(rpcClient.request(any(ConfigQueryRequest.class), anyLong())).thenReturn(configQueryResponse); ConfigResponse configResponse = clientWorker.getServerConfig(dataId, group, tenant, 100, true); - Assert.assertNull(configResponse.getContent()); + assertNull(configResponse.getContent()); localConfigInfoProcessorMockedStatic.verify( () -> LocalConfigInfoProcessor.saveSnapshot(eq(clientWorker.getAgentName()), eq(dataId), eq(group), eq(tenant), eq(null)), times(1)); @@ -449,7 +451,7 @@ public void testGeConfigConfigNotFound() throws NacosException { } @Test - public void testGeConfigConfigConflict() throws NacosException { + void testGeConfigConfigConflict() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -465,32 +467,32 @@ public void testGeConfigConfigConflict() throws NacosException { try { clientWorker.getServerConfig(dataId, group, tenant, 100, true); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals(NacosException.CONFLICT, e.getErrCode()); + assertEquals(NacosException.CONFLICT, e.getErrCode()); } } @Test - public void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties); clientWorker.shutdown(); Field agent1 = ClientWorker.class.getDeclaredField("agent"); agent1.setAccessible(true); ConfigTransportClient o = (ConfigTransportClient) agent1.get(clientWorker); - Assert.assertTrue(o.executor.isShutdown()); + assertTrue(o.executor.isShutdown()); agent1.setAccessible(false); - - Assert.assertNull(clientWorker.getAgentName()); + + assertNull(clientWorker.getAgentName()); } @Test - public void testExecuteConfigListen() throws Exception { + void testExecuteConfigListen() throws Exception { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -511,7 +513,7 @@ public void testExecuteConfigListen() throws Exception { String dataIdUseLocalCache = "dataIdUseLocalCache" + System.currentTimeMillis(); CacheData cacheUseLocalCache = useLocalCache(filter, agent.getName(), dataIdUseLocalCache, group, tenant, "content" + System.currentTimeMillis()); - Assert.assertFalse(cacheUseLocalCache.isUseLocalConfigInfo()); + assertFalse(cacheUseLocalCache.isUseLocalConfigInfo()); cacheDatas.add(cacheUseLocalCache); @@ -570,11 +572,11 @@ public void receiveConfigInfo(String configInfo) { (clientWorker.getAgent()).executeConfigListen(); //assert //use local cache. - Assert.assertTrue(cacheUseLocalCache.isUseLocalConfigInfo()); + assertTrue(cacheUseLocalCache.isUseLocalConfigInfo()); //discard cache to be deleted. - Assert.assertFalse(cacheMapMocked.get().containsKey(GroupKey.getKeyTenant(dataIdDiscard, group, tenant))); + assertFalse(cacheMapMocked.get().containsKey(GroupKey.getKeyTenant(dataIdDiscard, group, tenant))); //normal cache listener be notified. - Assert.assertEquals(configQueryResponse.getContent(), normalContent.get()); + assertEquals(configQueryResponse.getContent(), normalContent.get()); } @@ -616,28 +618,28 @@ private CacheData useLocalCache(ConfigFilterChainManager filter, String envName, } @Test - public void testIsHealthServer() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testIsHealthServer() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties); ClientWorker.ConfigRpcTransportClient client = Mockito.mock(ClientWorker.ConfigRpcTransportClient.class); Mockito.when(client.isHealthServer()).thenReturn(Boolean.TRUE); - + Field declaredField = ClientWorker.class.getDeclaredField("agent"); declaredField.setAccessible(true); declaredField.set(clientWorker, client); - - Assert.assertTrue(clientWorker.isHealthServer()); - + + assertTrue(clientWorker.isHealthServer()); + Mockito.when(client.isHealthServer()).thenReturn(Boolean.FALSE); assertFalse(clientWorker.isHealthServer()); } @Test - public void testPutCache() throws Exception { + void testPutCache() throws Exception { // 反射调用私有方法putCacheIfAbsent Method putCacheMethod = ClientWorker.class.getDeclaredMethod("putCache", String.class, CacheData.class); putCacheMethod.setAccessible(true); @@ -655,17 +657,16 @@ public void testPutCache() throws Exception { clientWorker); // 检查cacheMap是否包含特定的key assertNotNull(cacheMapRef.get().get(key)); - Assert.assertEquals(cacheData, cacheMapRef.get().get(key)); + assertEquals(cacheData, cacheMapRef.get().get(key)); // 测试再次插入相同的key将覆盖原始的值 CacheData newCacheData = new CacheData(filter, "newEnv", "newDataId", "newGroup"); putCacheMethod.invoke(clientWorker, key, newCacheData); // 检查key对应的value是否改变为newCacheData - Assert.assertEquals(newCacheData, cacheMapRef.get().get(key)); + assertEquals(newCacheData, cacheMapRef.get().get(key)); } @Test - public void testAddListenersEnsureCacheDataSafe() - throws NacosException, IllegalAccessException, NoSuchFieldException { + void testAddListenersEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; // 将key-cacheData插入到cacheMap中 @@ -696,7 +697,7 @@ public void testAddListenersEnsureCacheDataSafe() } @Test - public void testAddTenantListenersEnsureCacheDataSafe() + void testAddTenantListenersEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; @@ -729,7 +730,7 @@ public void testAddTenantListenersEnsureCacheDataSafe() } @Test - public void testAddTenantListenersWithContentEnsureCacheDataSafe() + void testAddTenantListenersWithContentEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java index f83713720e5..520d7725c2a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java @@ -17,23 +17,24 @@ package com.alibaba.nacos.client.config.impl; import com.alibaba.nacos.api.config.ConfigChangeItem; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; -public class ConfigChangeHandlerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigChangeHandlerTest { @Test - public void testParseProperties() throws IOException { + void testParseProperties() throws IOException { Map properties = ConfigChangeHandler.getInstance().parseChangeData("", "app.name = nacos", "properties"); - Assert.assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); + assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); } @Test - public void testParseYaml() throws IOException { + void testParseYaml() throws IOException { Map properties = ConfigChangeHandler.getInstance().parseChangeData("", "app:\n name: nacos", "yaml"); - Assert.assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); + assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java index 71355f74975..2ca8c0a0775 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java @@ -16,33 +16,33 @@ package com.alibaba.nacos.client.config.impl; -import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.http.client.NacosRestTemplate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -public class ConfigHttpClientManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ConfigHttpClientManagerTest { @Test - public void test() { + void test() { final ConfigHttpClientManager instance1 = ConfigHttpClientManager.getInstance(); final ConfigHttpClientManager instance2 = ConfigHttpClientManager.getInstance(); - Assert.assertEquals(instance1, instance2); - + assertEquals(instance1, instance2); + final NacosRestTemplate nacosRestTemplate = instance1.getNacosRestTemplate(); - Assert.assertNotNull(nacosRestTemplate); - + assertNotNull(nacosRestTemplate); + final int time1 = instance1.getConnectTimeoutOrDefault(10); - Assert.assertEquals(1000, time1); + assertEquals(1000, time1); final int time2 = instance1.getConnectTimeoutOrDefault(2000); - Assert.assertEquals(2000, time2); - - try { + assertEquals(2000, time2); + + Assertions.assertDoesNotThrow(() -> { instance1.shutdown(); - } catch (NacosException e) { - Assert.fail(); - } + }); } - + } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java index f481066306f..d48bdecd25e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java @@ -16,22 +16,24 @@ package com.alibaba.nacos.client.config.impl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LimiterTest { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LimiterTest { @Test - public void testIsLimit() { + void testIsLimit() { String keyId = "a"; //For initiating. - Assert.assertFalse(Limiter.isLimit(keyId)); + assertFalse(Limiter.isLimit(keyId)); long start = System.currentTimeMillis(); for (int j = 0; j < 5; j++) { - Assert.assertFalse(Limiter.isLimit(keyId)); + assertFalse(Limiter.isLimit(keyId)); } long elapse = System.currentTimeMillis() - start; // assert < limit 5qps - Assert.assertTrue(elapse > 980); + assertTrue(elapse > 980); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java index 9f06717c525..e667fd0f15d 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java @@ -17,42 +17,45 @@ package com.alibaba.nacos.client.config.impl; import com.alibaba.nacos.api.config.ConfigChangeItem; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; -public class PropertiesChangeParserTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PropertiesChangeParserTest { private final PropertiesChangeParser parser = new PropertiesChangeParser(); private final String type = "properties"; @Test - public void testType() { - Assert.assertTrue(parser.isResponsibleFor(type)); + void testType() { + assertTrue(parser.isResponsibleFor(type)); } @Test - public void testAddKey() throws IOException { + void testAddKey() throws IOException { Map map = parser.doParse("", "app.name = nacos", type); - Assert.assertNull(map.get("app.name").getOldValue()); - Assert.assertEquals("nacos", map.get("app.name").getNewValue()); + assertNull(map.get("app.name").getOldValue()); + assertEquals("nacos", map.get("app.name").getNewValue()); } @Test - public void testRemoveKey() throws IOException { + void testRemoveKey() throws IOException { Map map = parser.doParse("app.name = nacos", "", type); - Assert.assertEquals("nacos", map.get("app.name").getOldValue()); - Assert.assertNull(map.get("app.name").getNewValue()); + assertEquals("nacos", map.get("app.name").getOldValue()); + assertNull(map.get("app.name").getNewValue()); } @Test - public void testModifyKey() throws IOException { + void testModifyKey() throws IOException { Map map = parser.doParse("app.name = rocketMQ", "app.name = nacos", type); - Assert.assertEquals("rocketMQ", map.get("app.name").getOldValue()); - Assert.assertEquals("nacos", map.get("app.name").getNewValue()); + assertEquals("rocketMQ", map.get("app.name").getOldValue()); + assertEquals("nacos", map.get("app.name").getNewValue()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java index c0496b80f92..c38f620cd5c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java @@ -19,8 +19,7 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.ArrayList; @@ -29,17 +28,23 @@ import java.util.Properties; import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTP_PREFIX; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; -public class ServerListManagerTest { +class ServerListManagerTest { @Test - public void testStart() throws NacosException { + void testStart() throws NacosException { final ServerListManager mgr = new ServerListManager("localhost", 0); try { mgr.start(); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals( + assertEquals( "fail to get NACOS-server serverlist! env:custom-localhost_0_nacos_serverlist, not connnect url:http://localhost:0/nacos/serverlist", e.getErrMsg()); } @@ -47,26 +52,26 @@ public void testStart() throws NacosException { } @Test - public void testGetter() throws NacosException { + void testGetter() throws NacosException { { final ServerListManager mgr = new ServerListManager(); - Assert.assertEquals("nacos", mgr.getContentPath()); - Assert.assertEquals("default", mgr.getName()); - Assert.assertEquals("", mgr.getTenant()); - Assert.assertEquals("", mgr.getNamespace()); - Assert.assertEquals("1.1.1.1-2.2.2.2_8848", mgr.getFixedNameSuffix("http://1.1.1.1", "2.2.2.2:8848")); + assertEquals("nacos", mgr.getContentPath()); + assertEquals("default", mgr.getName()); + assertEquals("", mgr.getTenant()); + assertEquals("", mgr.getNamespace()); + assertEquals("1.1.1.1-2.2.2.2_8848", mgr.getFixedNameSuffix("http://1.1.1.1", "2.2.2.2:8848")); } { Properties properties = new Properties(); properties.put(PropertyKeyConst.CONTEXT_PATH, "aaa"); properties.put(PropertyKeyConst.ENDPOINT, "endpoint"); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); final ServerListManager mgr2 = new ServerListManager(nacosClientProperties); - Assert.assertEquals("aaa", mgr2.getContentPath()); + assertEquals("aaa", mgr2.getContentPath()); } - + // Test https { Properties properties = new Properties(); @@ -74,56 +79,58 @@ public void testGetter() throws NacosException { properties.put(PropertyKeyConst.SERVER_ADDR, "https://1.1.1.1:8848"); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); final ServerListManager mgr2 = new ServerListManager(nacosClientProperties); - Assert.assertEquals("aaa", mgr2.getContentPath()); - Assert.assertEquals("[https://1.1.1.1:8848]", mgr2.getServerUrls().toString()); + assertEquals("aaa", mgr2.getContentPath()); + assertEquals("[https://1.1.1.1:8848]", mgr2.getServerUrls().toString()); } { Properties properties2 = new Properties(); properties2.put(PropertyKeyConst.CONTEXT_PATH, "aaa"); properties2.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848"); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties2); final ServerListManager mgr3 = new ServerListManager(nacosClientProperties); - Assert.assertEquals(1, mgr3.getServerUrls().size()); - Assert.assertEquals("http://1.1.1.1:8848", mgr3.getServerUrls().get(0)); - Assert.assertEquals("[http://1.1.1.1:8848]", mgr3.getUrlString()); - Assert.assertTrue(mgr3.contain("http://1.1.1.1:8848")); - Assert.assertEquals("ServerManager-fixed-1.1.1.1_8848-[http://1.1.1.1:8848]", mgr3.toString()); + assertEquals(1, mgr3.getServerUrls().size()); + assertEquals("http://1.1.1.1:8848", mgr3.getServerUrls().get(0)); + assertEquals("[http://1.1.1.1:8848]", mgr3.getUrlString()); + assertTrue(mgr3.contain("http://1.1.1.1:8848")); + assertEquals("ServerManager-fixed-1.1.1.1_8848-[http://1.1.1.1:8848]", mgr3.toString()); } - + { Properties properties3 = new Properties(); properties3.put(PropertyKeyConst.CONTEXT_PATH, "aaa"); properties3.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848,2.2.2.2:8848"); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties3); final ServerListManager mgr4 = new ServerListManager(nacosClientProperties); - Assert.assertEquals(2, mgr4.getServerUrls().size()); - Assert.assertEquals("http://1.1.1.1:8848", mgr4.getServerUrls().get(0)); - Assert.assertEquals("http://2.2.2.2:8848", mgr4.getServerUrls().get(1)); - Assert.assertTrue(mgr4.contain("http://1.1.1.1:8848")); - Assert.assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", mgr4.toString()); + assertEquals(2, mgr4.getServerUrls().size()); + assertEquals("http://1.1.1.1:8848", mgr4.getServerUrls().get(0)); + assertEquals("http://2.2.2.2:8848", mgr4.getServerUrls().get(1)); + assertTrue(mgr4.contain("http://1.1.1.1:8848")); + assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", + mgr4.toString()); } - + { Properties properties4 = new Properties(); properties4.put(PropertyKeyConst.CONTEXT_PATH, "aaa"); properties4.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848;2.2.2.2:8848"); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties4); final ServerListManager mgr5 = new ServerListManager(nacosClientProperties); - Assert.assertEquals(2, mgr5.getServerUrls().size()); - Assert.assertEquals("http://1.1.1.1:8848", mgr5.getServerUrls().get(0)); - Assert.assertEquals("http://2.2.2.2:8848", mgr5.getServerUrls().get(1)); - Assert.assertTrue(mgr5.contain("http://1.1.1.1:8848")); - Assert.assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", mgr5.toString()); + assertEquals(2, mgr5.getServerUrls().size()); + assertEquals("http://1.1.1.1:8848", mgr5.getServerUrls().get(0)); + assertEquals("http://2.2.2.2:8848", mgr5.getServerUrls().get(1)); + assertTrue(mgr5.contain("http://1.1.1.1:8848")); + assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", + mgr5.toString()); } } @Test - public void testIterator() { + void testIterator() { List addrs = new ArrayList<>(); String addr = "1.1.1.1:8848"; addrs.add(addr); @@ -131,26 +138,26 @@ public void testIterator() { // new iterator final Iterator it = mgr.iterator(); - Assert.assertTrue(it.hasNext()); - Assert.assertEquals(addr, it.next()); + assertTrue(it.hasNext()); + assertEquals(addr, it.next()); - Assert.assertNull(mgr.getIterator()); + assertNull(mgr.getIterator()); mgr.refreshCurrentServerAddr(); - Assert.assertNotNull(mgr.getIterator()); + assertNotNull(mgr.getIterator()); final String currentServerAddr = mgr.getCurrentServerAddr(); - Assert.assertEquals(addr, currentServerAddr); + assertEquals(addr, currentServerAddr); final String nextServerAddr = mgr.getNextServerAddr(); - Assert.assertEquals(addr, nextServerAddr); + assertEquals(addr, nextServerAddr); final Iterator iterator1 = mgr.iterator(); - Assert.assertTrue(iterator1.hasNext()); + assertTrue(iterator1.hasNext()); } @Test - public void testAddressServerBaseServerAddrsStr() throws NacosException { + void testAddressServerBaseServerAddrsStr() throws NacosException { Properties properties = new Properties(); String serverAddrStr = "nacos.test.com:8080"; properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddrStr); @@ -158,12 +165,12 @@ public void testAddressServerBaseServerAddrsStr() throws NacosException { properties.setProperty(PropertyKeyConst.CONTEXT_PATH, endpointContextPath); final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ServerListManager serverListManager = new ServerListManager(clientProperties); - Assert.assertEquals(1, serverListManager.serverUrls.size()); - Assert.assertTrue(serverListManager.serverUrls.contains(HTTP_PREFIX + serverAddrStr)); + assertEquals(1, serverListManager.serverUrls.size()); + assertTrue(serverListManager.serverUrls.contains(HTTP_PREFIX + serverAddrStr)); } @Test - public void testAddressServerBaseEndpoint() throws NacosException { + void testAddressServerBaseEndpoint() throws NacosException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -173,12 +180,12 @@ public void testAddressServerBaseEndpoint() throws NacosException { properties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, endpointContextPath); final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ServerListManager serverListManager = new ServerListManager(clientProperties); - Assert.assertTrue(serverListManager.addressServerUrl.startsWith( + assertTrue(serverListManager.addressServerUrl.startsWith( HTTP_PREFIX + endpoint + ":" + endpointPort + endpointContextPath)); } @Test - public void testInitParam() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testInitParam() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -193,26 +200,26 @@ public void testInitParam() throws NacosException, NoSuchFieldException, Illegal Field endpointField = ServerListManager.class.getDeclaredField("endpoint"); endpointField.setAccessible(true); String fieldEndpoint = (String) endpointField.get(serverListManager); - Assert.assertEquals(endpoint, fieldEndpoint); + assertEquals(endpoint, fieldEndpoint); Field endpointPortField = ServerListManager.class.getDeclaredField("endpointPort"); endpointPortField.setAccessible(true); String fieldEndpointPort = String.valueOf(endpointPortField.get(serverListManager)); - Assert.assertEquals(endpointPort, fieldEndpointPort); + assertEquals(endpointPort, fieldEndpointPort); Field endpointContextPathField = ServerListManager.class.getDeclaredField("endpointContextPath"); endpointContextPathField.setAccessible(true); String fieldEndpointContextPath = String.valueOf(endpointContextPathField.get(serverListManager)); - Assert.assertEquals(endpointContextPath, fieldEndpointContextPath); + assertEquals(endpointContextPath, fieldEndpointContextPath); Field contentPathField = ServerListManager.class.getDeclaredField("contentPath"); contentPathField.setAccessible(true); String fieldContentPath = String.valueOf(contentPathField.get(serverListManager)); - Assert.assertEquals(fieldContentPath, contextPath); + assertEquals(fieldContentPath, contextPath); } @Test - public void testWithEndpointContextPath() throws NacosException { + void testWithEndpointContextPath() throws NacosException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -224,12 +231,12 @@ public void testWithEndpointContextPath() throws NacosException { properties.setProperty(PropertyKeyConst.CONTEXT_PATH, contextPath); final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ServerListManager serverListManager = new ServerListManager(clientProperties); - Assert.assertTrue(serverListManager.addressServerUrl.contains(endpointContextPath)); - Assert.assertTrue(serverListManager.getName().contains("endpointContextPath")); + assertTrue(serverListManager.addressServerUrl.contains(endpointContextPath)); + assertTrue(serverListManager.getName().contains("endpointContextPath")); } @Test - public void testWithoutEndpointContextPath() throws NacosException { + void testWithoutEndpointContextPath() throws NacosException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -240,9 +247,9 @@ public void testWithoutEndpointContextPath() throws NacosException { final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ServerListManager serverListManager = new ServerListManager(clientProperties); String endpointContextPath = "/endpointContextPath"; - Assert.assertFalse(serverListManager.addressServerUrl.contains(endpointContextPath)); - Assert.assertTrue(serverListManager.addressServerUrl.contains(contextPath)); - Assert.assertFalse(serverListManager.getName().contains("endpointContextPath")); - Assert.assertTrue(serverListManager.getName().contains("contextPath")); + assertFalse(serverListManager.addressServerUrl.contains(endpointContextPath)); + assertTrue(serverListManager.addressServerUrl.contains(contextPath)); + assertFalse(serverListManager.getName().contains("endpointContextPath")); + assertTrue(serverListManager.getName().contains("contextPath")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java index 10d1b765029..b0157672a38 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java @@ -18,46 +18,50 @@ import com.alibaba.nacos.api.config.ConfigChangeItem; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; -public class YmlChangeParserTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class YmlChangeParserTest { private final YmlChangeParser parser = new YmlChangeParser(); private final String type = "yaml"; @Test - public void testType() { - Assert.assertTrue(parser.isResponsibleFor(type)); + void testType() { + assertTrue(parser.isResponsibleFor(type)); } @Test - public void testAddKey() throws IOException { + void testAddKey() throws IOException { Map map = parser.doParse("", "app:\n name: nacos", type); - Assert.assertNull(map.get("app.name").getOldValue()); - Assert.assertEquals("nacos", map.get("app.name").getNewValue()); + assertNull(map.get("app.name").getOldValue()); + assertEquals("nacos", map.get("app.name").getNewValue()); } @Test - public void testRemoveKey() throws IOException { + void testRemoveKey() throws IOException { Map map = parser.doParse("app:\n name: nacos", "", type); - Assert.assertEquals("nacos", map.get("app.name").getOldValue()); - Assert.assertNull(map.get("app.name").getNewValue()); + assertEquals("nacos", map.get("app.name").getOldValue()); + assertNull(map.get("app.name").getNewValue()); } @Test - public void testModifyKey() throws IOException { + void testModifyKey() throws IOException { Map map = parser.doParse("app:\n name: rocketMQ", "app:\n name: nacos", type); - Assert.assertEquals("rocketMQ", map.get("app.name").getOldValue()); - Assert.assertEquals("nacos", map.get("app.name").getNewValue()); + assertEquals("rocketMQ", map.get("app.name").getOldValue()); + assertEquals("nacos", map.get("app.name").getNewValue()); } @Test - public void testComplexYaml() throws IOException { + void testComplexYaml() throws IOException { /* * map: * key1: "string" @@ -70,15 +74,17 @@ public void testComplexYaml() throws IOException { String s = "map:\n" + " key1: \"string\"\n" + " key2:\n" + " - item1\n" + " - item2\n" + " - item3\n" + " key3: 123 \n"; Map map = parser.doParse(s, s, type); - Assert.assertEquals(0, map.size()); + assertEquals(0, map.size()); } - @Test(expected = NacosRuntimeException.class) - public void testChangeInvalidKey() { - parser.doParse("anykey:\n a", - "anykey: !!javax.script.ScriptEngineManager [\n" + " !!java.net.URLClassLoader [[\n" - + " !!java.net.URL [\"http://[yourhost]:[port]/yaml-payload.jar\"]\n" + " ]]\n" + "]", - type); + @Test + void testChangeInvalidKey() { + assertThrows(NacosRuntimeException.class, () -> { + parser.doParse("anykey:\n a", + "anykey: !!javax.script.ScriptEngineManager [\n" + " !!java.net.URLClassLoader [[\n" + + " !!java.net.URL [\"http://[yourhost]:[port]/yaml-payload.jar\"]\n" + " ]]\n" + "]", + type); + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java index 12f2898c6fe..e57f270dee9 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java @@ -17,16 +17,17 @@ package com.alibaba.nacos.client.config.listener.impl; import com.alibaba.nacos.api.config.ConfigChangeEvent; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayDeque; import java.util.Deque; -public class AbstractConfigChangeListenerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AbstractConfigChangeListenerTest { @Test - public void receiveConfigInfo() { + void receiveConfigInfo() { final Deque data = new ArrayDeque(); AbstractConfigChangeListener a = new AbstractConfigChangeListener() { @Override @@ -41,6 +42,6 @@ public void receiveConfigInfo(String configInfo) { }; a.receiveConfigInfo("foo"); final String actual = data.poll(); - Assert.assertEquals("foo", actual); + assertEquals("foo", actual); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java index 9f7f4e63236..490224544f3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java @@ -16,17 +16,19 @@ package com.alibaba.nacos.client.config.listener.impl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayDeque; import java.util.Deque; import java.util.Properties; -public class PropertiesListenerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class PropertiesListenerTest { @Test - public void testReceiveConfigInfo() { + void testReceiveConfigInfo() { final Deque q2 = new ArrayDeque(); PropertiesListener a = new PropertiesListener() { @Override @@ -36,13 +38,13 @@ public void innerReceive(Properties properties) { }; a.receiveConfigInfo("foo=bar"); final Properties actual = q2.poll(); - Assert.assertEquals(1, actual.size()); - Assert.assertEquals("bar", actual.getProperty("foo")); + assertEquals(1, actual.size()); + assertEquals("bar", actual.getProperty("foo")); } @Test - public void testReceiveConfigInfoEmpty() { + void testReceiveConfigInfoEmpty() { final Deque q2 = new ArrayDeque(); PropertiesListener a = new PropertiesListener() { @Override @@ -52,11 +54,11 @@ public void innerReceive(Properties properties) { }; a.receiveConfigInfo(""); final Properties actual = q2.poll(); - Assert.assertNull(actual); + assertNull(actual); } @Test - public void testReceiveConfigInfoIsNotProperties() { + void testReceiveConfigInfoIsNotProperties() { final Deque q2 = new ArrayDeque(); PropertiesListener a = new PropertiesListener() { @Override @@ -66,11 +68,11 @@ public void innerReceive(Properties properties) { }; a.receiveConfigInfo(null); final Properties actual = q2.poll(); - Assert.assertNull(actual); + assertNull(actual); } @Test - public void testInnerReceive() { + void testInnerReceive() { final Deque q2 = new ArrayDeque(); PropertiesListener a = new PropertiesListener() { @Override @@ -82,8 +84,8 @@ public void innerReceive(Properties properties) { input.put("foo", "bar"); a.innerReceive(input); final Properties actual = q2.poll(); - Assert.assertEquals(1, actual.size()); - Assert.assertEquals("bar", actual.getProperty("foo")); + assertEquals(1, actual.size()); + assertEquals("bar", actual.getProperty("foo")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java index ba2e0b33041..bc2c12b3f19 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java @@ -18,103 +18,108 @@ package com.alibaba.nacos.client.config.utils; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.Arrays; import static com.alibaba.nacos.api.common.Constants.WORD_SEPARATOR; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ContentUtilsTest { - - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); +class ContentUtilsTest { @Test - public void testVerifyIncrementPubContent() { + void testVerifyIncrementPubContent() { String content = "aabbb"; ContentUtils.verifyIncrementPubContent(content); } @Test - public void testVerifyIncrementPubContentFail1() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("publish/delete content can not be null"); - String content = null; - ContentUtils.verifyIncrementPubContent(content); + void testVerifyIncrementPubContentFail1() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String content = null; + ContentUtils.verifyIncrementPubContent(content); + }); + assertTrue(exception.getMessage().contains("publish/delete content can not be null")); } @Test - public void testVerifyIncrementPubContentFail2() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("publish/delete content can not contain return and linefeed"); - String content = "aa\rbbb"; - ContentUtils.verifyIncrementPubContent(content); + void testVerifyIncrementPubContentFail2() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String content = "aa\rbbb"; + ContentUtils.verifyIncrementPubContent(content); + }); + assertTrue(exception.getMessage().contains("publish/delete content can not contain return and linefeed")); } @Test - public void testVerifyIncrementPubContentFail3() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("publish/delete content can not be null"); - String content = ""; - ContentUtils.verifyIncrementPubContent(content); + void testVerifyIncrementPubContentFail3() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String content = ""; + ContentUtils.verifyIncrementPubContent(content); + }); + assertTrue(exception.getMessage().contains("publish/delete content can not be null")); } @Test - public void testVerifyIncrementPubContentFail4() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("publish/delete content can not contain(char)2"); - String content = "aa" + WORD_SEPARATOR + "bbb"; - ContentUtils.verifyIncrementPubContent(content); + void testVerifyIncrementPubContentFail4() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String content = "aa" + WORD_SEPARATOR + "bbb"; + ContentUtils.verifyIncrementPubContent(content); + }); + assertTrue(exception.getMessage().contains("publish/delete content can not contain(char)2")); } @Test - public void testGetContentIdentity() { + void testGetContentIdentity() { String content = "aa" + WORD_SEPARATOR + "bbb"; String content1 = ContentUtils.getContentIdentity(content); - Assert.assertEquals("aa", content1); + assertEquals("aa", content1); } - @Test(expected = IllegalArgumentException.class) - public void testGetContentIdentityFail() { - String content = "aabbb"; - ContentUtils.getContentIdentity(content); + @Test + void testGetContentIdentityFail() { + assertThrows(IllegalArgumentException.class, () -> { + String content = "aabbb"; + ContentUtils.getContentIdentity(content); + }); } @Test - public void testGetContent() { + void testGetContent() { String content = "aa" + WORD_SEPARATOR + "bbb"; String content1 = ContentUtils.getContent(content); - Assert.assertEquals("bbb", content1); + assertEquals("bbb", content1); } - @Test(expected = IllegalArgumentException.class) - public void testGetContentFail() { - String content = "aabbb"; - ContentUtils.getContent(content); + @Test + void testGetContentFail() { + assertThrows(IllegalArgumentException.class, () -> { + String content = "aabbb"; + ContentUtils.getContent(content); + }); } @Test - public void testTruncateContent() { + void testTruncateContent() { String content = "aa"; String actual = ContentUtils.truncateContent(content); - Assert.assertEquals(content, actual); + assertEquals(content, actual); } @Test - public void testTruncateLongContent() { + void testTruncateLongContent() { char[] arr = new char[101]; Arrays.fill(arr, 'a'); String content = new String(arr); String actual = ContentUtils.truncateContent(content); - Assert.assertEquals(content.substring(0, 100) + "...", actual); + assertEquals(content.substring(0, 100) + "...", actual); } @Test - public void testTruncateContentNull() { + void testTruncateContentNull() { String actual = ContentUtils.truncateContent(null); - Assert.assertEquals("", actual); + assertEquals("", actual); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java index fcb39767a3f..a5966243778 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java @@ -18,27 +18,29 @@ package com.alibaba.nacos.client.config.utils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -public class JvmUtilTest { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class JvmUtilTest { Method initMethod; - @Before - public void setUp() throws NoSuchMethodException { + @BeforeEach + void setUp() throws NoSuchMethodException { initMethod = JvmUtil.class.getDeclaredMethod("init"); initMethod.setAccessible(true); } - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { System.clearProperty("isMultiInstance"); Field field = JvmUtil.class.getDeclaredField("isMultiInstance"); field.setAccessible(true); @@ -46,17 +48,17 @@ public void tearDown() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testIsMultiInstance() throws InvocationTargetException, IllegalAccessException { + void testIsMultiInstance() throws InvocationTargetException, IllegalAccessException { initMethod.invoke(JvmUtil.class); Boolean multiInstance = JvmUtil.isMultiInstance(); - Assert.assertFalse(multiInstance); + assertFalse(multiInstance); } @Test - public void testIsMultiInstance2() throws InvocationTargetException, IllegalAccessException { + void testIsMultiInstance2() throws InvocationTargetException, IllegalAccessException { System.setProperty("isMultiInstance", "true"); initMethod.invoke(JvmUtil.class); Boolean multiInstance = JvmUtil.isMultiInstance(); - Assert.assertTrue(multiInstance); + assertTrue(multiInstance); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java index ac9142edb3e..f28bfe4fd5f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java @@ -19,39 +19,39 @@ package com.alibaba.nacos.client.config.utils; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; -public class ParamUtilsTest { - - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class ParamUtilsTest { @Test - public void testIsValid() { + void testIsValid() { String content = "abcABC09.:_-"; - Assert.assertTrue(ParamUtils.isValid(content)); + assertTrue(ParamUtils.isValid(content)); content = null; - Assert.assertFalse(ParamUtils.isValid(content)); + assertFalse(ParamUtils.isValid(content)); content = "@"; - Assert.assertFalse(ParamUtils.isValid(content)); + assertFalse(ParamUtils.isValid(content)); content = "+"; - Assert.assertFalse(ParamUtils.isValid(content)); + assertFalse(ParamUtils.isValid(content)); content = "/"; - Assert.assertFalse(ParamUtils.isValid(content)); + assertFalse(ParamUtils.isValid(content)); } @Test - public void testCheckTdg() throws NacosException { + void testCheckTdg() throws NacosException { String tenant = "a"; String dataId = "b"; String group = "c"; @@ -59,29 +59,31 @@ public void testCheckTdg() throws NacosException { } @Test - public void testCheckTdgFail1() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("dataId invalid"); - - String tenant = "a"; - String dataId = ""; - String group = "c"; - ParamUtils.checkTdg(tenant, dataId, group); + void testCheckTdgFail1() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + String tenant = "a"; + String dataId = ""; + String group = "c"; + ParamUtils.checkTdg(tenant, dataId, group); + }); + assertTrue(exception.getMessage().contains("dataId invalid")); } @Test - public void testCheckTdgFail2() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("group invalid"); - - String tenant = "a"; - String dataId = "b"; - String group = ""; - ParamUtils.checkTdg(tenant, dataId, group); + void testCheckTdgFail2() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + String tenant = "a"; + String dataId = "b"; + String group = ""; + ParamUtils.checkTdg(tenant, dataId, group); + }); + assertTrue(exception.getMessage().contains("group invalid")); } @Test - public void testCheckKeyParam1() throws NacosException { + void testCheckKeyParam1() throws NacosException { String dataId = "b"; String group = "c"; ParamUtils.checkKeyParam(dataId, group); @@ -90,23 +92,23 @@ public void testCheckKeyParam1() throws NacosException { dataId = ""; group = "c"; ParamUtils.checkKeyParam(dataId, group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("dataId invalid", e.getMessage()); + assertEquals("dataId invalid", e.getMessage()); } try { dataId = "b"; group = ""; ParamUtils.checkKeyParam(dataId, group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("group invalid", e.getMessage()); + assertEquals("group invalid", e.getMessage()); } } @Test - public void testCheckKeyParam2() throws NacosException { + void testCheckKeyParam2() throws NacosException { String dataId = "b"; String group = "c"; String datumId = "a"; @@ -117,9 +119,9 @@ public void testCheckKeyParam2() throws NacosException { group = "c"; ParamUtils.checkKeyParam(dataId, group, datumId); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("dataId invalid", e.getMessage()); + assertEquals("dataId invalid", e.getMessage()); } try { @@ -127,9 +129,9 @@ public void testCheckKeyParam2() throws NacosException { group = ""; ParamUtils.checkKeyParam(dataId, group, datumId); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("group invalid", e.getMessage()); + assertEquals("group invalid", e.getMessage()); } try { @@ -138,14 +140,14 @@ public void testCheckKeyParam2() throws NacosException { datumId = ""; ParamUtils.checkKeyParam(dataId, group, datumId); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("datumId invalid", e.getMessage()); + assertEquals("datumId invalid", e.getMessage()); } } @Test - public void testCheckKeyParam3() throws NacosException { + void testCheckKeyParam3() throws NacosException { String dataId = "b"; String group = "c"; ParamUtils.checkKeyParam(Arrays.asList(dataId), group); @@ -154,9 +156,9 @@ public void testCheckKeyParam3() throws NacosException { group = "c"; ParamUtils.checkKeyParam(new ArrayList(), group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("dataIds invalid", e.getMessage()); + assertEquals("dataIds invalid", e.getMessage()); } try { @@ -164,9 +166,9 @@ public void testCheckKeyParam3() throws NacosException { group = "c"; ParamUtils.checkKeyParam(Arrays.asList(dataId), group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("dataId invalid", e.getMessage()); + assertEquals("dataId invalid", e.getMessage()); } try { @@ -174,33 +176,34 @@ public void testCheckKeyParam3() throws NacosException { group = ""; ParamUtils.checkKeyParam(Arrays.asList(dataId), group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("group invalid", e.getMessage()); + assertEquals("group invalid", e.getMessage()); } } @Test - public void testCheckParam() throws NacosException { + void testCheckParam() throws NacosException { String dataId = "b"; String group = "c"; String content = "a"; ParamUtils.checkParam(dataId, group, content); } - + @Test - public void testCheckParamFail() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("content invalid"); - - String dataId = "b"; - String group = "c"; - String content = ""; - ParamUtils.checkParam(dataId, group, content); + void testCheckParamFail() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + String dataId = "b"; + String group = "c"; + String content = ""; + ParamUtils.checkParam(dataId, group, content); + }); + assertTrue(exception.getMessage().contains("content invalid")); } @Test - public void testCheckParam2() throws NacosException { + void testCheckParam2() throws NacosException { String dataId = "b"; String group = "c"; String datumId = "d"; @@ -209,60 +212,65 @@ public void testCheckParam2() throws NacosException { } @Test - public void testCheckParam2Fail() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("content invalid"); - - String dataId = "b"; - String group = "c"; - String datumId = "d"; - String content = ""; - ParamUtils.checkParam(dataId, group, datumId, content); + void testCheckParam2Fail() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + String dataId = "b"; + String group = "c"; + String datumId = "d"; + String content = ""; + ParamUtils.checkParam(dataId, group, datumId, content); + }); + assertTrue(exception.getMessage().contains("content invalid")); } @Test - public void testCheckTenant() throws NacosException { + void testCheckTenant() throws NacosException { String tenant = "a"; ParamUtils.checkTenant(tenant); } @Test - public void testCheckTenantFail() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("tenant invalid"); - String tenant = ""; - ParamUtils.checkTenant(tenant); + void testCheckTenantFail() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + String tenant = ""; + ParamUtils.checkTenant(tenant); + }); + assertTrue(exception.getMessage().contains("tenant invalid")); } @Test - public void testCheckBetaIps() throws NacosException { + void testCheckBetaIps() throws NacosException { ParamUtils.checkBetaIps("127.0.0.1"); } @Test - public void testCheckBetaIpsFail1() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("betaIps invalid"); - - ParamUtils.checkBetaIps(""); + void testCheckBetaIpsFail1() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + ParamUtils.checkBetaIps(""); + }); + assertTrue(exception.getMessage().contains("betaIps invalid")); } @Test - public void testCheckBetaIpsFail2() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("betaIps invalid"); - ParamUtils.checkBetaIps("aaa"); + void testCheckBetaIpsFail2() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + ParamUtils.checkBetaIps("aaa"); + }); + assertTrue(exception.getMessage().contains("betaIps invalid")); } @Test - public void testCheckContent() throws NacosException { + void testCheckContent() throws NacosException { ParamUtils.checkContent("aaa"); } @Test - public void testCheckContentFail() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("content invalid"); - ParamUtils.checkContent(""); + void testCheckContentFail() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + ParamUtils.checkContent(""); + }); + assertTrue(exception.getMessage().contains("content invalid")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java index 13ad8f4364e..2e0990db99f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java @@ -18,21 +18,23 @@ package com.alibaba.nacos.client.config.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SnapShotSwitchTest { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SnapShotSwitchTest { @Test - public void testGetIsSnapShot() { + void testGetIsSnapShot() { Boolean isSnapShot = SnapShotSwitch.getIsSnapShot(); - Assert.assertTrue(isSnapShot); + assertTrue(isSnapShot); SnapShotSwitch.setIsSnapShot(false); - Assert.assertFalse(SnapShotSwitch.getIsSnapShot()); + assertFalse(SnapShotSwitch.getIsSnapShot()); SnapShotSwitch.setIsSnapShot(true); - Assert.assertTrue(SnapShotSwitch.getIsSnapShot()); + assertTrue(SnapShotSwitch.getIsSnapShot()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java b/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java index ce696d99b3c..ce047577211 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java @@ -16,34 +16,39 @@ package com.alibaba.nacos.client.env; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Properties; -public class NacosClientPropertiesTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NacosClientPropertiesTest { - @BeforeClass - public static void init() { + @BeforeAll + static void init() { System.setProperty("nacos.env.first", "jvm"); } - @AfterClass - public static void teardown() { + @AfterAll + static void teardown() { System.clearProperty("nacos.env.first"); } @Test - public void testGetProperty() { + void testGetProperty() { NacosClientProperties.PROTOTYPE.setProperty("nacos.home", "/home/nacos"); final String value = NacosClientProperties.PROTOTYPE.getProperty("nacos.home"); - Assert.assertEquals("/home/nacos", value); + assertEquals("/home/nacos", value); } @Test - public void testGetPropertyMultiLayer() { + void testGetPropertyMultiLayer() { NacosClientProperties.PROTOTYPE.setProperty("top.layer", "top"); @@ -57,85 +62,85 @@ public void testGetPropertyMultiLayer() { layerCEnv.setProperty("c.layer", "c"); String value = layerCEnv.getProperty("c.layer"); - Assert.assertEquals("c", value); + assertEquals("c", value); value = layerCEnv.getProperty("b.layer"); - Assert.assertEquals("b", value); + assertEquals("b", value); value = layerCEnv.getProperty("a.layer"); - Assert.assertEquals("a", value); + assertEquals("a", value); value = layerCEnv.getProperty("top.layer"); - Assert.assertEquals("top", value); + assertEquals("top", value); } @Test - public void testGetPropertyDefaultValue() { + void testGetPropertyDefaultValue() { final String value = NacosClientProperties.PROTOTYPE.getProperty("nacos.home.default", "/home/default_value"); - Assert.assertEquals("/home/default_value", value); + assertEquals("/home/default_value", value); } @Test - public void testGetBoolean() { + void testGetBoolean() { NacosClientProperties.PROTOTYPE.setProperty("use.cluster", "true"); final Boolean value = NacosClientProperties.PROTOTYPE.getBoolean("use.cluster"); - Assert.assertTrue(value); + assertTrue(value); } @Test - public void testGetBooleanDefaultValue() { + void testGetBooleanDefaultValue() { final Boolean value = NacosClientProperties.PROTOTYPE.getBoolean("use.cluster.default", false); - Assert.assertFalse(value); + assertFalse(value); } @Test - public void testGetInteger() { + void testGetInteger() { NacosClientProperties.PROTOTYPE.setProperty("max.timeout", "200"); final Integer value = NacosClientProperties.PROTOTYPE.getInteger("max.timeout"); - Assert.assertEquals(200, value.intValue()); + assertEquals(200, value.intValue()); } @Test - public void testGetIntegerDefaultValue() { + void testGetIntegerDefaultValue() { final Integer value = NacosClientProperties.PROTOTYPE.getInteger("max.timeout.default", 400); - Assert.assertEquals(400, value.intValue()); + assertEquals(400, value.intValue()); } @Test - public void testGetLong() { + void testGetLong() { NacosClientProperties.PROTOTYPE.setProperty("connection.timeout", "200"); final Long value = NacosClientProperties.PROTOTYPE.getLong("connection.timeout"); - Assert.assertEquals(200L, value.longValue()); + assertEquals(200L, value.longValue()); } @Test - public void testGetLongDefault() { + void testGetLongDefault() { final Long value = NacosClientProperties.PROTOTYPE.getLong("connection.timeout.default", 400L); - Assert.assertEquals(400L, value.longValue()); + assertEquals(400L, value.longValue()); } @Test - public void setProperty() { + void setProperty() { NacosClientProperties.PROTOTYPE.setProperty("nacos.set.property", "true"); final String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.set.property"); - Assert.assertEquals("true", ret); + assertEquals("true", ret); } @Test - public void setPropertyWithScope() { + void setPropertyWithScope() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty("nacos.set.property.scope", "config"); String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.set.property.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = properties.getProperty("nacos.set.property.scope"); - Assert.assertEquals("config", ret); + assertEquals("config", ret); } @Test - public void testAddProperties() { + void testAddProperties() { Properties properties = new Properties(); properties.setProperty("nacos.add.properties", "true"); @@ -143,11 +148,11 @@ public void testAddProperties() { final String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.add.properties"); - Assert.assertEquals("true", ret); + assertEquals("true", ret); } @Test - public void testAddPropertiesWithScope() { + void testAddPropertiesWithScope() { Properties properties = new Properties(); properties.setProperty("nacos.add.properties.scope", "config"); @@ -156,15 +161,15 @@ public void testAddPropertiesWithScope() { nacosClientProperties.addProperties(properties); String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.add.properties.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = nacosClientProperties.getProperty("nacos.add.properties.scope"); - Assert.assertEquals("config", ret); + assertEquals("config", ret); } @Test - public void testTestDerive() { + void testTestDerive() { Properties properties = new Properties(); properties.setProperty("nacos.derive.properties.scope", "derive"); @@ -172,23 +177,23 @@ public void testTestDerive() { final String value = nacosClientProperties.getProperty("nacos.derive.properties.scope"); - Assert.assertEquals("derive", value); + assertEquals("derive", value); } @Test - public void testContainsKey() { + void testContainsKey() { NacosClientProperties.PROTOTYPE.setProperty("nacos.contains.key", "true"); boolean ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.key"); - Assert.assertTrue(ret); + assertTrue(ret); ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.key.in.sys"); - Assert.assertFalse(ret); + assertFalse(ret); } @Test - public void testContainsKeyMultiLayers() { + void testContainsKeyMultiLayers() { NacosClientProperties.PROTOTYPE.setProperty("top.layer", "top"); @@ -202,49 +207,49 @@ public void testContainsKeyMultiLayers() { layerCEnv.setProperty("c.layer", "c"); boolean exist = layerCEnv.containsKey("c.layer"); - Assert.assertTrue(exist); + assertTrue(exist); exist = layerCEnv.containsKey("b.layer"); - Assert.assertTrue(exist); + assertTrue(exist); exist = layerCEnv.containsKey("a.layer"); - Assert.assertTrue(exist); + assertTrue(exist); exist = layerCEnv.containsKey("top.layer"); - Assert.assertTrue(exist); + assertTrue(exist); } @Test - public void testContainsKeyWithScope() { + void testContainsKeyWithScope() { NacosClientProperties.PROTOTYPE.setProperty("nacos.contains.global.scope", "global"); final NacosClientProperties namingProperties = NacosClientProperties.PROTOTYPE.derive(); namingProperties.setProperty("nacos.contains.naming.scope", "naming"); boolean ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.global.scope"); - Assert.assertTrue(ret); + assertTrue(ret); ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.naming.scope"); - Assert.assertFalse(ret); + assertFalse(ret); ret = namingProperties.containsKey("nacos.contains.naming.scope"); - Assert.assertTrue(ret); + assertTrue(ret); ret = namingProperties.containsKey("nacos.contains.global.scope"); - Assert.assertTrue(ret); + assertTrue(ret); } @Test - public void testAsProperties() { + void testAsProperties() { NacosClientProperties.PROTOTYPE.setProperty("nacos.as.properties", "true"); final Properties properties = NacosClientProperties.PROTOTYPE.asProperties(); - Assert.assertNotNull(properties); - Assert.assertEquals("true", properties.getProperty("nacos.as.properties")); + assertNotNull(properties); + assertEquals("true", properties.getProperty("nacos.as.properties")); } @Test - public void testAsPropertiesWithScope() { + void testAsPropertiesWithScope() { NacosClientProperties.PROTOTYPE.setProperty("nacos.as.properties.global.scope", "global"); NacosClientProperties.PROTOTYPE.setProperty("nacos.server.addr.scope", "global"); @@ -253,17 +258,17 @@ public void testAsPropertiesWithScope() { configProperties.setProperty("nacos.server.addr.scope", "config"); final Properties properties = configProperties.asProperties(); - Assert.assertNotNull(properties); + assertNotNull(properties); String ret = properties.getProperty("nacos.as.properties.global.scope"); - Assert.assertEquals("global", ret); + assertEquals("global", ret); ret = properties.getProperty("nacos.server.addr.scope"); - Assert.assertEquals("config", ret); + assertEquals("config", ret); } @Test - public void testGetPropertyWithScope() { + void testGetPropertyWithScope() { NacosClientProperties.PROTOTYPE.setProperty("nacos.global.scope", "global"); @@ -274,41 +279,40 @@ public void testGetPropertyWithScope() { namingProperties.setProperty("nacos.naming.scope", "naming"); String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.global.scope"); - Assert.assertEquals("global", ret); + assertEquals("global", ret); ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.config.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.naming.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = configProperties.getProperty("nacos.config.scope"); - Assert.assertEquals("config", ret); + assertEquals("config", ret); ret = configProperties.getProperty("nacos.global.scope"); - Assert.assertEquals("global", ret); + assertEquals("global", ret); ret = configProperties.getProperty("nacos.naming.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = namingProperties.getProperty("nacos.naming.scope"); - Assert.assertEquals("naming", ret); + assertEquals("naming", ret); ret = namingProperties.getProperty("nacos.global.scope"); - Assert.assertEquals("global", ret); + assertEquals("global", ret); ret = namingProperties.getProperty("nacos.config.scope"); - Assert.assertNull(ret); + assertNull(ret); } @Test - public void testGetPropertyFrom() { + void testGetPropertyFrom() { System.setProperty("nacos.home.default.test", "/home/jvm_args"); NacosClientProperties.PROTOTYPE.setProperty("nacos.home.default.test", "/home/properties_args"); - Assert.assertEquals(NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.JVM, "nacos.home.default.test"), - "/home/jvm_args"); - Assert.assertEquals( - NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.PROPERTIES, "nacos.home.default.test"), - "/home/properties_args"); - Assert.assertEquals(NacosClientProperties.PROTOTYPE.getPropertyFrom(null, "nacos.home.default.test"), + assertEquals("/home/jvm_args", + NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.JVM, "nacos.home.default.test")); + assertEquals("/home/properties_args", + NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.PROPERTIES, "nacos.home.default.test")); + assertEquals(NacosClientProperties.PROTOTYPE.getPropertyFrom(null, "nacos.home.default.test"), NacosClientProperties.PROTOTYPE.getProperty("nacos.home.default.test")); } diff --git a/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java b/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java index 5518884b21a..d4f52428fbb 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java @@ -17,59 +17,59 @@ package com.alibaba.nacos.client.env; import com.alibaba.nacos.client.constant.Constants; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Additional test cases for SearchableProperties. * *

Common cases see {@link NacosClientPropertiesTest}.

*/ -public class SearchablePropertiesTest { +class SearchablePropertiesTest { Method initMethod; - @BeforeClass - public static void init() { + @BeforeAll + static void init() { System.setProperty(Constants.SysEnv.NACOS_ENV_FIRST, "jvm"); } - @Before - public void setUp() throws Exception { + @AfterAll + static void teardown() { + System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); + } + + @BeforeEach + void setUp() throws Exception { initMethod = SearchableProperties.class.getDeclaredMethod("init"); initMethod.setAccessible(true); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { init(); initMethod.invoke(null); } - @AfterClass - public static void teardown() { - System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); - } - @Test - public void testInitWithInvalidOrder() throws IllegalAccessException, InvocationTargetException { + void testInitWithInvalidOrder() throws IllegalAccessException, InvocationTargetException { System.setProperty(Constants.SysEnv.NACOS_ENV_FIRST, "invalid"); List order = (List) initMethod.invoke(null); assertOrder(order, SourceType.PROPERTIES, SourceType.JVM, SourceType.ENV); } @Test - public void testInitWithoutSpecifiedOrder() throws IllegalAccessException, InvocationTargetException { + void testInitWithoutSpecifiedOrder() throws IllegalAccessException, InvocationTargetException { System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); List order = (List) initMethod.invoke(null); assertOrder(order, SourceType.PROPERTIES, SourceType.JVM, SourceType.ENV); @@ -83,7 +83,7 @@ private void assertOrder(List order, SourceType... sourceTypes) { } @Test - public void testGetPropertyFromEnv() { + void testGetPropertyFromEnv() { System.setProperty("testFromSource", "jvm"); NacosClientProperties properties = SearchableProperties.INSTANCE.derive(); properties.setProperty("testFromSource", "properties"); @@ -91,7 +91,7 @@ public void testGetPropertyFromEnv() { } @Test - public void testGetPropertyFromUnknown() { + void testGetPropertyFromUnknown() { System.setProperty("testFromSource", "jvm"); NacosClientProperties properties = SearchableProperties.INSTANCE.derive(); properties.setProperty("testFromSource", "properties"); diff --git a/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java b/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java index 89361fc68a2..89d1ad6604b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java @@ -16,28 +16,28 @@ package com.alibaba.nacos.client.env; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Additional test cases for SystemEnvPropertySource. * *

Common cases see {@link NacosClientPropertiesTest}.

*/ -public class SystemEnvPropertySourceTest { +class SystemEnvPropertySourceTest { SystemEnvPropertySource systemEnvPropertySource; private Map mockEnvMap; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { systemEnvPropertySource = new SystemEnvPropertySource(); mockEnvMap = new HashMap<>(); Field envField = SystemEnvPropertySource.class.getDeclaredField("env"); @@ -50,42 +50,42 @@ public void setUp() throws Exception { } @Test - public void testGetEnvForLowerCaseKey() { + void testGetEnvForLowerCaseKey() { assertEquals("value1", systemEnvPropertySource.getProperty("testcase1")); } @Test - public void testGetEnvForLowerCaseKeyWithDot() { + void testGetEnvForLowerCaseKeyWithDot() { assertEquals("value2", systemEnvPropertySource.getProperty("test.case.2")); } @Test - public void testGetEnvForLowerCaseKeyWithHyphen() { + void testGetEnvForLowerCaseKeyWithHyphen() { assertEquals("value2", systemEnvPropertySource.getProperty("test-case-2")); } @Test - public void testGetEnvForLowerCaseKeyWithHyphenAndDot() { + void testGetEnvForLowerCaseKeyWithHyphenAndDot() { assertEquals("value2", systemEnvPropertySource.getProperty("test.case-2")); } @Test - public void testGetEnvForUpperCaseKey() { + void testGetEnvForUpperCaseKey() { assertEquals("value3", systemEnvPropertySource.getProperty("TESTCASE3")); } @Test - public void testGetEnvForUpperCaseKeyWithDot() { + void testGetEnvForUpperCaseKeyWithDot() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST.CASE.4")); } @Test - public void testGetEnvForUpperCaseKeyWithHyphen() { + void testGetEnvForUpperCaseKeyWithHyphen() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST-CASE-4")); } @Test - public void testGetEnvForUpperCaseKeyWithHyphenAndDot() { + void testGetEnvForUpperCaseKeyWithHyphenAndDot() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST_CASE.4")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java b/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java index a248a42eed6..8d200e29a29 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java @@ -16,42 +16,45 @@ package com.alibaba.nacos.client.env.convert; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.MissingFormatArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class CompositeConverterTest { +class CompositeConverterTest { CompositeConverter compositeConverter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { compositeConverter = new CompositeConverter(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } - @Test(expected = MissingFormatArgumentException.class) - public void testConvertNotSupportType() { - compositeConverter.convert("test", CompositeConverter.class); + @Test + void testConvertNotSupportType() { + assertThrows(MissingFormatArgumentException.class, () -> { + compositeConverter.convert("test", CompositeConverter.class); + }); } @Test - public void testConvertBooleanForEmptyProperty() { + void testConvertBooleanForEmptyProperty() { assertNull(compositeConverter.convert(null, Boolean.class)); } @Test - public void testConvertBooleanTrue() { + void testConvertBooleanTrue() { assertTrue(compositeConverter.convert("true", Boolean.class)); assertTrue(compositeConverter.convert("on", Boolean.class)); assertTrue(compositeConverter.convert("yes", Boolean.class)); @@ -59,49 +62,57 @@ public void testConvertBooleanTrue() { } @Test - public void testConvertBooleanFalse() { + void testConvertBooleanFalse() { assertFalse(compositeConverter.convert("false", Boolean.class)); assertFalse(compositeConverter.convert("off", Boolean.class)); assertFalse(compositeConverter.convert("no", Boolean.class)); assertFalse(compositeConverter.convert("0", Boolean.class)); } - @Test(expected = IllegalArgumentException.class) - public void testConvertBooleanIllegal() { - compositeConverter.convert("aaa", Boolean.class); + @Test + void testConvertBooleanIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + compositeConverter.convert("aaa", Boolean.class); + }); } @Test - public void testConvertIntegerForEmptyProperty() { + void testConvertIntegerForEmptyProperty() { assertNull(compositeConverter.convert(null, Integer.class)); } @Test - public void testConvertInteger() { + void testConvertInteger() { assertEquals(100, (int) compositeConverter.convert("100", Integer.class)); - assertEquals(Integer.MAX_VALUE, (int) compositeConverter.convert(String.valueOf(Integer.MAX_VALUE), Integer.class)); - assertEquals(Integer.MIN_VALUE, (int) compositeConverter.convert(String.valueOf(Integer.MIN_VALUE), Integer.class)); + assertEquals(Integer.MAX_VALUE, + (int) compositeConverter.convert(String.valueOf(Integer.MAX_VALUE), Integer.class)); + assertEquals(Integer.MIN_VALUE, + (int) compositeConverter.convert(String.valueOf(Integer.MIN_VALUE), Integer.class)); } - @Test(expected = IllegalArgumentException.class) - public void testConvertIntegerIllegal() { - compositeConverter.convert("aaa", Integer.class); + @Test + void testConvertIntegerIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + compositeConverter.convert("aaa", Integer.class); + }); } @Test - public void testConvertLongForEmptyProperty() { + void testConvertLongForEmptyProperty() { assertNull(compositeConverter.convert(null, Long.class)); } @Test - public void testConvertLong() { + void testConvertLong() { assertEquals(100L, (long) compositeConverter.convert("100", Long.class)); assertEquals(Long.MAX_VALUE, (long) compositeConverter.convert(String.valueOf(Long.MAX_VALUE), Long.class)); assertEquals(Long.MIN_VALUE, (long) compositeConverter.convert(String.valueOf(Long.MIN_VALUE), Long.class)); } - @Test(expected = IllegalArgumentException.class) - public void testConvertLongIllegal() { - compositeConverter.convert("aaa", Long.class); + @Test + void testConvertLongIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + compositeConverter.convert("aaa", Long.class); + }); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java b/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java index b2d94d42404..bdd3f4d9701 100644 --- a/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java @@ -20,21 +20,21 @@ import com.alibaba.nacos.common.logging.NacosLoggingAdapter; import com.alibaba.nacos.common.logging.NacosLoggingProperties; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.doThrow; -@RunWith(MockitoJUnitRunner.class) -public class NacosLoggingTest { +@ExtendWith(MockitoExtension.class) +class NacosLoggingTest { @Mock NacosLoggingAdapter loggingAdapter; @@ -43,8 +43,8 @@ public class NacosLoggingTest { NacosLogging instance; - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { loggingProperties = new NacosLoggingProperties("", new Properties()); instance = NacosLogging.getInstance(); Field loggingPropertiesField = NacosLogging.class.getDeclaredField("loggingProperties"); @@ -53,13 +53,13 @@ public void setUp() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testGetInstance() { + void testGetInstance() { NacosLogging instance = NacosLogging.getInstance(); - Assert.assertNotNull(instance); + assertNotNull(instance); } @Test - public void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessException { + void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessException { instance = NacosLogging.getInstance(); Field nacosLogging = NacosLogging.class.getDeclaredField("loggingAdapter"); nacosLogging.setAccessible(true); @@ -69,7 +69,7 @@ public void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessEx } @Test - public void testLoadConfigurationWithException() throws NoSuchFieldException, IllegalAccessException { + void testLoadConfigurationWithException() throws NoSuchFieldException, IllegalAccessException { instance = NacosLogging.getInstance(); Field nacosLoggingField = NacosLogging.class.getDeclaredField("loggingAdapter"); nacosLoggingField.setAccessible(true); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java index e5a84b6e022..50580d0e526 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java @@ -29,10 +29,9 @@ import com.alibaba.nacos.client.naming.core.ServerListManager; import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy; import com.alibaba.nacos.client.security.SecurityProxy; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatcher; import java.lang.reflect.Field; @@ -41,12 +40,13 @@ import java.util.Properties; import java.util.concurrent.ScheduledExecutorService; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class NacosNamingMaintainServiceTest { +class NacosNamingMaintainServiceTest { private NacosNamingMaintainService nacosNamingMaintainService; @@ -58,18 +58,18 @@ public class NacosNamingMaintainServiceTest { private ScheduledExecutorService executorService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { Properties prop = new Properties(); prop.setProperty(PropertyKeyConst.NAMESPACE, "public"); prop.setProperty("serverAddr", "localhost"); - + nacosNamingMaintainService = new NacosNamingMaintainService(prop); serverProxy = mock(NamingHttpClientProxy.class); serverListManager = mock(ServerListManager.class); securityProxy = mock(SecurityProxy.class); executorService = mock(ScheduledExecutorService.class); - + Field serverProxyField = NacosNamingMaintainService.class.getDeclaredField("serverProxy"); serverProxyField.setAccessible(true); serverProxyField.set(nacosNamingMaintainService, serverProxy); @@ -84,18 +84,18 @@ public void setUp() throws Exception { executorServiceField.set(nacosNamingMaintainService, executorService); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testConstructor() throws NacosException { + void testConstructor() throws NacosException { NacosNamingMaintainService client = new NacosNamingMaintainService("localhost"); - Assert.assertNotNull(client); + assertNotNull(client); } @Test - public void testUpdateInstance1() throws NacosException { + void testUpdateInstance1() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -107,7 +107,7 @@ public void testUpdateInstance1() throws NacosException { } @Test - public void testUpdateInstance2() throws NacosException { + void testUpdateInstance2() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -118,7 +118,7 @@ public void testUpdateInstance2() throws NacosException { } @Test - public void testQueryService1() throws NacosException { + void testQueryService1() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -129,7 +129,7 @@ public void testQueryService1() throws NacosException { } @Test - public void testQueryService2() throws NacosException { + void testQueryService2() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -140,7 +140,7 @@ public void testQueryService2() throws NacosException { } @Test - public void testCreateService1() throws NacosException { + void testCreateService1() throws NacosException { //given String serviceName = "service1"; //when @@ -157,7 +157,7 @@ public boolean matches(Service service) { } @Test - public void testCreateService2() throws NacosException { + void testCreateService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -175,7 +175,7 @@ public boolean matches(Service service) { } @Test - public void testCreateService3() throws NacosException { + void testCreateService3() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -194,7 +194,7 @@ public boolean matches(Service service) { } @Test - public void testCreateService5() throws NacosException { + void testCreateService5() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -214,7 +214,7 @@ public boolean matches(Service service) { } @Test - public void testCreateService4() throws NacosException { + void testCreateService4() throws NacosException { //given Service service = new Service(); AbstractSelector selector = new NoneSelector(); @@ -225,7 +225,7 @@ public void testCreateService4() throws NacosException { } @Test - public void testDeleteService1() throws NacosException { + void testDeleteService1() throws NacosException { //given String serviceName = "service1"; //when @@ -235,7 +235,7 @@ public void testDeleteService1() throws NacosException { } @Test - public void testDeleteService2() throws NacosException { + void testDeleteService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -246,7 +246,7 @@ public void testDeleteService2() throws NacosException { } @Test - public void testUpdateService1() throws NacosException { + void testUpdateService1() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -265,7 +265,7 @@ public boolean matches(Service service) { } @Test - public void testUpdateService2() throws NacosException { + void testUpdateService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -287,7 +287,7 @@ public boolean matches(Service service) { } @Test - public void testUpdateService3() throws NacosException { + void testUpdateService3() throws NacosException { //given Service service = new Service(); AbstractSelector selector = new NoneSelector(); @@ -298,7 +298,7 @@ public void testUpdateService3() throws NacosException { } @Test - public void testShutDown() throws NacosException { + void testShutDown() throws NacosException { //when nacosNamingMaintainService.shutDown(); //then diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java index 8a6e5a95e32..02fa6ce13f3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java @@ -32,15 +32,12 @@ import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy; import com.alibaba.nacos.client.naming.utils.CollectionUtils; import com.alibaba.nacos.client.naming.utils.UtilAndComs; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.ArrayList; @@ -49,7 +46,10 @@ import java.util.List; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; @@ -60,11 +60,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosNamingServiceTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); +@ExtendWith(MockitoExtension.class) +class NacosNamingServiceTest { @Mock private NamingClientProxy proxy; @@ -77,8 +74,8 @@ public class NacosNamingServiceTest { private NacosNamingService client; - @Before - public void before() throws NoSuchFieldException, NacosException, IllegalAccessException { + @BeforeEach + void before() throws NoSuchFieldException, NacosException, IllegalAccessException { Properties prop = new Properties(); prop.setProperty("serverAddr", "localhost"); prop.put(PropertyKeyConst.NAMESPACE, "test"); @@ -86,8 +83,8 @@ public void before() throws NoSuchFieldException, NacosException, IllegalAccessE injectMocks(client); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { client.shutDown(); } @@ -118,7 +115,7 @@ private void injectMocks(NacosNamingService client) throws NoSuchFieldException, } @Test - public void testRegisterInstance1() throws NacosException { + void testRegisterInstance1() throws NacosException { //given String serviceName = "service1"; String ip = "1.1.1.1"; @@ -133,7 +130,7 @@ public void testRegisterInstance1() throws NacosException { } @Test - public void testBatchRegisterInstance() throws NacosException { + void testBatchRegisterInstance() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -152,7 +149,7 @@ public void testBatchRegisterInstance() throws NacosException { } @Test - public void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException { + void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -171,7 +168,7 @@ public void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException } @Test - public void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosException { + void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -186,13 +183,13 @@ public void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosExce try { client.batchRegisterInstance(serviceName, Constants.DEFAULT_GROUP, instanceList); } catch (Exception e) { - Assert.assertTrue(e instanceof NacosException); - Assert.assertTrue(e.getMessage().contains("wrong group name prefix of instance service name")); + assertTrue(e instanceof NacosException); + assertTrue(e.getMessage().contains("wrong group name prefix of instance service name")); } } @Test - public void testBatchDeRegisterInstance() throws NacosException { + void testBatchDeRegisterInstance() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -207,13 +204,13 @@ public void testBatchDeRegisterInstance() throws NacosException { try { client.batchDeregisterInstance(serviceName, Constants.DEFAULT_GROUP, instanceList); } catch (Exception e) { - Assert.assertTrue(e instanceof NacosException); - Assert.assertTrue(e.getMessage().contains("not found")); + assertTrue(e instanceof NacosException); + assertTrue(e.getMessage().contains("not found")); } } @Test - public void testRegisterInstance2() throws NacosException { + void testRegisterInstance2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -229,7 +226,7 @@ public void testRegisterInstance2() throws NacosException { } @Test - public void testRegisterInstance3() throws NacosException { + void testRegisterInstance3() throws NacosException { //given String serviceName = "service1"; String clusterName = "cluster1"; @@ -245,7 +242,7 @@ public void testRegisterInstance3() throws NacosException { } @Test - public void testRegisterInstance4() throws NacosException { + void testRegisterInstance4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -262,7 +259,7 @@ public void testRegisterInstance4() throws NacosException { } @Test - public void testRegisterInstance5() throws NacosException { + void testRegisterInstance5() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -273,7 +270,7 @@ public void testRegisterInstance5() throws NacosException { } @Test - public void testRegisterInstance6() throws NacosException { + void testRegisterInstance6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -285,22 +282,23 @@ public void testRegisterInstance6() throws NacosException { } @Test - public void testRegisterInstance7() throws NacosException { - expectedException.expect(NacosException.class); - expectedException.expectMessage( - "Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)"); - - //given - String serviceName = "service1"; - String groupName = "group1"; - Instance instance = new Instance(); - instance.setClusterName("cluster1,cluster2"); - //when - client.registerInstance(serviceName, groupName, instance); + void testRegisterInstance7() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + //given + String serviceName = "service1"; + String groupName = "group1"; + Instance instance = new Instance(); + instance.setClusterName("cluster1,cluster2"); + //when + client.registerInstance(serviceName, groupName, instance); + }); + assertTrue(exception.getMessage().contains( + "Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)")); } @Test - public void testDeregisterInstance1() throws NacosException { + void testDeregisterInstance1() throws NacosException { //given String serviceName = "service1"; String ip = "1.1.1.1"; @@ -315,7 +313,7 @@ public void testDeregisterInstance1() throws NacosException { } @Test - public void testDeregisterInstance2() throws NacosException { + void testDeregisterInstance2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -331,7 +329,7 @@ public void testDeregisterInstance2() throws NacosException { } @Test - public void testDeregisterInstance3() throws NacosException { + void testDeregisterInstance3() throws NacosException { //given String serviceName = "service1"; String clusterName = "cluster1"; @@ -347,7 +345,7 @@ public void testDeregisterInstance3() throws NacosException { } @Test - public void testDeregisterInstance4() throws NacosException { + void testDeregisterInstance4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -364,7 +362,7 @@ public void testDeregisterInstance4() throws NacosException { } @Test - public void testDeregisterInstance5() throws NacosException { + void testDeregisterInstance5() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -375,7 +373,7 @@ public void testDeregisterInstance5() throws NacosException { } @Test - public void testDeregisterInstance6() throws NacosException { + void testDeregisterInstance6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -387,7 +385,7 @@ public void testDeregisterInstance6() throws NacosException { } @Test - public void testGetAllInstances1() throws NacosException { + void testGetAllInstances1() throws NacosException { //given String serviceName = "service1"; //when @@ -397,7 +395,7 @@ public void testGetAllInstances1() throws NacosException { } @Test - public void testGetAllInstances2() throws NacosException { + void testGetAllInstances2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -408,7 +406,7 @@ public void testGetAllInstances2() throws NacosException { } @Test - public void testGetAllInstances3() throws NacosException { + void testGetAllInstances3() throws NacosException { //given String serviceName = "service1"; //when @@ -418,7 +416,7 @@ public void testGetAllInstances3() throws NacosException { } @Test - public void testGetAllInstances4() throws NacosException { + void testGetAllInstances4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -430,7 +428,7 @@ public void testGetAllInstances4() throws NacosException { } @Test - public void testGetAllInstances5() throws NacosException { + void testGetAllInstances5() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -441,7 +439,7 @@ public void testGetAllInstances5() throws NacosException { } @Test - public void testGetAllInstances6() throws NacosException { + void testGetAllInstances6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -454,19 +452,19 @@ public void testGetAllInstances6() throws NacosException { } @Test - public void testGetAllInstances7() throws NacosException { + void testGetAllInstances7() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); //when client.getAllInstances(serviceName, clusterList, false); //then - verify(proxy, times(1)) - .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); + verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", + false); } @Test - public void testGetAllInstances8() throws NacosException { + void testGetAllInstances8() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -478,7 +476,7 @@ public void testGetAllInstances8() throws NacosException { } @Test - public void testGetAllInstanceFromFailover() throws NacosException { + void testGetAllInstanceFromFailover() throws NacosException { when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true); ServiceInfo serviceInfo = new ServiceInfo("group1@@service1"); serviceInfo.setHosts(Collections.singletonList(new Instance())); @@ -490,7 +488,7 @@ public void testGetAllInstanceFromFailover() throws NacosException { } @Test - public void testGetAllInstanceFromFailoverEmpty() throws NacosException { + void testGetAllInstanceFromFailoverEmpty() throws NacosException { when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true); ServiceInfo serviceInfo = new ServiceInfo("group1@@service1"); when(serviceInfoHolder.getFailoverServiceInfo(anyString(), anyString(), anyString())).thenReturn(serviceInfo); @@ -500,7 +498,7 @@ public void testGetAllInstanceFromFailoverEmpty() throws NacosException { } @Test - public void testSelectInstances1() throws NacosException { + void testSelectInstances1() throws NacosException { //given String serviceName = "service1"; //when @@ -510,7 +508,7 @@ public void testSelectInstances1() throws NacosException { } @Test - public void testSelectInstances2() throws NacosException { + void testSelectInstances2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -521,7 +519,7 @@ public void testSelectInstances2() throws NacosException { } @Test - public void testSelectInstances3() throws NacosException { + void testSelectInstances3() throws NacosException { //given String serviceName = "service1"; //when @@ -531,7 +529,7 @@ public void testSelectInstances3() throws NacosException { } @Test - public void testSelectInstances4() throws NacosException { + void testSelectInstances4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -543,7 +541,7 @@ public void testSelectInstances4() throws NacosException { } @Test - public void testSelectInstances5() throws NacosException { + void testSelectInstances5() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -554,7 +552,7 @@ public void testSelectInstances5() throws NacosException { } @Test - public void testSelectInstances6() throws NacosException { + void testSelectInstances6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -567,19 +565,19 @@ public void testSelectInstances6() throws NacosException { } @Test - public void testSelectInstances7() throws NacosException { + void testSelectInstances7() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); //when client.selectInstances(serviceName, clusterList, true, false); //then - verify(proxy, times(1)) - .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); + verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", + false); } @Test - public void testSelectInstances8() throws NacosException { + void testSelectInstances8() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -591,7 +589,7 @@ public void testSelectInstances8() throws NacosException { } @Test - public void testSelectInstancesWithHealthyFlag() throws NacosException { + void testSelectInstancesWithHealthyFlag() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setHealthy(true); @@ -623,11 +621,11 @@ public void testSelectInstancesWithHealthyFlag() throws NacosException { List instances = client.selectInstances(serviceName, groupName, clusterList, true, false); //then assertEquals(1, instances.size()); - Assert.assertSame(healthyInstance, instances.get(0)); + assertSame(healthyInstance, instances.get(0)); } @Test - public void testSelectOneHealthyInstance1() throws NacosException { + void testSelectOneHealthyInstance1() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -646,7 +644,7 @@ public void testSelectOneHealthyInstance1() throws NacosException { } @Test - public void testSelectOneHealthyInstance2() throws NacosException { + void testSelectOneHealthyInstance2() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -666,7 +664,7 @@ public void testSelectOneHealthyInstance2() throws NacosException { } @Test - public void testSelectOneHealthyInstance3() throws NacosException { + void testSelectOneHealthyInstance3() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -675,8 +673,8 @@ public void testSelectOneHealthyInstance3() throws NacosException { hosts.add(healthyInstance); ServiceInfo infoWithHealthyInstance = new ServiceInfo(); infoWithHealthyInstance.setHosts(hosts); - when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())) - .thenReturn(infoWithHealthyInstance); + when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn( + infoWithHealthyInstance); String serviceName = "service1"; //when @@ -686,7 +684,7 @@ public void testSelectOneHealthyInstance3() throws NacosException { } @Test - public void testSelectOneHealthyInstance4() throws NacosException { + void testSelectOneHealthyInstance4() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -695,8 +693,8 @@ public void testSelectOneHealthyInstance4() throws NacosException { hosts.add(healthyInstance); ServiceInfo infoWithHealthyInstance = new ServiceInfo(); infoWithHealthyInstance.setHosts(hosts); - when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())) - .thenReturn(infoWithHealthyInstance); + when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn( + infoWithHealthyInstance); String serviceName = "service1"; String groupName = "group1"; @@ -708,7 +706,7 @@ public void testSelectOneHealthyInstance4() throws NacosException { } @Test - public void testSelectOneHealthyInstance5() throws NacosException { + void testSelectOneHealthyInstance5() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -728,7 +726,7 @@ public void testSelectOneHealthyInstance5() throws NacosException { } @Test - public void testSelectOneHealthyInstance6() throws NacosException { + void testSelectOneHealthyInstance6() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -750,7 +748,7 @@ public void testSelectOneHealthyInstance6() throws NacosException { } @Test - public void testSelectOneHealthyInstance7() throws NacosException { + void testSelectOneHealthyInstance7() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -759,20 +757,20 @@ public void testSelectOneHealthyInstance7() throws NacosException { hosts.add(healthyInstance); ServiceInfo infoWithHealthyInstance = new ServiceInfo(); infoWithHealthyInstance.setHosts(hosts); - when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())) - .thenReturn(infoWithHealthyInstance); + when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn( + infoWithHealthyInstance); String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); //when client.selectOneHealthyInstance(serviceName, clusterList, false); //then - verify(proxy, times(1)) - .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); + verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", + false); } @Test - public void testSelectOneHealthyInstance8() throws NacosException { + void testSelectOneHealthyInstance8() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -781,8 +779,8 @@ public void testSelectOneHealthyInstance8() throws NacosException { hosts.add(healthyInstance); ServiceInfo infoWithHealthyInstance = new ServiceInfo(); infoWithHealthyInstance.setHosts(hosts); - when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())) - .thenReturn(infoWithHealthyInstance); + when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn( + infoWithHealthyInstance); String serviceName = "service1"; String groupName = "group1"; @@ -794,7 +792,7 @@ public void testSelectOneHealthyInstance8() throws NacosException { } @Test - public void testSubscribe1() throws NacosException { + void testSubscribe1() throws NacosException { //given String serviceName = "service1"; EventListener listener = event -> { @@ -808,7 +806,7 @@ public void testSubscribe1() throws NacosException { } @Test - public void testSubscribe2() throws NacosException { + void testSubscribe2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -823,7 +821,7 @@ public void testSubscribe2() throws NacosException { } @Test - public void testSubscribe3() throws NacosException { + void testSubscribe3() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -833,13 +831,13 @@ public void testSubscribe3() throws NacosException { //when client.subscribe(serviceName, clusterList, listener); //then - verify(changeNotifier, times(1)) - .registerListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener); + verify(changeNotifier, times(1)).registerListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", + listener); verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } @Test - public void testSubscribe4() throws NacosException { + void testSubscribe4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -855,7 +853,7 @@ public void testSubscribe4() throws NacosException { } @Test - public void testSubscribeWithNullListener() throws NacosException { + void testSubscribeWithNullListener() throws NacosException { String serviceName = "service1"; String groupName = "group1"; //when @@ -867,7 +865,7 @@ public void testSubscribeWithNullListener() throws NacosException { } @Test - public void testUnSubscribe1() throws NacosException { + void testUnSubscribe1() throws NacosException { //given String serviceName = "service1"; EventListener listener = event -> { @@ -880,7 +878,7 @@ public void testUnSubscribe1() throws NacosException { } @Test - public void testUnSubscribe2() throws NacosException { + void testUnSubscribe2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -894,7 +892,7 @@ public void testUnSubscribe2() throws NacosException { } @Test - public void testUnSubscribe3() throws NacosException { + void testUnSubscribe3() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -903,13 +901,13 @@ public void testUnSubscribe3() throws NacosException { }; client.unsubscribe(serviceName, clusterList, listener); //then - verify(changeNotifier, times(1)) - .deregisterListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener); + verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", + listener); verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } @Test - public void testUnSubscribe4() throws NacosException { + void testUnSubscribe4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -924,7 +922,7 @@ public void testUnSubscribe4() throws NacosException { } @Test - public void testGetServicesOfServer1() throws NacosException { + void testGetServicesOfServer1() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -935,7 +933,7 @@ public void testGetServicesOfServer1() throws NacosException { } @Test - public void testGetServicesOfServer2() throws NacosException { + void testGetServicesOfServer2() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -947,7 +945,7 @@ public void testGetServicesOfServer2() throws NacosException { } @Test - public void testGetServicesOfServer3() throws NacosException { + void testGetServicesOfServer3() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -964,7 +962,7 @@ public String getType() { } @Test - public void testGetServicesOfServer4() throws NacosException { + void testGetServicesOfServer4() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -983,7 +981,7 @@ public String getType() { } @Test - public void testGetSubscribeServices() { + void testGetSubscribeServices() { //when client.getSubscribeServices(); //then @@ -991,7 +989,7 @@ public void testGetSubscribeServices() { } @Test - public void testGetServerStatus() { + void testGetServerStatus() { //given when(proxy.serverHealthy()).thenReturn(true); //when @@ -1001,7 +999,7 @@ public void testGetServerStatus() { } @Test - public void testGetServerStatusFail() { + void testGetServerStatusFail() { //given when(proxy.serverHealthy()).thenReturn(false); //when @@ -1011,7 +1009,7 @@ public void testGetServerStatusFail() { } @Test - public void testShutDown() throws NacosException { + void testShutDown() throws NacosException { //when client.shutDown(); //then @@ -1019,7 +1017,7 @@ public void testShutDown() throws NacosException { } @Test - public void testConstructorWithServerList() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testConstructorWithServerList() throws NacosException, NoSuchFieldException, IllegalAccessException { NacosNamingService namingService = new NacosNamingService("localhost"); try { Field namespaceField = NacosNamingService.class.getDeclaredField("namespace"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java index 26cad59f79a..8c480ada321 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java @@ -20,13 +20,12 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder; import com.alibaba.nacos.common.utils.ReflectUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -37,14 +36,15 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class FailoverReactorTest { +@ExtendWith(MockitoExtension.class) +class FailoverReactorTest { @Mock ServiceInfoHolder holder; @@ -54,33 +54,33 @@ public class FailoverReactorTest { FailoverReactor failoverReactor; - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { failoverReactor = new FailoverReactor(holder, UUID.randomUUID().toString()); Field failoverDataSourceField = FailoverReactor.class.getDeclaredField("failoverDataSource"); failoverDataSourceField.setAccessible(true); failoverDataSourceField.set(failoverReactor, failoverDataSource); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { failoverReactor.shutdown(); } @Test - public void testIsFailoverSwitch() throws NacosException { - Assert.assertFalse(failoverReactor.isFailoverSwitch()); + void testIsFailoverSwitch() throws NacosException { + assertFalse(failoverReactor.isFailoverSwitch()); } @Test - public void testGetService() throws NacosException { + void testGetService() throws NacosException { ServiceInfo info = failoverReactor.getService("aa@@bb"); assertEquals(new ServiceInfo("aa@@bb").toString(), info.toString()); } @Test - public void testRefreshFromDisabledToEnabled() throws InterruptedException { + void testRefreshFromDisabledToEnabled() throws InterruptedException { // make sure the first no delay refresh thread finished. TimeUnit.MILLISECONDS.sleep(500); FailoverSwitch mockFailoverSwitch = new FailoverSwitch(true); @@ -97,7 +97,7 @@ public void testRefreshFromDisabledToEnabled() throws InterruptedException { } @Test - public void testRefreshFromDisabledToEnabledWithException() throws InterruptedException { + void testRefreshFromDisabledToEnabledWithException() throws InterruptedException { // make sure the first no delay refresh thread finished. TimeUnit.MILLISECONDS.sleep(500); FailoverSwitch mockFailoverSwitch = new FailoverSwitch(true); @@ -109,8 +109,7 @@ public void testRefreshFromDisabledToEnabledWithException() throws InterruptedEx } @Test - public void testRefreshFromEnabledToDisabled() - throws InterruptedException, NoSuchFieldException, IllegalAccessException { + void testRefreshFromEnabledToDisabled() throws InterruptedException, NoSuchFieldException, IllegalAccessException { // make sure the first no delay refresh thread finished. TimeUnit.MILLISECONDS.sleep(500); FailoverSwitch mockFailoverSwitch = new FailoverSwitch(false); @@ -133,7 +132,7 @@ public void testRefreshFromEnabledToDisabled() } @Test - public void testFailoverServiceCntMetrics() + void testFailoverServiceCntMetrics() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method method = FailoverReactor.class.getDeclaredMethod("failoverServiceCntMetrics"); method.setAccessible(true); @@ -142,7 +141,7 @@ public void testFailoverServiceCntMetrics() } @Test - public void testFailoverServiceCntMetricsClear() + void testFailoverServiceCntMetricsClear() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { Field field = FailoverReactor.class.getDeclaredField("meterMap"); field.setAccessible(true); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java index 7a0b3066610..e839e815b79 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java @@ -19,35 +19,34 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.client.naming.backups.FailoverData; import com.alibaba.nacos.client.naming.backups.FailoverSwitch; -import com.alibaba.nacos.client.naming.cache.DiskCacheTest; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class DiskFailoverDataSourceTest { +class DiskFailoverDataSourceTest { DiskFailoverDataSource dataSource; - @Before - public void setUp() { + @BeforeEach + void setUp() { dataSource = new DiskFailoverDataSource(); } @Test - public void testGetSwitchWithNonExistFailoverSwitchFile() { + void testGetSwitchWithNonExistFailoverSwitchFile() { FailoverSwitch actual = dataSource.getSwitch(); assertFalse(actual.getEnabled()); } @Test - public void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, IllegalAccessException { - String dir = DiskCacheTest.class.getResource("/").getPath() + "/failover_test/disabled"; + void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, IllegalAccessException { + String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/disabled"; injectFailOverDir(dir); assertFalse(dataSource.getSwitch().getEnabled()); Map actual = dataSource.getFailoverData(); @@ -55,8 +54,8 @@ public void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, Ille } @Test - public void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, IllegalAccessException { - String dir = DiskCacheTest.class.getResource("/").getPath() + "/failover_test/enabled"; + void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, IllegalAccessException { + String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/enabled"; injectFailOverDir(dir); assertTrue(dataSource.getSwitch().getEnabled()); Map actual = dataSource.getFailoverData(); @@ -68,7 +67,7 @@ public void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, Illeg } @Test - public void testGetFailoverDataForFailoverDisabled() { + void testGetFailoverDataForFailoverDisabled() { Map actual = dataSource.getFailoverData(); assertTrue(actual.isEmpty()); } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java index e6f638ef767..a99fdda69de 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java @@ -18,10 +18,9 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.UnsupportedEncodingException; @@ -29,11 +28,12 @@ import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -public class DiskCacheTest { +class DiskCacheTest { private static final String CACHE_DIR = DiskCacheTest.class.getResource("/").getPath() + "cache/"; @@ -41,8 +41,8 @@ public class DiskCacheTest { private Instance instance; - @Before - public void setUp() { + @BeforeEach + void setUp() { System.out.println(CACHE_DIR); serviceInfo = new ServiceInfo("G@@testName", "testClusters"); instance = new Instance(); @@ -54,8 +54,8 @@ public void setUp() { serviceInfo.setHosts(Collections.singletonList(instance)); } - @After - public void tearDown() { + @AfterEach + void tearDown() { File file = new File(CACHE_DIR); if (file.exists() && file.list().length > 0) { for (File each : file.listFiles()) { @@ -66,7 +66,7 @@ public void tearDown() { } @Test - public void testCache() { + void testCache() { DiskCache.write(serviceInfo, CACHE_DIR); Map actual = DiskCache.read(CACHE_DIR); assertEquals(1, actual.size()); @@ -75,7 +75,7 @@ public void testCache() { } @Test - public void testWriteCacheWithErrorPath() { + void testWriteCacheWithErrorPath() { File file = new File(CACHE_DIR, serviceInfo.getKeyEncoded()); try { file.mkdirs(); @@ -87,7 +87,7 @@ public void testWriteCacheWithErrorPath() { } @Test - public void testReadCacheForAllSituation() { + void testReadCacheForAllSituation() { String dir = DiskCacheTest.class.getResource("/").getPath() + "/disk_cache_test"; Map actual = DiskCache.read(dir); assertEquals(2, actual.size()); @@ -98,28 +98,32 @@ public void testReadCacheForAllSituation() { } @Test - public void testReadCacheForNullFile() { + void testReadCacheForNullFile() { Map actual = DiskCache.read(null); assertTrue(actual.isEmpty()); } @Test - public void testParseServiceInfoFromNonExistFile() throws UnsupportedEncodingException { + void testParseServiceInfoFromNonExistFile() throws UnsupportedEncodingException { File file = new File("non%40%40exist%40%40file"); Map actual = DiskCache.parseServiceInfoFromCache(file); assertTrue(actual.isEmpty()); } - @Test(expected = IllegalStateException.class) - public void testCreateFileIfAbsentForDir() throws Throwable { - File file = mock(File.class); - DiskCache.createFileIfAbsent(file, true); + @Test + void testCreateFileIfAbsentForDir() throws Throwable { + assertThrows(IllegalStateException.class, () -> { + File file = mock(File.class); + DiskCache.createFileIfAbsent(file, true); + }); } - @Test(expected = IllegalStateException.class) - public void testCreateFileIfAbsentForFile() throws Throwable { - File file = mock(File.class); - DiskCache.createFileIfAbsent(file, false); + @Test + void testCreateFileIfAbsentForFile() throws Throwable { + assertThrows(IllegalStateException.class, () -> { + File file = mock(File.class); + DiskCache.createFileIfAbsent(file, false); + }); } private void assertServiceInfo(ServiceInfo actual, ServiceInfo expected) { @@ -148,8 +152,8 @@ private void assertInstance(Instance actual, Instance expected) { } @Test - public void testGetLineSeparator() { + void testGetLineSeparator() { String lineSeparator = DiskCache.getLineSeparator(); - Assert.assertTrue(lineSeparator.length() > 0); + assertTrue(lineSeparator.length() > 0); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java index 9104cb8b0d8..ebfd6ec3c55 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java @@ -24,46 +24,49 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.client.env.NacosClientProperties; import com.alibaba.nacos.client.naming.backups.FailoverReactor; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ServiceInfoHolderTest { +class ServiceInfoHolderTest { NacosClientProperties nacosClientProperties; ServiceInfoHolder holder; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(); holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException { - Assert.assertEquals(0, holder.getServiceInfoMap().size()); + void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException { + assertEquals(0, holder.getServiceInfoMap().size()); Field fieldNotifierEventScope = ServiceInfoHolder.class.getDeclaredField("notifierEventScope"); fieldNotifierEventScope.setAccessible(true); - Assert.assertEquals("scope-001", fieldNotifierEventScope.get(holder)); + assertEquals("scope-001", fieldNotifierEventScope.get(holder)); } @Test - public void testProcessServiceInfo() { + void testProcessServiceInfo() { ServiceInfo info = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); Instance instance2 = createInstance("1.1.1.2", 2); @@ -73,7 +76,7 @@ public void testProcessServiceInfo() { info.setHosts(hosts); ServiceInfo actual1 = holder.processServiceInfo(info); - Assert.assertEquals(info, actual1); + assertEquals(info, actual1); Instance newInstance1 = createInstance("1.1.1.1", 1); newInstance1.setWeight(2.0); @@ -85,7 +88,7 @@ public void testProcessServiceInfo() { info2.setHosts(hosts2); ServiceInfo actual2 = holder.processServiceInfo(info2); - Assert.assertEquals(info2, actual2); + assertEquals(info2, actual2); } private Instance createInstance(String ip, int port) { @@ -96,17 +99,17 @@ private Instance createInstance(String ip, int port) { } @Test - public void testProcessServiceInfo2() { + void testProcessServiceInfo2() { String json = "{\"groupName\":\"a\",\"name\":\"b\",\"clusters\":\"c\"}"; ServiceInfo actual = holder.processServiceInfo(json); ServiceInfo expect = new ServiceInfo("a@@b@@c"); expect.setJsonFromServer(json); - Assert.assertEquals(expect.getKey(), actual.getKey()); + assertEquals(expect.getKey(), actual.getKey()); } @Test - public void testProcessServiceInfoWithPushEmpty() throws NacosException { + void testProcessServiceInfoWithPushEmpty() throws NacosException { ServiceInfo oldInfo = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); Instance instance2 = createInstance("1.1.1.2", 2); @@ -124,17 +127,17 @@ public void testProcessServiceInfoWithPushEmpty() throws NacosException { final ServiceInfo actual = holder.processServiceInfo(newInfo); - Assert.assertEquals(oldInfo.getKey(), actual.getKey()); - Assert.assertEquals(2, actual.getHosts().size()); + assertEquals(oldInfo.getKey(), actual.getKey()); + assertEquals(2, actual.getHosts().size()); } @Test - public void testProcessNullServiceInfo() { - Assert.assertNull(holder.processServiceInfo(new ServiceInfo())); + void testProcessNullServiceInfo() { + assertNull(holder.processServiceInfo(new ServiceInfo())); } @Test - public void testProcessServiceInfoForOlder() { + void testProcessServiceInfoForOlder() { ServiceInfo info = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); Instance instance2 = createInstance("1.1.1.2", 2); @@ -147,11 +150,11 @@ public void testProcessServiceInfoForOlder() { ServiceInfo olderInfo = new ServiceInfo("a@@b@@c"); olderInfo.setLastRefTime(0L); final ServiceInfo actual = holder.processServiceInfo(olderInfo); - Assert.assertEquals(olderInfo, actual); + assertEquals(olderInfo, actual); } @Test - public void testGetServiceInfo() { + void testGetServiceInfo() { ServiceInfo info = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); List hosts = new ArrayList<>(); @@ -163,47 +166,47 @@ public void testGetServiceInfo() { String groupName = "a"; String clusters = "c"; ServiceInfo actual = holder.getServiceInfo(serviceName, groupName, clusters); - Assert.assertEquals(expect.getKey(), actual.getKey()); - Assert.assertEquals(expect.getHosts().size(), actual.getHosts().size()); - Assert.assertEquals(expect.getHosts().get(0), actual.getHosts().get(0)); + assertEquals(expect.getKey(), actual.getKey()); + assertEquals(expect.getHosts().size(), actual.getHosts().size()); + assertEquals(expect.getHosts().get(0), actual.getHosts().get(0)); } @Test - public void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { Field field = ServiceInfoHolder.class.getDeclaredField("failoverReactor"); field.setAccessible(true); FailoverReactor reactor = (FailoverReactor) field.get(holder); Field executorService = FailoverReactor.class.getDeclaredField("executorService"); executorService.setAccessible(true); ScheduledExecutorService pool = (ScheduledExecutorService) executorService.get(reactor); - Assert.assertFalse(pool.isShutdown()); + assertFalse(pool.isShutdown()); holder.shutdown(); - Assert.assertTrue(pool.isShutdown()); + assertTrue(pool.isShutdown()); } @Test - public void testConstructWithCacheLoad() throws NacosException { + void testConstructWithCacheLoad() throws NacosException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START, "true"); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "non-exist"); holder.shutdown(); holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties); - Assert.assertEquals(System.getProperty("user.home") + "/nacos/non-exist/naming/aa", holder.getCacheDir()); - Assert.assertTrue(holder.getServiceInfoMap().isEmpty()); + assertEquals(System.getProperty("user.home") + "/nacos/non-exist/naming/aa", holder.getCacheDir()); + assertTrue(holder.getServiceInfoMap().isEmpty()); } @Test - public void testIsFailoverSwitch() throws IllegalAccessException, NoSuchFieldException, NacosException { + void testIsFailoverSwitch() throws IllegalAccessException, NoSuchFieldException, NacosException { FailoverReactor mock = injectMockFailoverReactor(); when(mock.isFailoverSwitch()).thenReturn(true); - Assert.assertTrue(holder.isFailoverSwitch()); + assertTrue(holder.isFailoverSwitch()); } @Test - public void testGetFailoverServiceInfo() throws IllegalAccessException, NoSuchFieldException, NacosException { + void testGetFailoverServiceInfo() throws IllegalAccessException, NoSuchFieldException, NacosException { FailoverReactor mock = injectMockFailoverReactor(); ServiceInfo serviceInfo = new ServiceInfo("a@@b@@c"); when(mock.getService("a@@b@@c")).thenReturn(serviceInfo); - Assert.assertEquals(serviceInfo, holder.getFailoverServiceInfo("b", "a", "c")); + assertEquals(serviceInfo, holder.getFailoverServiceInfo("b", "a", "c")); } private FailoverReactor injectMockFailoverReactor() diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java index cc2801d2e91..a26652cfe3a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java @@ -18,36 +18,35 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -public class BalancerTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BalancerTest { @Test - public void testGetHostByRandomWeightNull() { - Assert.assertNull(Balancer.getHostByRandomWeight(null)); - Assert.assertNull(Balancer.getHostByRandomWeight(new ArrayList<>())); + void testGetHostByRandomWeightNull() { + assertNull(Balancer.getHostByRandomWeight(null)); + assertNull(Balancer.getHostByRandomWeight(new ArrayList<>())); } @Test - public void testGetHostByRandomWeight() { + void testGetHostByRandomWeight() { List list = new ArrayList<>(); Instance instance1 = new Instance(); list.add(instance1); final Instance actual = Balancer.getHostByRandomWeight(list); - Assert.assertEquals(instance1, actual); + assertEquals(instance1, actual); } @Test - public void testSelectHost() { + void testSelectHost() { List hosts = new ArrayList<>(); Instance instance1 = new Instance(); hosts.add(instance1); @@ -55,15 +54,16 @@ public void testSelectHost() { serviceInfo.setHosts(hosts); final Instance actual = Balancer.RandomByWeight.selectHost(serviceInfo); - Assert.assertEquals(instance1, actual); + assertEquals(instance1, actual); } @Test - public void testSelectHostEmpty() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("no host to srv for serviceInfo: null"); - ServiceInfo serviceInfo = new ServiceInfo(); - - Balancer.RandomByWeight.selectHost(serviceInfo); + void testSelectHostEmpty() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { + ServiceInfo serviceInfo = new ServiceInfo(); + + Balancer.RandomByWeight.selectHost(serviceInfo); + }); + assertTrue(exception.getMessage().contains("no host to srv for serviceInfo: null")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java index 3954d84c808..23951d6d5ff 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java @@ -16,22 +16,23 @@ package com.alibaba.nacos.client.naming.core; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ProtectModeTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ProtectModeTest { @Test - public void testProtectThresholdDefault() { + void testProtectThresholdDefault() { final ProtectMode protectMode = new ProtectMode(); - Assert.assertEquals(0.8f, protectMode.getProtectThreshold(), 0.01f); + assertEquals(0.8f, protectMode.getProtectThreshold(), 0.01f); } @Test - public void testSetProtectThreshold() { + void testSetProtectThreshold() { final ProtectMode protectMode = new ProtectMode(); float expect = 0.7f; protectMode.setProtectThreshold(expect); - Assert.assertEquals(expect, protectMode.getProtectThreshold(), 0.01f); + assertEquals(expect, protectMode.getProtectThreshold(), 0.01f); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java index 4dbeb9deeec..3fadc114998 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java @@ -22,14 +22,16 @@ import com.alibaba.nacos.common.http.HttpClientBeanHolder; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.client.NacosRestTemplate; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.io.IOException; import java.lang.reflect.Field; @@ -39,11 +41,16 @@ import java.util.Map; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) -public class ServerListManagerTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class ServerListManagerTest { private static final String NS = "ns"; @@ -58,14 +65,14 @@ public class ServerListManagerTest { ServerListManager serverListManager; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { clientProperties = NacosClientProperties.PROTOTYPE.derive(); Field restMapField = HttpClientBeanHolder.class.getDeclaredField("SINGLETON_REST"); restMapField.setAccessible(true); Map restMap = (Map) restMapField.get(null); - cachedNacosRestTemplate = restMap - .get("com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory"); + cachedNacosRestTemplate = restMap.get( + "com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory"); restMap.put("com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory", nacosRestTemplate); httpRestResult = new HttpRestResult<>(); @@ -74,8 +81,8 @@ public void setUp() throws Exception { Mockito.when(nacosRestTemplate.get(any(), any(), any(), any())).thenReturn(httpRestResult); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (null != cachedNacosRestTemplate) { Field restMapField = HttpClientBeanHolder.class.getDeclaredField("SINGLETON_REST"); restMapField.setAccessible(true); @@ -88,107 +95,109 @@ public void tearDown() throws Exception { } } - @Test(expected = NacosLoadException.class) - public void testConstructError() { - serverListManager = new ServerListManager(new Properties()); + @Test + void testConstructError() { + assertThrows(NacosLoadException.class, () -> { + serverListManager = new ServerListManager(new Properties()); + }); } @Test - public void testConstructWithAddr() { + void testConstructWithAddr() { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848,127.0.0.1:8849"); serverListManager = new ServerListManager(properties); final List serverList = serverListManager.getServerList(); - Assert.assertEquals(2, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); - Assert.assertEquals("127.0.0.1:8849", serverList.get(1)); + assertEquals(2, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals("127.0.0.1:8849", serverList.get(1)); } @Test - public void testConstructWithAddrTryToRefresh() + void testConstructWithAddrTryToRefresh() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848,127.0.0.1:8849"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(2, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); - Assert.assertEquals("127.0.0.1:8849", serverList.get(1)); + assertEquals(2, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals("127.0.0.1:8849", serverList.get(1)); mockThreadInvoke(serverListManager, false); serverList = serverListManager.getServerList(); - Assert.assertEquals(2, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); - Assert.assertEquals("127.0.0.1:8849", serverList.get(1)); + assertEquals(2, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals("127.0.0.1:8849", serverList.get(1)); } @Test - public void testConstructWithEndpointAndRefresh() throws Exception { + void testConstructWithEndpointAndRefresh() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); httpRestResult.setData("127.0.0.1:8848\n127.0.0.1:8948"); mockThreadInvoke(serverListManager, true); serverList = serverListManager.getServerList(); - Assert.assertEquals(2, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); - Assert.assertEquals("127.0.0.1:8948", serverList.get(1)); + assertEquals(2, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals("127.0.0.1:8948", serverList.get(1)); } @Test - public void testConstructWithEndpointAndTimedNotNeedRefresh() throws Exception { + void testConstructWithEndpointAndTimedNotNeedRefresh() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); httpRestResult.setData("127.0.0.1:8848\n127.0.0.1:8948"); mockThreadInvoke(serverListManager, false); serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } @Test - public void testConstructWithEndpointAndRefreshEmpty() throws Exception { + void testConstructWithEndpointAndRefreshEmpty() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); httpRestResult.setData(""); mockThreadInvoke(serverListManager, true); serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } @Test - public void testConstructWithEndpointAndRefreshException() + void testConstructWithEndpointAndRefreshException() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); httpRestResult.setCode(500); mockThreadInvoke(serverListManager, true); serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } @Test - public void testConstructWithEndpointWithCustomPathAndName() throws Exception { + void testConstructWithEndpointWithCustomPathAndName() throws Exception { clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "aaa"); clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1"); @@ -197,12 +206,12 @@ public void testConstructWithEndpointWithCustomPathAndName() throws Exception { .thenReturn(httpRestResult); serverListManager = new ServerListManager(clientProperties, "test"); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } @Test - public void testConstructWithEndpointWithEndpointPathAndName() throws Exception { + void testConstructWithEndpointWithEndpointPathAndName() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "aaa"); clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1"); @@ -211,12 +220,12 @@ public void testConstructWithEndpointWithEndpointPathAndName() throws Exception .thenReturn(httpRestResult); serverListManager = new ServerListManager(clientProperties, "test"); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } @Test - public void testConstructEndpointContextPathPriority() throws Exception { + void testConstructEndpointContextPathPriority() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "aaa"); clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "bbb"); clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "ccc"); @@ -226,12 +235,12 @@ public void testConstructEndpointContextPathPriority() throws Exception { .thenReturn(httpRestResult); serverListManager = new ServerListManager(clientProperties, "test"); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } @Test - public void testConstructEndpointContextPathIsEmpty() throws Exception { + void testConstructEndpointContextPathIsEmpty() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, ""); clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "bbb"); clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "ccc"); @@ -241,38 +250,36 @@ public void testConstructEndpointContextPathIsEmpty() throws Exception { .thenReturn(httpRestResult); serverListManager = new ServerListManager(clientProperties, "test"); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } @Test - public void testIsDomain() throws IOException { + void testIsDomain() throws IOException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); serverListManager = new ServerListManager(properties); - Assert.assertTrue(serverListManager.isDomain()); - Assert.assertEquals("127.0.0.1:8848", serverListManager.getNacosDomain()); + assertTrue(serverListManager.isDomain()); + assertEquals("127.0.0.1:8848", serverListManager.getNacosDomain()); } @Test - public void testGetCurrentServer() { + void testGetCurrentServer() { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); final ServerListManager serverListManager = new ServerListManager(properties); - Assert.assertEquals("127.0.0.1:8848", serverListManager.getCurrentServer()); - Assert.assertEquals("127.0.0.1:8848", serverListManager.genNextServer()); + assertEquals("127.0.0.1:8848", serverListManager.getCurrentServer()); + assertEquals("127.0.0.1:8848", serverListManager.genNextServer()); } @Test - public void testShutdown() { + void testShutdown() { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); final ServerListManager serverListManager = new ServerListManager(properties); - try { + Assertions.assertDoesNotThrow(() -> { serverListManager.shutdown(); - } catch (Exception e) { - Assert.fail(); - } + }); } private void mockThreadInvoke(ServerListManager serverListManager, boolean expectedInvoked) diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java index aaffa64adb4..f6833d7d5ef 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java @@ -24,13 +24,15 @@ import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder; import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier; import com.alibaba.nacos.client.naming.remote.NamingClientProxy; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.lang.reflect.Field; import java.util.Collections; @@ -40,11 +42,13 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ServiceInfoUpdateServiceTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class ServiceInfoUpdateServiceTest { String serviceName = "aa"; @@ -67,8 +71,8 @@ public class ServiceInfoUpdateServiceTest { ServiceInfoUpdateService serviceInfoUpdateService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(); info = new ServiceInfo(); info.setName(serviceName); @@ -78,15 +82,15 @@ public void setUp() throws Exception { when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenReturn(info); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (null != serviceInfoUpdateService) { serviceInfoUpdateService.shutdown(); } } @Test - public void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosException { + void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosException { serviceInfoUpdateService = new ServiceInfoUpdateService(null, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); TimeUnit.MILLISECONDS.sleep(1500); @@ -94,7 +98,7 @@ public void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosEx } @Test - public void testScheduleUpdateIfAbsent() throws InterruptedException, NacosException { + void testScheduleUpdateIfAbsent() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -104,7 +108,7 @@ public void testScheduleUpdateIfAbsent() throws InterruptedException, NacosExcep } @Test - public void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, NacosException { + void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -116,7 +120,7 @@ public void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, N } @Test - public void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, NacosException { + void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -129,7 +133,7 @@ public void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, } @Test - public void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws InterruptedException, NacosException { + void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -143,43 +147,43 @@ public void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws Interrupt } @Test - public void testScheduleUpdateIfAbsentWith403Exception() + void testScheduleUpdateIfAbsentWith403Exception() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); - when(proxy.queryInstancesOfService(serviceName, group, clusters, false)) - .thenThrow(new NacosException(403, "test")); + when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenThrow( + new NacosException(403, "test")); TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 1000); } @Test - public void testScheduleUpdateIfAbsentWith500Exception() + void testScheduleUpdateIfAbsentWith500Exception() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); - when(proxy.queryInstancesOfService(serviceName, group, clusters, false)) - .thenThrow(new NacosException(500, "test")); + when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenThrow( + new NacosException(500, "test")); TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 2000); } @Test - public void testScheduleUpdateIfAbsentWithOtherException() + void testScheduleUpdateIfAbsentWithOtherException() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); - when(proxy.queryInstancesOfService(serviceName, group, clusters, false)) - .thenThrow(new RuntimeException("test")); + when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenThrow( + new RuntimeException("test")); TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 1000); } @Test - public void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosException { + void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -190,7 +194,7 @@ public void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosE } @Test - public void testStopUpdateIfContainWithoutOpen() throws NacosException, InterruptedException { + void testStopUpdateIfContainWithoutOpen() throws NacosException, InterruptedException { serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); TimeUnit.MILLISECONDS.sleep(1500); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java index 17cdfff75c4..4f22b4af69b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java @@ -17,16 +17,17 @@ package com.alibaba.nacos.client.naming.event; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -public class InstancesChangeEventTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InstancesChangeEventTest { @Test - public void testGetServiceName() { + void testGetServiceName() { String eventScope = "scope-001"; String serviceName = "a"; String groupName = "b"; @@ -35,12 +36,12 @@ public void testGetServiceName() { Instance ins = new Instance(); hosts.add(ins); InstancesChangeEvent event = new InstancesChangeEvent(eventScope, serviceName, groupName, clusters, hosts); - Assert.assertEquals(eventScope, event.scope()); - Assert.assertEquals(serviceName, event.getServiceName()); - Assert.assertEquals(clusters, event.getClusters()); - Assert.assertEquals(groupName, event.getGroupName()); + assertEquals(eventScope, event.scope()); + assertEquals(serviceName, event.getServiceName()); + assertEquals(clusters, event.getClusters()); + assertEquals(groupName, event.getGroupName()); List hosts1 = event.getHosts(); - Assert.assertEquals(hosts.size(), hosts1.size()); - Assert.assertEquals(hosts.get(0), hosts1.get(0)); + assertEquals(hosts.size(), hosts1.size()); + assertEquals(hosts.get(0), hosts1.get(0)); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java index 858ac881336..b8eeb9496e4 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java @@ -20,24 +20,26 @@ import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -public class InstancesChangeNotifierTest { +class InstancesChangeNotifierTest { @Test - public void testRegisterListener() { + void testRegisterListener() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -46,20 +48,20 @@ public void testRegisterListener() { EventListener listener = Mockito.mock(EventListener.class); instancesChangeNotifier.registerListener(group, name, clusters, listener); List subscribeServices = instancesChangeNotifier.getSubscribeServices(); - Assert.assertEquals(1, subscribeServices.size()); - Assert.assertEquals(group, subscribeServices.get(0).getGroupName()); - Assert.assertEquals(name, subscribeServices.get(0).getName()); - Assert.assertEquals(clusters, subscribeServices.get(0).getClusters()); + assertEquals(1, subscribeServices.size()); + assertEquals(group, subscribeServices.get(0).getGroupName()); + assertEquals(name, subscribeServices.get(0).getName()); + assertEquals(clusters, subscribeServices.get(0).getClusters()); List hosts = new ArrayList<>(); Instance ins = new Instance(); hosts.add(ins); InstancesChangeEvent event = new InstancesChangeEvent(eventScope, name, group, clusters, hosts); - Assert.assertEquals(true, instancesChangeNotifier.scopeMatches(event)); + assertTrue(instancesChangeNotifier.scopeMatches(event)); } @Test - public void testDeregisterListener() { + void testDeregisterListener() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -68,33 +70,33 @@ public void testDeregisterListener() { EventListener listener = Mockito.mock(EventListener.class); instancesChangeNotifier.registerListener(group, name, clusters, listener); List subscribeServices = instancesChangeNotifier.getSubscribeServices(); - Assert.assertEquals(1, subscribeServices.size()); + assertEquals(1, subscribeServices.size()); instancesChangeNotifier.deregisterListener(group, name, clusters, listener); List subscribeServices2 = instancesChangeNotifier.getSubscribeServices(); - Assert.assertEquals(0, subscribeServices2.size()); + assertEquals(0, subscribeServices2.size()); instancesChangeNotifier.deregisterListener(group, name, clusters, listener); - Assert.assertEquals(0, subscribeServices2.size()); + assertEquals(0, subscribeServices2.size()); } @Test - public void testIsSubscribed() { + void testIsSubscribed() { String eventScope = "scope-001"; String group = "a"; String name = "b"; String clusters = "c"; InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); EventListener listener = Mockito.mock(EventListener.class); - Assert.assertFalse(instancesChangeNotifier.isSubscribed(group, name, clusters)); + assertFalse(instancesChangeNotifier.isSubscribed(group, name, clusters)); instancesChangeNotifier.registerListener(group, name, clusters, listener); - Assert.assertTrue(instancesChangeNotifier.isSubscribed(group, name, clusters)); + assertTrue(instancesChangeNotifier.isSubscribed(group, name, clusters)); } @Test - public void testOnEvent() { + void testOnEvent() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -113,7 +115,7 @@ public void testOnEvent() { } @Test - public void testOnEventWithoutListener() { + void testOnEventWithoutListener() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -130,7 +132,7 @@ public void testOnEventWithoutListener() { } @Test - public void testOnEventByExecutor() { + void testOnEventByExecutor() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -151,9 +153,9 @@ public void testOnEventByExecutor() { } @Test - public void testSubscribeType() { + void testSubscribeType() { String eventScope = "scope-001"; InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); - Assert.assertEquals(InstancesChangeEvent.class, instancesChangeNotifier.subscribeType()); + assertEquals(InstancesChangeEvent.class, instancesChangeNotifier.subscribeType()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java index 22863f57d92..b2b60a68d30 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java @@ -31,21 +31,22 @@ import com.alibaba.nacos.client.utils.AppNameUtils; import com.alibaba.nacos.common.notify.Event; import com.alibaba.nacos.plugin.auth.api.RequestResource; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.HashMap; import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class AbstractNamingClientProxyTest { +@ExtendWith(MockitoExtension.class) +class AbstractNamingClientProxyTest { @Mock private SecurityProxy sc; @@ -54,16 +55,16 @@ public class AbstractNamingClientProxyTest { * test get security headers for accessToken. */ @Test - public void testGetSecurityHeadersForAccessToken() { + void testGetSecurityHeadersForAccessToken() { AbstractNamingClientProxy proxy = new MockNamingClientProxy(sc); String token = "aa"; Map keyMap = new HashMap<>(); keyMap.put(Constants.ACCESS_TOKEN, token); when(sc.getIdentityContext(any(RequestResource.class))).thenReturn(keyMap); Map securityHeaders = proxy.getSecurityHeaders("", "", ""); - Assert.assertEquals(2, securityHeaders.size()); - Assert.assertEquals(token, securityHeaders.get(Constants.ACCESS_TOKEN)); - Assert.assertEquals(AppNameUtils.getAppName(), securityHeaders.get("app")); + assertEquals(2, securityHeaders.size()); + assertEquals(token, securityHeaders.get(Constants.ACCESS_TOKEN)); + assertEquals(AppNameUtils.getAppName(), securityHeaders.get("app")); } /** @@ -72,7 +73,7 @@ public void testGetSecurityHeadersForAccessToken() { * @throws Exception exception */ @Test - public void testGetSecurityHeadersForRam() throws Exception { + void testGetSecurityHeadersForRam() throws Exception { String ak = "aa"; String sk = "bb"; Map mockIdentityContext = new HashMap<>(); @@ -84,12 +85,12 @@ public void testGetSecurityHeadersForRam() throws Exception { when(sc.getIdentityContext(any(RequestResource.class))).thenReturn(mockIdentityContext); AbstractNamingClientProxy proxy = new MockNamingClientProxy(sc); Map spasHeaders = proxy.getSecurityHeaders("", "", serviceName); - Assert.assertEquals(4, spasHeaders.size()); - Assert.assertEquals(AppNameUtils.getAppName(), spasHeaders.get("app")); - Assert.assertEquals(ak, spasHeaders.get("ak")); - Assert.assertTrue(spasHeaders.get("data").endsWith("@@" + serviceName)); + assertEquals(4, spasHeaders.size()); + assertEquals(AppNameUtils.getAppName(), spasHeaders.get("app")); + assertEquals(ak, spasHeaders.get("ak")); + assertTrue(spasHeaders.get("data").endsWith("@@" + serviceName)); String expectSign = SignUtil.sign(spasHeaders.get("data"), sk); - Assert.assertEquals(expectSign, spasHeaders.get("signature")); + assertEquals(expectSign, spasHeaders.get("signature")); } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java index d1074f93dc3..bdc3ac6cec1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java @@ -31,27 +31,31 @@ import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier; import com.alibaba.nacos.client.naming.remote.gprc.NamingGrpcClientProxy; import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamingClientProxyDelegateTest { +@ExtendWith(MockitoExtension.class) +class NamingClientProxyDelegateTest { private static final String TEST_NAMESPACE = "ns1"; @@ -67,8 +71,8 @@ public class NamingClientProxyDelegateTest { NacosClientProperties nacosClientProperties; - @Before - public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties props = new Properties(); props.setProperty("serverAddr", "localhost"); nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props); @@ -79,13 +83,13 @@ public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessEx grpcClientProxyField.set(delegate, mockGrpcClient); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { delegate.shutdown(); } @Test - public void testRegisterEphemeralServiceByGrpc() throws NacosException { + void testRegisterEphemeralServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -99,7 +103,7 @@ public void testRegisterEphemeralServiceByGrpc() throws NacosException { } @Test - public void testBatchRegisterServiceByGrpc() throws NacosException { + void testBatchRegisterServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -114,7 +118,7 @@ public void testBatchRegisterServiceByGrpc() throws NacosException { } @Test - public void testBatchDeregisterServiceByGrpc() throws NacosException { + void testBatchDeregisterServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; List instanceList = new ArrayList<>(); @@ -127,7 +131,7 @@ public void testBatchDeregisterServiceByGrpc() throws NacosException { } @Test - public void testRegisterPersistentServiceByGrpc() throws NacosException { + void testRegisterPersistentServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -138,15 +142,14 @@ public void testRegisterPersistentServiceByGrpc() throws NacosException { // persistent instance instance.setEphemeral(false); // when server support register persistent instance by grpc, will use grpc to register - when(mockGrpcClient.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(true); + when(mockGrpcClient.isAbilitySupportedByServer( + AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn(true); delegate.registerService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).registerService(serviceName, groupName, instance); } @Test - public void testRegisterPersistentServiceByHttp() - throws NacosException, NoSuchFieldException, IllegalAccessException { + void testRegisterPersistentServiceByHttp() throws NacosException, NoSuchFieldException, IllegalAccessException { NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class); Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy"); mockHttpClientField.setAccessible(true); @@ -167,7 +170,7 @@ public void testRegisterPersistentServiceByHttp() } @Test - public void testDeregisterEphemeralServiceGrpc() throws NacosException { + void testDeregisterEphemeralServiceGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -182,7 +185,7 @@ public void testDeregisterEphemeralServiceGrpc() throws NacosException { } @Test - public void testDeregisterPersistentServiceGrpc() throws NacosException { + void testDeregisterPersistentServiceGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -193,15 +196,14 @@ public void testDeregisterPersistentServiceGrpc() throws NacosException { // persistent instance instance.setEphemeral(false); // when server support deregister persistent instance by grpc, will use grpc to deregister - when(mockGrpcClient.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(true); + when(mockGrpcClient.isAbilitySupportedByServer( + AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn(true); delegate.deregisterService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).deregisterService(serviceName, groupName, instance); } @Test - public void testDeregisterPersistentServiceHttp() - throws NacosException, NoSuchFieldException, IllegalAccessException { + void testDeregisterPersistentServiceHttp() throws NacosException, NoSuchFieldException, IllegalAccessException { NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class); Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy"); mockHttpClientField.setAccessible(true); @@ -221,19 +223,17 @@ public void testDeregisterPersistentServiceHttp() } @Test - public void testUpdateInstance() { + void testUpdateInstance() { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); - try { + Assertions.assertDoesNotThrow(() -> { delegate.updateInstance(serviceName, groupName, instance); - } catch (Exception e) { - Assert.fail(); - } + }); } @Test - public void testQueryInstancesOfService() throws NacosException { + void testQueryInstancesOfService() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; @@ -242,38 +242,34 @@ public void testQueryInstancesOfService() throws NacosException { } @Test - public void testQueryService() throws NacosException { + void testQueryService() throws NacosException { Service service = delegate.queryService("a", "b"); - Assert.assertNull(service); + assertNull(service); } @Test - public void testCreateService() { + void testCreateService() { Service service = new Service(); - try { + Assertions.assertDoesNotThrow(() -> { delegate.createService(service, new NoneSelector()); - } catch (Exception e) { - Assert.fail(); - } + }); } @Test - public void testDeleteService() throws NacosException { - Assert.assertFalse(delegate.deleteService("service", "group1")); + void testDeleteService() throws NacosException { + assertFalse(delegate.deleteService("service", "group1")); } @Test - public void testUpdateService() { + void testUpdateService() { Service service = new Service(); - try { + Assertions.assertDoesNotThrow(() -> { delegate.updateService(service, new ExpressionSelector()); - } catch (Exception e) { - Assert.fail(); - } + }); } @Test - public void testGetServiceList() throws NacosException { + void testGetServiceList() throws NacosException { AbstractSelector selector = new ExpressionSelector(); int pageNo = 1; int pageSize = 10; @@ -284,7 +280,7 @@ public void testGetServiceList() throws NacosException { } @Test - public void testSubscribe() throws NacosException { + void testSubscribe() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; @@ -295,14 +291,14 @@ public void testSubscribe() throws NacosException { when(mockGrpcClient.subscribe(serviceName, groupName, clusters)).thenReturn(info); ServiceInfo actual = delegate.subscribe(serviceName, groupName, clusters); - Assert.assertEquals(info, actual); + assertEquals(info, actual); verify(mockGrpcClient, times(1)).subscribe(serviceName, groupName, clusters); verify(holder, times(1)).processServiceInfo(info); } @Test - public void testUnsubscribe() throws NacosException { + void testUnsubscribe() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; @@ -311,23 +307,23 @@ public void testUnsubscribe() throws NacosException { } @Test - public void testServerHealthy() { + void testServerHealthy() { Mockito.when(mockGrpcClient.serverHealthy()).thenReturn(true); - Assert.assertTrue(delegate.serverHealthy()); + assertTrue(delegate.serverHealthy()); } @Test - public void testIsSubscribed() throws NacosException { + void testIsSubscribed() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; - Assert.assertFalse(delegate.isSubscribed(serviceName, groupName, clusters)); + assertFalse(delegate.isSubscribed(serviceName, groupName, clusters)); when(mockGrpcClient.isSubscribed(serviceName, groupName, clusters)).thenReturn(true); - Assert.assertTrue(delegate.isSubscribed(serviceName, groupName, clusters)); + assertTrue(delegate.isSubscribed(serviceName, groupName, clusters)); } @Test - public void testShutdown() throws NacosException { + void testShutdown() throws NacosException { delegate.shutdown(); verify(mockGrpcClient, times(1)).shutdown(); } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java index 901d6d4a7b2..18b7f6ef3a1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java @@ -60,16 +60,15 @@ import com.alibaba.nacos.common.remote.client.grpc.GrpcClient; import com.alibaba.nacos.common.remote.client.grpc.GrpcClientConfig; import com.alibaba.nacos.common.remote.client.grpc.GrpcConstants; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.lang.reflect.Field; import java.util.ArrayList; @@ -83,8 +82,13 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doThrow; @@ -92,11 +96,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamingGrpcClientProxyTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class NamingGrpcClientProxyTest { private static final String NAMESPACE_ID = "ns1"; @@ -132,11 +135,8 @@ public class NamingGrpcClientProxyTest { private String uuid; - @Rule - public final ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { System.setProperty(GrpcConstants.GRPC_RETRY_TIMES, "1"); System.setProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT, "100"); List serverList = Stream.of(ORIGIN_SERVER, "anotherServer").collect(Collectors.toList()); @@ -151,7 +151,7 @@ public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessEx uuidField.setAccessible(true); uuid = (String) uuidField.get(client); - Assert.assertNotNull(RpcClientFactory.getClient(uuid)); + assertNotNull(RpcClientFactory.getClient(uuid)); Field rpcClientField = NamingGrpcClientProxy.class.getDeclaredField("rpcClient"); rpcClientField.setAccessible(true); ((RpcClient) rpcClientField.get(client)).shutdown(); @@ -171,15 +171,15 @@ public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessEx persistentInstance.setEphemeral(false); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { System.clearProperty(GrpcConstants.GRPC_RETRY_TIMES); System.clearProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT); client.shutdown(); } @Test - public void testRegisterService() throws NacosException { + void testRegisterService() throws NacosException { client.registerService(SERVICE_NAME, GROUP_NAME, instance); verify(this.rpcClient, times(1)).request(argThat(request -> { if (request instanceof InstanceRequest) { @@ -191,7 +191,7 @@ public void testRegisterService() throws NacosException { } @Test - public void testRegisterPersistentService() throws NacosException { + void testRegisterPersistentService() throws NacosException { client.registerService(SERVICE_NAME, GROUP_NAME, persistentInstance); verify(this.rpcClient, times(1)).request(argThat(request -> { if (request instanceof PersistentInstanceRequest) { @@ -203,39 +203,41 @@ public void testRegisterPersistentService() throws NacosException { } @Test - public void testRegisterServiceThrowsNacosException() throws NacosException { - expectedException.expect(NacosException.class); - expectedException.expectMessage("err args"); - - when(this.rpcClient.request(Mockito.any())).thenReturn(ErrorResponse.build(400, "err args")); - - try { - client.registerService(SERVICE_NAME, GROUP_NAME, instance); - } catch (NacosException ex) { - Assert.assertNull(ex.getCause()); + void testRegisterServiceThrowsNacosException() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { - throw ex; - } + when(this.rpcClient.request(Mockito.any())).thenReturn(ErrorResponse.build(400, "err args")); + + try { + client.registerService(SERVICE_NAME, GROUP_NAME, instance); + } catch (NacosException ex) { + assertNull(ex.getCause()); + + throw ex; + } + }); + assertTrue(exception.getMessage().contains("err args")); } @Test - public void testRegisterServiceThrowsException() throws NacosException { - expectedException.expect(NacosException.class); - expectedException.expectMessage("Request nacos server failed: "); - - when(this.rpcClient.request(Mockito.any())).thenReturn(null); - - try { - client.registerService(SERVICE_NAME, GROUP_NAME, instance); - } catch (NacosException ex) { - Assert.assertEquals(NullPointerException.class, ex.getCause().getClass()); + void testRegisterServiceThrowsException() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { - throw ex; - } + when(this.rpcClient.request(Mockito.any())).thenReturn(null); + + try { + client.registerService(SERVICE_NAME, GROUP_NAME, instance); + } catch (NacosException ex) { + assertEquals(NullPointerException.class, ex.getCause().getClass()); + + throw ex; + } + }); + assertTrue(exception.getMessage().contains("Request nacos server failed: ")); } @Test - public void testDeregisterService() throws NacosException { + void testDeregisterService() throws NacosException { client.deregisterService(SERVICE_NAME, GROUP_NAME, instance); verify(this.rpcClient, times(1)).request(argThat(request -> { if (request instanceof InstanceRequest) { @@ -247,7 +249,7 @@ public void testDeregisterService() throws NacosException { } @Test - public void testDeregisterPersistentService() throws NacosException { + void testDeregisterPersistentService() throws NacosException { client.deregisterService(SERVICE_NAME, GROUP_NAME, persistentInstance); verify(this.rpcClient, times(1)).request(argThat(request -> { if (request instanceof PersistentInstanceRequest) { @@ -259,7 +261,7 @@ public void testDeregisterPersistentService() throws NacosException { } @Test - public void testDeregisterServiceForBatchRegistered() throws NacosException { + void testDeregisterServiceForBatchRegistered() throws NacosException { try { List instanceList = new ArrayList<>(); instance.setHealthy(true); @@ -286,7 +288,7 @@ public void testDeregisterServiceForBatchRegistered() throws NacosException { } @Test - public void testBatchRegisterService() throws NacosException { + void testBatchRegisterService() throws NacosException { List instanceList = new ArrayList<>(); instance.setHealthy(true); instanceList.add(instance); @@ -303,42 +305,50 @@ public void testBatchRegisterService() throws NacosException { })); } - @Test(expected = NacosException.class) - public void testBatchDeregisterServiceWithEmptyInstances() throws NacosException { - client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); + @Test + void testBatchDeregisterServiceWithEmptyInstances() throws NacosException { + assertThrows(NacosException.class, () -> { + client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); + }); } - @Test(expected = NacosException.class) - public void testBatchDeregisterServiceWithoutCacheData() throws NacosException { - List instanceList = new ArrayList<>(); - instance.setHealthy(true); - instanceList.add(instance); - client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + @Test + void testBatchDeregisterServiceWithoutCacheData() throws NacosException { + assertThrows(NacosException.class, () -> { + List instanceList = new ArrayList<>(); + instance.setHealthy(true); + instanceList.add(instance); + client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + }); } - @Test(expected = NacosException.class) - public void testBatchDeregisterServiceNotBatchData() throws NacosException { - client.registerService(SERVICE_NAME, GROUP_NAME, instance); - List instanceList = new ArrayList<>(); - instance.setHealthy(true); - instanceList.add(instance); - client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + @Test + void testBatchDeregisterServiceNotBatchData() throws NacosException { + assertThrows(NacosException.class, () -> { + client.registerService(SERVICE_NAME, GROUP_NAME, instance); + List instanceList = new ArrayList<>(); + instance.setHealthy(true); + instanceList.add(instance); + client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + }); } - @Test(expected = NacosException.class) - public void testBatchDeregisterServiceWithEmptyBatchData() throws NacosException { - try { - client.batchRegisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); - } catch (Exception ignored) { - } - List instanceList = new ArrayList<>(); - instance.setHealthy(true); - instanceList.add(instance); - client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + @Test + void testBatchDeregisterServiceWithEmptyBatchData() throws NacosException { + assertThrows(NacosException.class, () -> { + try { + client.batchRegisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); + } catch (Exception ignored) { + } + List instanceList = new ArrayList<>(); + instance.setHealthy(true); + instanceList.add(instance); + client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + }); } @Test - public void testBatchDeregisterService() throws NacosException { + void testBatchDeregisterService() throws NacosException { try { List instanceList = new ArrayList<>(); instance.setHealthy(true); @@ -365,7 +375,7 @@ public void testBatchDeregisterService() throws NacosException { } @Test - public void testBatchDeregisterServiceWithOtherPortInstance() throws NacosException { + void testBatchDeregisterServiceWithOtherPortInstance() throws NacosException { try { List instanceList = new ArrayList<>(); instance.setHealthy(true); @@ -395,29 +405,29 @@ public void testBatchDeregisterServiceWithOtherPortInstance() throws NacosExcept } @Test - public void testUpdateInstance() throws Exception { + void testUpdateInstance() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); client.updateInstance(SERVICE_NAME, GROUP_NAME, instance); } @Test - public void testQueryInstancesOfService() throws Exception { + void testQueryInstancesOfService() throws Exception { QueryServiceResponse res = new QueryServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); when(this.rpcClient.request(any())).thenReturn(res); ServiceInfo actual = client.queryInstancesOfService(SERVICE_NAME, GROUP_NAME, CLUSTERS, false); - Assert.assertEquals(info, actual); + assertEquals(info, actual); } @Test - public void testQueryService() throws Exception { + void testQueryService() throws Exception { Service service = client.queryService(SERVICE_NAME, GROUP_NAME); - Assert.assertNull(service); + assertNull(service); } @Test - public void testCreateService() throws Exception { + void testCreateService() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); Service service = new Service(); AbstractSelector selector = new NoneSelector(); @@ -425,13 +435,13 @@ public void testCreateService() throws Exception { } @Test - public void testDeleteService() throws Exception { + void testDeleteService() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); assertFalse(client.deleteService(SERVICE_NAME, GROUP_NAME)); } @Test - public void testUpdateService() throws NacosException { + void testUpdateService() throws NacosException { //TODO thrown.expect(UnsupportedOperationException.class); Service service = new Service(); AbstractSelector selector = new NoneSelector(); @@ -439,7 +449,7 @@ public void testUpdateService() throws NacosException { } @Test - public void testGetServiceList() throws Exception { + void testGetServiceList() throws Exception { ServiceListResponse res = new ServiceListResponse(); List services = Arrays.asList("service1", "service2"); res.setServiceNames(services); @@ -447,12 +457,12 @@ public void testGetServiceList() throws Exception { when(this.rpcClient.request(any())).thenReturn(res); AbstractSelector selector = new NoneSelector(); ListView serviceList = client.getServiceList(1, 10, GROUP_NAME, selector); - Assert.assertEquals(5, serviceList.getCount()); - Assert.assertEquals(services, serviceList.getData()); + assertEquals(5, serviceList.getCount()); + assertEquals(services, serviceList.getData()); } @Test - public void testGetServiceListForLabelSelector() throws Exception { + void testGetServiceListForLabelSelector() throws Exception { ServiceListResponse res = new ServiceListResponse(); List services = Arrays.asList("service1", "service2"); res.setServiceNames(services); @@ -460,22 +470,22 @@ public void testGetServiceListForLabelSelector() throws Exception { when(this.rpcClient.request(any())).thenReturn(res); AbstractSelector selector = new ExpressionSelector(); ListView serviceList = client.getServiceList(1, 10, GROUP_NAME, selector); - Assert.assertEquals(5, serviceList.getCount()); - Assert.assertEquals(services, serviceList.getData()); + assertEquals(5, serviceList.getCount()); + assertEquals(services, serviceList.getData()); } @Test - public void testSubscribe() throws Exception { + void testSubscribe() throws Exception { SubscribeServiceResponse res = new SubscribeServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); when(this.rpcClient.request(any())).thenReturn(res); ServiceInfo actual = client.subscribe(SERVICE_NAME, GROUP_NAME, CLUSTERS); - Assert.assertEquals(info, actual); + assertEquals(info, actual); } @Test - public void testUnsubscribe() throws Exception { + void testUnsubscribe() throws Exception { SubscribeServiceResponse res = new SubscribeServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); @@ -486,16 +496,16 @@ public void testUnsubscribe() throws Exception { SubscribeServiceRequest request1 = (SubscribeServiceRequest) request; // verify request fields - return !request1.isSubscribe() && SERVICE_NAME.equals(request1.getServiceName()) && GROUP_NAME - .equals(request1.getGroupName()) && CLUSTERS.equals(request1.getClusters()) && NAMESPACE_ID - .equals(request1.getNamespace()); + return !request1.isSubscribe() && SERVICE_NAME.equals(request1.getServiceName()) && GROUP_NAME.equals( + request1.getGroupName()) && CLUSTERS.equals(request1.getClusters()) && NAMESPACE_ID.equals( + request1.getNamespace()); } return false; })); } @Test - public void testIsSubscribed() throws NacosException { + void testIsSubscribed() throws NacosException { SubscribeServiceResponse res = new SubscribeServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); @@ -506,53 +516,53 @@ public void testIsSubscribed() throws NacosException { } @Test - public void testServerHealthy() { + void testServerHealthy() { when(this.rpcClient.isRunning()).thenReturn(true); - Assert.assertTrue(client.serverHealthy()); + assertTrue(client.serverHealthy()); verify(this.rpcClient, times(1)).isRunning(); } @Test - public void testIsAbilitySupportedByServer1() { - when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(AbilityStatus.SUPPORTED); - Assert.assertTrue(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + void testIsAbilitySupportedByServer1() { + when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( + AbilityStatus.SUPPORTED); + assertTrue(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } @Test - public void testIsAbilitySupportedByServer2() { - when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(AbilityStatus.NOT_SUPPORTED); - Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + void testIsAbilitySupportedByServer2() { + when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( + AbilityStatus.NOT_SUPPORTED); + assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } @Test - public void testIsAbilitySupportedByServer3() { - when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(AbilityStatus.UNKNOWN); - Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + void testIsAbilitySupportedByServer3() { + when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( + AbilityStatus.UNKNOWN); + assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } @Test - public void testIsAbilitySupportedByServer4() { - when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(null); - Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + void testIsAbilitySupportedByServer4() { + when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( + null); + assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } @Test - public void testShutdown() throws Exception { + void testShutdown() throws Exception { client.shutdown(); - Assert.assertNull(RpcClientFactory.getClient(uuid)); + assertNull(RpcClientFactory.getClient(uuid)); //verify(this.rpcClient, times(1)).shutdown(); } @Test - public void testShutdownWithException() throws NoSuchFieldException, IllegalAccessException, NacosException { + void testShutdownWithException() throws NoSuchFieldException, IllegalAccessException, NacosException { Field field = RpcClientFactory.class.getDeclaredField("CLIENT_MAP"); field.setAccessible(true); Map map = (Map) field.get(RpcClientFactory.class); @@ -566,14 +576,14 @@ public void testShutdownWithException() throws NoSuchFieldException, IllegalAcce } @Test - public void testIsEnable() { + void testIsEnable() { when(this.rpcClient.isRunning()).thenReturn(true); - Assert.assertTrue(client.isEnable()); + assertTrue(client.isEnable()); verify(this.rpcClient, times(1)).isRunning(); } @Test - public void testServerListChanged() throws Exception { + void testServerListChanged() throws Exception { RpcClient rpc = new RpcClient(new RpcClientConfig() { @Override @@ -664,11 +674,11 @@ public void close() { while (!rpc.isRunning()) { TimeUnit.MILLISECONDS.sleep(200); if (--retry < 0) { - Assert.fail("rpc is not running"); + fail("rpc is not running"); } } - Assert.assertEquals(ORIGIN_SERVER, rpc.getCurrentServer().getServerIp()); + assertEquals(ORIGIN_SERVER, rpc.getCurrentServer().getServerIp()); String newServer = "www.aliyun.com"; when(factory.genNextServer()).thenReturn(newServer); @@ -679,15 +689,15 @@ public void close() { while (ORIGIN_SERVER.equals(rpc.getCurrentServer().getServerIp())) { TimeUnit.MILLISECONDS.sleep(200); if (--retry < 0) { - Assert.fail("failed to auth switch server"); + fail("failed to auth switch server"); } } - Assert.assertEquals(newServer, rpc.getCurrentServer().getServerIp()); + assertEquals(newServer, rpc.getCurrentServer().getServerIp()); } @Test - public void testConfigAppNameLabels() throws Exception { + void testConfigAppNameLabels() throws Exception { final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); client = new NamingGrpcClientProxy(NAMESPACE_ID, proxy, factory, nacosClientProperties, holder); Field rpcClientField = NamingGrpcClientProxy.class.getDeclaredField("rpcClient"); @@ -697,6 +707,6 @@ public void testConfigAppNameLabels() throws Exception { clientConfig.setAccessible(true); GrpcClientConfig config = (GrpcClientConfig) clientConfig.get(rpcClient); String appName = config.labels().get(Constants.APPNAME); - Assert.assertNotNull(appName); + assertNotNull(appName); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java index 791f3c5a540..341c26e1dcd 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java @@ -27,17 +27,18 @@ import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder; import com.alibaba.nacos.client.naming.remote.TestConnection; import com.alibaba.nacos.common.remote.client.RpcClient; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class NamingPushRequestHandlerTest { +class NamingPushRequestHandlerTest { @Test - public void testRequestReply() { + void testRequestReply() { //given ServiceInfoHolder holder = mock(ServiceInfoHolder.class); NamingPushRequestHandler handler = new NamingPushRequestHandler(holder); @@ -46,15 +47,14 @@ public void testRequestReply() { //when Response response = handler.requestReply(req, new TestConnection(new RpcClient.ServerInfo())); //then - Assert.assertTrue(response instanceof NotifySubscriberResponse); + assertTrue(response instanceof NotifySubscriberResponse); verify(holder, times(1)).processServiceInfo(info); } @Test - public void testRequestReplyOtherType() { + void testRequestReplyOtherType() { ServiceInfoHolder holder = mock(ServiceInfoHolder.class); NamingPushRequestHandler handler = new NamingPushRequestHandler(holder); - Assert.assertNull( - handler.requestReply(new HealthCheckRequest(), new TestConnection(new RpcClient.ServerInfo()))); + assertNull(handler.requestReply(new HealthCheckRequest(), new TestConnection(new RpcClient.ServerInfo()))); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java index 23681502af4..61c31fc51ef 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java @@ -18,20 +18,20 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.client.naming.remote.TestConnection; import com.alibaba.nacos.client.env.NacosClientProperties; +import com.alibaba.nacos.client.naming.remote.TestConnection; import com.alibaba.nacos.client.naming.remote.gprc.NamingGrpcClientProxy; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.BatchInstanceRedoData; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.InstanceRedoData; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.SubscriberRedoData; import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.utils.ReflectUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.ArrayList; @@ -40,12 +40,12 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(MockitoJUnitRunner.class) -public class NamingGrpcRedoServiceTest { +@ExtendWith(MockitoExtension.class) +class NamingGrpcRedoServiceTest { private static final String SERVICE = "service"; @@ -58,8 +58,8 @@ public class NamingGrpcRedoServiceTest { private NamingGrpcRedoService redoService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { Properties prop = new Properties(); NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); redoService = new NamingGrpcRedoService(clientProxy, nacosClientProperties); @@ -68,56 +68,56 @@ public void setUp() throws Exception { redoExecutor.shutdownNow(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { redoService.shutdown(); } @Test - public void testDefaultProperties() throws Exception { + void testDefaultProperties() throws Exception { Field redoThreadCountField = NamingGrpcRedoService.class.getDeclaredField("redoThreadCount"); redoThreadCountField.setAccessible(true); - + Field redoDelayTimeField = NamingGrpcRedoService.class.getDeclaredField("redoDelayTime"); redoDelayTimeField.setAccessible(true); - + Long redoDelayTimeValue = (Long) redoDelayTimeField.get(redoService); Integer redoThreadCountValue = (Integer) redoThreadCountField.get(redoService); - + assertEquals(Long.valueOf(3000L), redoDelayTimeValue); assertEquals(Integer.valueOf(1), redoThreadCountValue); } - + @Test - public void testCustomProperties() throws Exception { + void testCustomProperties() throws Exception { Properties prop = new Properties(); prop.setProperty(PropertyKeyConst.REDO_DELAY_TIME, "4000"); prop.setProperty(PropertyKeyConst.REDO_DELAY_THREAD_COUNT, "2"); NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); - + NamingGrpcRedoService redoService = new NamingGrpcRedoService(clientProxy, nacosClientProperties); - + Field redoThreadCountField = NamingGrpcRedoService.class.getDeclaredField("redoThreadCount"); redoThreadCountField.setAccessible(true); - + Field redoDelayTimeField = NamingGrpcRedoService.class.getDeclaredField("redoDelayTime"); redoDelayTimeField.setAccessible(true); - + Long redoDelayTimeValue = (Long) redoDelayTimeField.get(redoService); Integer redoThreadCountValue = (Integer) redoThreadCountField.get(redoService); assertEquals(Long.valueOf(4000L), redoDelayTimeValue); assertEquals(Integer.valueOf(2), redoThreadCountValue); } - + @Test - public void testOnConnected() { + void testOnConnected() { assertFalse(redoService.isConnected()); redoService.onConnected(new TestConnection(new RpcClient.ServerInfo())); assertTrue(redoService.isConnected()); } @Test - public void testOnDisConnect() { + void testOnDisConnect() { redoService.onConnected(new TestConnection(new RpcClient.ServerInfo())); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceRegistered(SERVICE, GROUP); @@ -133,7 +133,7 @@ public void testOnDisConnect() { } @Test - public void testCacheInstanceForRedo() { + void testCacheInstanceForRedo() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); Instance instance = new Instance(); @@ -149,7 +149,7 @@ public void testCacheInstanceForRedo() { } @Test - public void testCacheInstanceForRedoByBatchInstanceRedoData() { + void testCacheInstanceForRedoByBatchInstanceRedoData() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); Instance instance = new Instance(); @@ -167,7 +167,7 @@ public void testCacheInstanceForRedoByBatchInstanceRedoData() { } @Test - public void testInstanceRegistered() { + void testInstanceRegistered() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceRegistered(SERVICE, GROUP); @@ -176,7 +176,7 @@ public void testInstanceRegistered() { } @Test - public void testInstanceDeregister() { + void testInstanceDeregister() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceDeregister(SERVICE, GROUP); @@ -186,7 +186,7 @@ public void testInstanceDeregister() { } @Test - public void testInstanceDeregistered() { + void testInstanceDeregistered() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceDeregistered(SERVICE, GROUP); @@ -196,7 +196,7 @@ public void testInstanceDeregistered() { } @Test - public void testRemoveInstanceForRedo() { + void testRemoveInstanceForRedo() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); @@ -207,7 +207,7 @@ public void testRemoveInstanceForRedo() { } @Test - public void testFindInstanceRedoData() { + void testFindInstanceRedoData() { redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); assertFalse(redoService.findInstanceRedoData().isEmpty()); redoService.instanceRegistered(SERVICE, GROUP); @@ -222,7 +222,7 @@ private ConcurrentMap getInstanceRedoDataMap() { } @Test - public void testCacheSubscriberForRedo() { + void testCacheSubscriberForRedo() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); assertTrue(subscribes.isEmpty()); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); @@ -236,7 +236,7 @@ public void testCacheSubscriberForRedo() { } @Test - public void testSubscriberRegistered() { + void testSubscriberRegistered() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); @@ -245,7 +245,7 @@ public void testSubscriberRegistered() { } @Test - public void testSubscriberDeregister() { + void testSubscriberDeregister() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberDeregister(SERVICE, GROUP, CLUSTER); @@ -254,7 +254,7 @@ public void testSubscriberDeregister() { } @Test - public void testIsSubscriberRegistered() { + void testIsSubscriberRegistered() { assertFalse(redoService.isSubscriberRegistered(SERVICE, GROUP, CLUSTER)); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); @@ -262,7 +262,7 @@ public void testIsSubscriberRegistered() { } @Test - public void testRemoveSubscriberForRedo() { + void testRemoveSubscriberForRedo() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); assertTrue(subscribes.isEmpty()); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); @@ -273,7 +273,7 @@ public void testRemoveSubscriberForRedo() { } @Test - public void testFindSubscriberRedoData() { + void testFindSubscriberRedoData() { redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); assertFalse(redoService.findSubscriberRedoData().isEmpty()); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java index 2df4d75207c..de86b8bd5db 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java @@ -22,11 +22,13 @@ import com.alibaba.nacos.client.naming.remote.gprc.redo.data.BatchInstanceRedoData; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.InstanceRedoData; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.SubscriberRedoData; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.util.Collections; import java.util.HashSet; @@ -37,8 +39,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class RedoScheduledTaskTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class RedoScheduledTaskTest { private static final String SERVICE = "service"; @@ -56,15 +60,15 @@ public class RedoScheduledTaskTest { private RedoScheduledTask redoTask; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { redoTask = new RedoScheduledTask(clientProxy, redoService); when(clientProxy.isEnable()).thenReturn(true); when(redoService.isConnected()).thenReturn(true); } @Test - public void testRunRedoRegisterInstance() throws NacosException { + void testRunRedoRegisterInstance() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); @@ -72,9 +76,9 @@ public void testRunRedoRegisterInstance() throws NacosException { } @Test - public void testRunRedoRegisterBatchInstance() throws NacosException { - BatchInstanceRedoData redoData = BatchInstanceRedoData - .build(SERVICE, GROUP, Collections.singletonList(INSTANCE)); + void testRunRedoRegisterBatchInstance() throws NacosException { + BatchInstanceRedoData redoData = BatchInstanceRedoData.build(SERVICE, GROUP, + Collections.singletonList(INSTANCE)); redoData.setRegistered(false); redoData.setUnregistering(false); redoData.setExpectedRegistered(true); @@ -86,7 +90,7 @@ public void testRunRedoRegisterBatchInstance() throws NacosException { } @Test - public void testRunRedoDeregisterInstance() throws NacosException { + void testRunRedoDeregisterInstance() throws NacosException { Set mockData = generateMockInstanceData(true, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); @@ -94,7 +98,7 @@ public void testRunRedoDeregisterInstance() throws NacosException { } @Test - public void testRunRedoRemoveInstanceRedoData() throws NacosException { + void testRunRedoRemoveInstanceRedoData() throws NacosException { Set mockData = generateMockInstanceData(false, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); @@ -102,7 +106,7 @@ public void testRunRedoRemoveInstanceRedoData() throws NacosException { } @Test - public void testRunRedoRegisterInstanceWithClientDisabled() throws NacosException { + void testRunRedoRegisterInstanceWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set mockData = generateMockInstanceData(false, false, true); when(redoService.findInstanceRedoData()).thenReturn(mockData); @@ -111,7 +115,7 @@ public void testRunRedoRegisterInstanceWithClientDisabled() throws NacosExceptio } @Test - public void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosException { + void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set mockData = generateMockInstanceData(true, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); @@ -120,7 +124,7 @@ public void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosExcept } @Test - public void testRunRedoRegisterInstanceWithNacosException() throws NacosException { + void testRunRedoRegisterInstanceWithNacosException() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); when(redoService.findInstanceRedoData()).thenReturn(mockData); doThrow(new NacosException()).when(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE); @@ -129,7 +133,7 @@ public void testRunRedoRegisterInstanceWithNacosException() throws NacosExceptio } @Test - public void testRunRedoRegisterInstanceWithOtherException() throws NacosException { + void testRunRedoRegisterInstanceWithOtherException() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); when(redoService.findInstanceRedoData()).thenReturn(mockData); doThrow(new RuntimeException("test")).when(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE); @@ -149,7 +153,7 @@ private Set generateMockInstanceData(boolean registered, boole } @Test - public void testRunRedoRegisterSubscriber() throws NacosException { + void testRunRedoRegisterSubscriber() throws NacosException { Set mockData = generateMockSubscriberData(false, false, true); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); @@ -157,7 +161,7 @@ public void testRunRedoRegisterSubscriber() throws NacosException { } @Test - public void testRunRedoDeregisterSubscriber() throws NacosException { + void testRunRedoDeregisterSubscriber() throws NacosException { Set mockData = generateMockSubscriberData(true, true, false); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); @@ -165,7 +169,7 @@ public void testRunRedoDeregisterSubscriber() throws NacosException { } @Test - public void testRunRedoRemoveSubscriberRedoData() throws NacosException { + void testRunRedoRemoveSubscriberRedoData() throws NacosException { Set mockData = generateMockSubscriberData(false, true, false); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); @@ -173,7 +177,7 @@ public void testRunRedoRemoveSubscriberRedoData() throws NacosException { } @Test - public void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosException { + void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set mockData = generateMockSubscriberData(false, false, true); when(redoService.findSubscriberRedoData()).thenReturn(mockData); @@ -182,7 +186,7 @@ public void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosExcept } @Test - public void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosException { + void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set mockData = generateMockSubscriberData(true, true, false); when(redoService.findSubscriberRedoData()).thenReturn(mockData); @@ -191,7 +195,7 @@ public void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosExce } @Test - public void testRunRedoRegisterSubscriberWithNacosException() throws NacosException { + void testRunRedoRegisterSubscriberWithNacosException() throws NacosException { Set mockData = generateMockSubscriberData(false, false, true); when(redoService.findSubscriberRedoData()).thenReturn(mockData); doThrow(new NacosException()).when(clientProxy).doSubscribe(SERVICE, GROUP, CLUSTER); @@ -211,7 +215,7 @@ private Set generateMockSubscriberData(boolean registered, b } @Test - public void testRunRedoWithDisconnection() { + void testRunRedoWithDisconnection() { when(redoService.isConnected()).thenReturn(false); redoTask.run(); verify(redoService, never()).findInstanceRedoData(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java index e9f033e1031..2dee36e902a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java @@ -17,36 +17,34 @@ package com.alibaba.nacos.client.naming.remote.gprc.redo.data; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -public class BatchInstanceRedoDataTest { +class BatchInstanceRedoDataTest { @Test @SuppressWarnings("all") - public void testEquals() { + void testEquals() { BatchInstanceRedoData redoData1 = new BatchInstanceRedoData("a", "b"); redoData1.setInstances(Collections.singletonList(new Instance())); BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b"); redoData2.setInstances(Collections.singletonList(new Instance())); - assertTrue(redoData1.equals(redoData1)); - assertTrue(redoData1.equals(redoData2)); + assertEquals(redoData1, redoData1); + assertEquals(redoData1, redoData2); redoData2.getInstances().get(0).setIp("1.1.1.1"); - assertFalse(redoData1.equals(null)); - assertFalse(redoData1.equals(redoData2)); - assertFalse(redoData1.equals(redoData2)); + assertNotEquals(null, redoData1); + assertNotEquals(redoData1, redoData2); + assertNotEquals(redoData1, redoData2); BatchInstanceRedoData redoData3 = new BatchInstanceRedoData("c", "b"); - assertFalse(redoData1.equals(redoData3)); + assertNotEquals(redoData1, redoData3); } @Test - public void testHashCode() { + void testHashCode() { BatchInstanceRedoData redoData1 = new BatchInstanceRedoData("a", "b"); redoData1.setInstances(Collections.singletonList(new Instance())); BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java index ddbc79b05c4..46b2d070218 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java @@ -17,28 +17,26 @@ package com.alibaba.nacos.client.naming.remote.gprc.redo.data; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -public class InstanceRedoDataTest { +class InstanceRedoDataTest { @Test - public void testEquals() { + void testEquals() { InstanceRedoData redoData1 = new InstanceRedoData("a", "b"); - assertTrue(redoData1.equals(redoData1)); - assertFalse(redoData1.equals(null)); + assertEquals(redoData1, redoData1); + assertNotEquals(null, redoData1); BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b"); - assertFalse(redoData1.equals(redoData2)); + assertNotEquals(redoData1, redoData2); InstanceRedoData redoData3 = new InstanceRedoData("a", "b"); - assertTrue(redoData1.equals(redoData3)); + assertEquals(redoData1, redoData3); } @Test - public void testHashCode() { + void testHashCode() { InstanceRedoData redoData1 = new InstanceRedoData("a", "b"); redoData1.set(new Instance()); InstanceRedoData redoData2 = new InstanceRedoData("a", "b"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java index ac318b86a99..5b4a44bdc2c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java @@ -22,8 +22,7 @@ import com.alibaba.nacos.common.http.HttpClientBeanHolder; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.client.request.HttpClientRequest; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; @@ -31,31 +30,32 @@ import java.util.Map; import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTP_PREFIX; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class NamingHttpClientManagerTest { +class NamingHttpClientManagerTest { @Test - public void testGetInstance() { - Assert.assertNotNull(NamingHttpClientManager.getInstance()); + void testGetInstance() { + assertNotNull(NamingHttpClientManager.getInstance()); } @Test - public void testGetPrefix() { + void testGetPrefix() { assertEquals(HTTP_PREFIX, NamingHttpClientManager.getInstance().getPrefix()); } @Test - public void testGetNacosRestTemplate() { - Assert.assertNotNull(NamingHttpClientManager.getInstance().getNacosRestTemplate()); + void testGetNacosRestTemplate() { + assertNotNull(NamingHttpClientManager.getInstance().getNacosRestTemplate()); } @Test - public void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosException, IOException { + void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosException, IOException { //given NamingHttpClientManager instance = NamingHttpClientManager.getInstance(); @@ -70,7 +70,7 @@ public void testShutdown() throws NoSuchFieldException, IllegalAccessException, } @Test - public void testShutdownWithException() throws Exception { + void testShutdownWithException() throws Exception { String key = "com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory"; try { HttpClientBeanHolder.shutdownNacosSyncRest(key); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java index 3ffcc78f423..28e09582226 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java @@ -34,15 +34,14 @@ import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.utils.HttpMethod; import com.alibaba.nacos.common.utils.ReflectUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.lang.reflect.Field; import java.util.Arrays; @@ -52,9 +51,11 @@ import java.util.Map; import java.util.Properties; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.endsWith; import static org.mockito.ArgumentMatchers.eq; @@ -64,11 +65,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamingHttpClientProxyTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class NamingHttpClientProxyTest { @Mock private SecurityProxy proxy; @@ -80,33 +80,33 @@ public class NamingHttpClientProxyTest { private NamingHttpClientProxy clientProxy; - @Before - public void setUp() { + @BeforeEach + void setUp() { when(mgr.getServerList()).thenReturn(Arrays.asList("localhost")); props = new Properties(); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props); clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, nacosClientProperties); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { clientProxy.shutdown(); System.clearProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT); } @Test - public void testOnEvent() { + void testOnEvent() { clientProxy.onEvent(new ServerListChangedEvent()); // Do nothing } @Test - public void testSubscribeType() { + void testSubscribeType() { assertEquals(ServerListChangedEvent.class, clientProxy.subscribeType()); } @Test - public void testRegisterService() throws Exception { + void testRegisterService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -128,81 +128,88 @@ public void testRegisterService() throws Exception { verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), any(), any()); } - @Test(expected = UnsupportedOperationException.class) - public void testRegisterEphemeralInstance() throws NacosException { - Instance instance = new Instance(); - clientProxy.registerService("a", "b", instance); + @Test + void testRegisterEphemeralInstance() throws NacosException { + assertThrows(UnsupportedOperationException.class, () -> { + Instance instance = new Instance(); + clientProxy.registerService("a", "b", instance); + }); } @Test - public void testRegisterServiceThrowsNacosException() throws Exception { - thrown.expect(NacosException.class); - thrown.expectMessage("failed to req API"); - - NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - HttpRestResult a = new HttpRestResult(); - a.setCode(503); - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a); - - final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); - nacosRestTemplateField.setAccessible(true); - nacosRestTemplateField.set(clientProxy, nacosRestTemplate); - String serviceName = "service1"; - String groupName = "group1"; - Instance instance = new Instance(); - instance.setEphemeral(false); - try { - clientProxy.registerService(serviceName, groupName, instance); - } catch (NacosException ex) { - // verify the `NacosException` is directly thrown - assertEquals(null, ex.getCause()); + void testRegisterServiceThrowsNacosException() throws Exception { + Throwable exception = assertThrows(NacosException.class, () -> { + + NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); + HttpRestResult a = new HttpRestResult(); + a.setCode(503); + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a); - throw ex; - } + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); + nacosRestTemplateField.setAccessible(true); + nacosRestTemplateField.set(clientProxy, nacosRestTemplate); + String serviceName = "service1"; + String groupName = "group1"; + Instance instance = new Instance(); + instance.setEphemeral(false); + try { + clientProxy.registerService(serviceName, groupName, instance); + } catch (NacosException ex) { + // verify the `NacosException` is directly thrown + assertNull(ex.getCause()); + + throw ex; + } + }); + assertTrue(exception.getMessage().contains("failed to req API")); } @Test - public void testRegisterServiceThrowsException() throws Exception { - // assert throw NacosException - thrown.expect(NacosException.class); - - NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - HttpRestResult a = new HttpRestResult(); - a.setCode(503); - // makes exchangeForm failed with a NullPointerException - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(null); - - final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); - nacosRestTemplateField.setAccessible(true); - nacosRestTemplateField.set(clientProxy, nacosRestTemplate); - String serviceName = "service1"; - String groupName = "group1"; - Instance instance = new Instance(); - instance.setEphemeral(false); - - try { - clientProxy.registerService(serviceName, groupName, instance); - } catch (NacosException ex) { - // verify the `NacosException` is directly thrown - Assert.assertTrue(ex.getErrMsg().contains("java.lang.NullPointerException")); - assertEquals(NacosException.SERVER_ERROR, ex.getErrCode()); + void testRegisterServiceThrowsException() throws Exception { + assertThrows(NacosException.class, () -> { + + NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); + HttpRestResult a = new HttpRestResult(); + a.setCode(503); + // makes exchangeForm failed with a NullPointerException + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(null); + + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); + nacosRestTemplateField.setAccessible(true); + nacosRestTemplateField.set(clientProxy, nacosRestTemplate); + String serviceName = "service1"; + String groupName = "group1"; + Instance instance = new Instance(); + instance.setEphemeral(false); - throw ex; - } + try { + clientProxy.registerService(serviceName, groupName, instance); + } catch (NacosException ex) { + // verify the `NacosException` is directly thrown + assertTrue(ex.getErrMsg().contains("java.lang.NullPointerException")); + assertEquals(NacosException.SERVER_ERROR, ex.getErrCode()); + + throw ex; + } + }); } - @Test(expected = UnsupportedOperationException.class) - public void testBatchRegisterService() { - clientProxy.batchRegisterService("a", "b", null); + @Test + void testBatchRegisterService() { + assertThrows(UnsupportedOperationException.class, () -> { + clientProxy.batchRegisterService("a", "b", null); + }); } - @Test(expected = UnsupportedOperationException.class) - public void testBatchDeregisterService() { - clientProxy.batchDeregisterService("a", "b", null); + @Test + void testBatchDeregisterService() { + assertThrows(UnsupportedOperationException.class, () -> { + clientProxy.batchDeregisterService("a", "b", null); + }); } @Test - public void testDeregisterService() throws Exception { + void testDeregisterService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -225,7 +232,7 @@ public void testDeregisterService() throws Exception { } @Test - public void testDeregisterServiceForEphemeral() throws Exception { + void testDeregisterServiceForEphemeral() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); nacosRestTemplateField.setAccessible(true); @@ -237,7 +244,7 @@ public void testDeregisterServiceForEphemeral() throws Exception { } @Test - public void testUpdateInstance() throws Exception { + void testUpdateInstance() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -259,17 +266,17 @@ public void testUpdateInstance() throws Exception { } @Test - public void testQueryInstancesOfServiceThrowsException() { + void testQueryInstancesOfServiceThrowsException() { //assert exception String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; - Assert.assertThrows(UnsupportedOperationException.class, + assertThrows(UnsupportedOperationException.class, () -> clientProxy.queryInstancesOfService(serviceName, groupName, clusters, false)); } @Test - public void testQueryService() throws Exception { + void testQueryService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -287,14 +294,14 @@ public void testQueryService() throws Exception { //when Service service = clientProxy.queryService(serviceName, groupName); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.GET), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), + eq(HttpMethod.GET), any()); assertEquals(serviceName, service.getName()); assertEquals(groupName, service.getGroupName()); } @Test - public void testCreateService() throws Exception { + void testCreateService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -309,12 +316,12 @@ public void testCreateService() throws Exception { //when clientProxy.createService(new Service(), new NoneSelector()); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.POST), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), + eq(HttpMethod.POST), any()); } @Test - public void testDeleteService() throws Exception { + void testDeleteService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -331,12 +338,12 @@ public void testDeleteService() throws Exception { //when clientProxy.deleteService(serviceName, groupName); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.DELETE), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), + eq(HttpMethod.DELETE), any()); } @Test - public void testUpdateService() throws Exception { + void testUpdateService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -353,13 +360,13 @@ public void testUpdateService() throws Exception { //when clientProxy.updateService(new Service(), new NoneSelector()); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.PUT), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), + eq(HttpMethod.PUT), any()); } @Test - public void testServerHealthy() throws Exception { + void testServerHealthy() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -374,16 +381,16 @@ public void testServerHealthy() throws Exception { //when boolean serverHealthy = clientProxy.serverHealthy(); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith("/operator/metrics"), any(), any(), any(), eq(HttpMethod.GET), any()); - Assert.assertTrue(serverHealthy); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/operator/metrics"), any(), any(), any(), + eq(HttpMethod.GET), any()); + assertTrue(serverHealthy); } @Test - public void testServerHealthyForException() throws Exception { + void testServerHealthyForException() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())) - .thenThrow(new RuntimeException("test")); + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenThrow( + new RuntimeException("test")); final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); nacosRestTemplateField.setAccessible(true); nacosRestTemplateField.set(clientProxy, nacosRestTemplate); @@ -391,7 +398,7 @@ public void testServerHealthyForException() throws Exception { } @Test - public void testGetServiceList() throws Exception { + void testGetServiceList() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -407,15 +414,15 @@ public void testGetServiceList() throws Exception { //when ListView serviceList = clientProxy.getServiceList(1, 10, groupName, new NoneSelector()); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith("/service/list"), any(), any(), any(), eq(HttpMethod.GET), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/service/list"), any(), any(), any(), + eq(HttpMethod.GET), any()); assertEquals(2, serviceList.getCount()); assertEquals("aaa", serviceList.getData().get(0)); assertEquals("bbb", serviceList.getData().get(1)); } @Test - public void testGetServiceListWithLabelSelector() throws Exception { + void testGetServiceListWithLabelSelector() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -431,25 +438,27 @@ public void testGetServiceListWithLabelSelector() throws Exception { //when ListView serviceList = clientProxy.getServiceList(1, 10, groupName, new ExpressionSelector()); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith("/service/list"), any(), any(), any(), eq(HttpMethod.GET), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/service/list"), any(), any(), any(), + eq(HttpMethod.GET), any()); assertEquals(2, serviceList.getCount()); assertEquals("aaa", serviceList.getData().get(0)); assertEquals("bbb", serviceList.getData().get(1)); } - @Test(expected = UnsupportedOperationException.class) - public void testSubscribe() throws Exception { - String groupName = "group1"; - String serviceName = "serviceName"; - String clusters = "clusters"; - - //when - clientProxy.subscribe(serviceName, groupName, clusters); + @Test + void testSubscribe() throws Exception { + assertThrows(UnsupportedOperationException.class, () -> { + String groupName = "group1"; + String serviceName = "serviceName"; + String clusters = "clusters"; + + //when + clientProxy.subscribe(serviceName, groupName, clusters); + }); } @Test - public void testUnsubscribe() throws Exception { + void testUnsubscribe() throws Exception { String groupName = "group1"; String serviceName = "serviceName"; String clusters = "clusters"; @@ -460,12 +469,12 @@ public void testUnsubscribe() throws Exception { } @Test - public void testIsSubscribed() throws NacosException { + void testIsSubscribed() throws NacosException { assertTrue(clientProxy.isSubscribed("serviceName", "group1", "clusters")); } @Test - public void testReqApi() throws Exception { + void testReqApi() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -491,7 +500,7 @@ public void testReqApi() throws Exception { } @Test - public void testReqApi2() throws Exception { + void testReqApi2() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -517,7 +526,7 @@ public void testReqApi2() throws Exception { } @Test - public void testReqApi3() throws Exception { + void testReqApi3() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -544,36 +553,38 @@ public void testReqApi3() throws Exception { } @Test - public void testCallServerFail() throws Exception { - //then - thrown.expect(NacosException.class); - - //given - NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenAnswer(invocationOnMock -> { - //return url - HttpRestResult res = new HttpRestResult(); - res.setMessage("fail"); - res.setCode(400); - return res; + void testCallServerFail() throws Exception { + assertThrows(NacosException.class, () -> { + + //given + NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); + + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenAnswer( + invocationOnMock -> { + //return url + HttpRestResult res = new HttpRestResult(); + res.setMessage("fail"); + res.setCode(400); + return res; + }); + + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); + nacosRestTemplateField.setAccessible(true); + nacosRestTemplateField.set(clientProxy, nacosRestTemplate); + String api = "/api"; + Map params = new HashMap<>(); + Map body = new HashMap<>(); + String method = HttpMethod.GET; + String curServer = "127.0.0.1"; + //when + clientProxy.callServer(api, params, body, curServer, method); + }); - final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); - nacosRestTemplateField.setAccessible(true); - nacosRestTemplateField.set(clientProxy, nacosRestTemplate); - String api = "/api"; - Map params = new HashMap<>(); - Map body = new HashMap<>(); - String method = HttpMethod.GET; - String curServer = "127.0.0.1"; - //when - clientProxy.callServer(api, params, body, curServer, method); - } @Test - public void testCallServerFail304() throws Exception { + void testCallServerFail304() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -600,7 +611,7 @@ public void testCallServerFail304() throws Exception { } @Test - public void testGetNamespaceId() { + void testGetNamespaceId() { String namespaceId = "aaa"; final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props); NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, nacosClientProperties); @@ -609,7 +620,7 @@ public void testGetNamespaceId() { } @Test - public void testSetServerPort() { + void testSetServerPort() { clientProxy.setServerPort(1234); assertEquals(1234, ReflectUtils.getFieldValue(clientProxy, "serverPort")); System.setProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT, "1111"); @@ -617,20 +628,23 @@ public void testSetServerPort() { assertEquals(1111, ReflectUtils.getFieldValue(clientProxy, "serverPort")); } - @Test(expected = NacosException.class) - public void testReqApiForEmptyServer() throws NacosException { - Map params = new HashMap<>(); - clientProxy - .reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + @Test + void testReqApiForEmptyServer() throws NacosException { + assertThrows(NacosException.class, () -> { + Map params = new HashMap<>(); + clientProxy.reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + }); } - @Test(expected = NacosException.class) - public void testRegApiForDomain() throws NacosException { - Map params = new HashMap<>(); - when(mgr.isDomain()).thenReturn(true); - when(mgr.getNacosDomain()).thenReturn("http://test.nacos.domain"); - clientProxy - .reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + @Test + void testRegApiForDomain() throws NacosException { + assertThrows(NacosException.class, () -> { + Map params = new HashMap<>(); + when(mgr.isDomain()).thenReturn(true); + when(mgr.getNacosDomain()).thenReturn("http://test.nacos.domain"); + clientProxy.reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java index 32a8599037c..5abbc54a57c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java @@ -18,28 +18,28 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CacheDirUtilTest { +class CacheDirUtilTest { - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { System.clearProperty("user.home"); System.clearProperty("JM.SNAPSHOT.PATH"); } @Test - public void testInitCacheDirWithDefaultRootAndWithoutCache() { + void testInitCacheDirWithDefaultRootAndWithoutCache() { System.setProperty("user.home", "/home/admin"); String actual = CacheDirUtil.initCacheDir("test", NacosClientProperties.PROTOTYPE.derive()); assertEquals("/home/admin/nacos/naming/test", actual); } @Test - public void testInitCacheDirWithDefaultRootAndWithCache() { + void testInitCacheDirWithDefaultRootAndWithCache() { System.setProperty("user.home", "/home/admin"); NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "custom"); @@ -48,14 +48,14 @@ public void testInitCacheDirWithDefaultRootAndWithCache() { } @Test - public void testInitCacheDirWithJmSnapshotPathRootAndWithoutCache() { + void testInitCacheDirWithJmSnapshotPathRootAndWithoutCache() { System.setProperty("JM.SNAPSHOT.PATH", "/home/snapshot"); String actual = CacheDirUtil.initCacheDir("test", NacosClientProperties.PROTOTYPE.derive()); assertEquals("/home/snapshot/nacos/naming/test", actual); } @Test - public void testInitCacheDirWithJmSnapshotPathRootAndWithCache() { + void testInitCacheDirWithJmSnapshotPathRootAndWithCache() { System.setProperty("user.home", "/home/snapshot"); NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "custom"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java index 8f62917f88a..30b4e24a952 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.client.naming.utils; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; @@ -25,16 +25,17 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ChooserTest { +class ChooserTest { @Test - public void testChooser() { + void testChooser() { //Test the correctness of Chooser, the weight of the final selected instance must be greater than 0 List hosts = getInstanceList(); Instance target = getRandomInstance(hosts); @@ -42,14 +43,14 @@ public void testChooser() { } @Test - public void testChooserRandomForEmptyList() { + void testChooserRandomForEmptyList() { Chooser chooser = new Chooser<>("test"); assertEquals("test", chooser.getUniqueKey()); assertNull(chooser.random()); } @Test - public void testChooserRandomForOneSizeList() { + void testChooserRandomForOneSizeList() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); Chooser chooser = new Chooser<>("test", list); @@ -59,7 +60,7 @@ public void testChooserRandomForOneSizeList() { } @Test - public void testChooserRandom() { + void testChooserRandom() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); list.add(new Pair<>("test2", 1)); @@ -70,7 +71,7 @@ public void testChooserRandom() { } @Test - public void testOnlyOneInstanceWeightIsNotZero() { + void testOnlyOneInstanceWeightIsNotZero() { // If there is only one instance whose weight is not zero, it will be selected List hosts = getOneInstanceNotZeroList(); @@ -79,7 +80,7 @@ public void testOnlyOneInstanceWeightIsNotZero() { } @Test - public void testInstanceWeightAllZero() { + void testInstanceWeightAllZero() { // Throw an IllegalStateException when all instances have a weight of zero. List hosts = getInstanceWeightAllZero(); @@ -90,16 +91,18 @@ public void testInstanceWeightAllZero() { } } - @Test(expected = IllegalStateException.class) - public void testRandomWithWeightForNaNAndInfinity() { - List> list = new LinkedList<>(); - list.add(new Pair<>("test", Double.NaN)); - list.add(new Pair<>("test2", Double.POSITIVE_INFINITY)); - new Chooser<>("test", list); + @Test + void testRandomWithWeightForNaNAndInfinity() { + assertThrows(IllegalStateException.class, () -> { + List> list = new LinkedList<>(); + list.add(new Pair<>("test", Double.NaN)); + list.add(new Pair<>("test2", Double.POSITIVE_INFINITY)); + new Chooser<>("test", list); + }); } @Test - public void testRefresh() { + void testRefresh() { Chooser chooser = new Chooser<>("test"); assertEquals("test", chooser.getUniqueKey()); assertNull(chooser.random()); @@ -112,43 +115,43 @@ public void testRefresh() { } @Test - public void testEqualsHashCode() { + void testEqualsHashCode() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); list.add(new Pair<>("test2", 1)); Chooser chooser = new Chooser<>("test", list); assertEquals("test".hashCode(), chooser.hashCode()); - assertTrue(chooser.equals(chooser)); - assertFalse(chooser.equals(null)); - assertFalse(chooser.equals("test")); + assertEquals(chooser, chooser); + assertNotEquals(null, chooser); + assertNotEquals("test", chooser); Chooser chooser1 = new Chooser<>(null, null); - assertFalse(chooser.equals(chooser1)); - assertFalse(chooser1.equals(chooser)); + assertNotEquals(chooser, chooser1); + assertNotEquals(chooser1, chooser); Chooser chooser2 = new Chooser<>("test", Collections.emptyList()); - assertFalse(chooser.equals(chooser2)); - assertFalse(chooser2.equals(chooser)); + assertNotEquals(chooser, chooser2); + assertNotEquals(chooser2, chooser); Chooser chooser3 = new Chooser<>("test1", list); - assertFalse(chooser.equals(chooser3)); + assertNotEquals(chooser, chooser3); Chooser chooser4 = new Chooser<>("test", list); - assertTrue(chooser.equals(chooser4)); + assertEquals(chooser, chooser4); } @Test - public void testRefEqualsHashCode() { + void testRefEqualsHashCode() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); list.add(new Pair<>("test2", 1)); Chooser chooser = new Chooser<>("test", list); Chooser.Ref ref = chooser.getRef(); assertEquals(list.hashCode(), ref.hashCode()); - assertTrue(ref.equals(ref)); - assertFalse(ref.equals(null)); - assertFalse(ref.equals(chooser)); + assertEquals(ref, ref); + assertNotEquals(null, ref); + assertNotEquals(ref, chooser); Chooser.Ref ref1 = new Chooser<>("test", null).getRef(); - assertFalse(ref.equals(ref1)); - assertFalse(ref1.equals(ref)); + assertNotEquals(ref, ref1); + assertNotEquals(ref1, ref); Chooser.Ref ref2 = new Chooser<>("test", list).getRef(); - assertTrue(ref.equals(ref2)); + assertEquals(ref, ref2); } private List getInstanceList() { diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java index fdcb20993d9..433c4cb5d8a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java @@ -16,53 +16,56 @@ package com.alibaba.nacos.client.naming.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; -public class CollectionUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CollectionUtilsTest { @Test - public void testSubtract() { - List subtract = (List) CollectionUtils - .subtract(Arrays.asList("a", "b"), Arrays.asList("b", "c")); - Assert.assertEquals(1, subtract.size()); - Assert.assertEquals("a", subtract.get(0)); + void testSubtract() { + List subtract = (List) CollectionUtils.subtract(Arrays.asList("a", "b"), + Arrays.asList("b", "c")); + assertEquals(1, subtract.size()); + assertEquals("a", subtract.get(0)); } @Test - public void testGetCardinalityMap() { + void testGetCardinalityMap() { List list1 = Arrays.asList("2", "2", "3"); Map map1 = CollectionUtils.getCardinalityMap(list1); - Assert.assertEquals(2, map1.size()); - Assert.assertEquals(2, map1.get("2").intValue()); - Assert.assertEquals(1, map1.get("3").intValue()); + assertEquals(2, map1.size()); + assertEquals(2, map1.get("2").intValue()); + assertEquals(1, map1.get("3").intValue()); } @Test - public void testIsEqualCollection() { + void testIsEqualCollection() { List list1 = Arrays.asList("2", "2", "3"); List list2 = Arrays.asList("3", "2", "2"); List list3 = Arrays.asList("3", "2", "3"); List list4 = Arrays.asList("3", "2"); + assertTrue(CollectionUtils.isEqualCollection(list1, list2)); + assertFalse(CollectionUtils.isEqualCollection(list1, list3)); + assertFalse(CollectionUtils.isEqualCollection(list1, list4)); List list5 = Arrays.asList("3", "2", "1"); + assertFalse(CollectionUtils.isEqualCollection(list1, list5)); List list6 = Arrays.asList("2", "2", "1"); - Assert.assertTrue(CollectionUtils.isEqualCollection(list1, list2)); - Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list3)); - Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list4)); - Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list5)); - Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list6)); + assertFalse(CollectionUtils.isEqualCollection(list1, list6)); } @Test - public void testIsEmpty() { - Assert.assertTrue(CollectionUtils.isEmpty(null)); - Assert.assertTrue(CollectionUtils.isEmpty(new ArrayList())); - Assert.assertFalse(CollectionUtils.isEmpty(Arrays.asList("aa"))); + void testIsEmpty() { + assertTrue(CollectionUtils.isEmpty(null)); + assertTrue(CollectionUtils.isEmpty(new ArrayList())); + assertFalse(CollectionUtils.isEmpty(Arrays.asList("aa"))); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java index 545df8d0d5f..467f3146687 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java @@ -17,8 +17,7 @@ package com.alibaba.nacos.client.naming.utils; import com.alibaba.nacos.client.utils.ConcurrentDiskUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -28,76 +27,83 @@ import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ConcurrentDiskUtilTest { +class ConcurrentDiskUtilTest { @Test - public void testReadAndWrite() throws IOException { + void testReadAndWrite() throws IOException { File tempFile = File.createTempFile("aaa", "bbb"); String fileName = tempFile.getAbsolutePath(); String content = "hello"; String charset = "UTF-8"; ConcurrentDiskUtil.writeFileContent(fileName, content, charset); String actualContent = ConcurrentDiskUtil.getFileContent(fileName, charset); - Assert.assertEquals(content, actualContent); + assertEquals(content, actualContent); } @Test - public void testReadAndWrite2() throws IOException { + void testReadAndWrite2() throws IOException { File tempFile = File.createTempFile("aaa", "bbb"); String content = "hello"; String charset = "UTF-8"; ConcurrentDiskUtil.writeFileContent(tempFile, content, charset); String actualContent = ConcurrentDiskUtil.getFileContent(tempFile, charset); - Assert.assertEquals(content, actualContent); + assertEquals(content, actualContent); } @Test - public void testByteBufferToString() throws IOException { + void testByteBufferToString() throws IOException { String msg = "test buff to string"; ByteBuffer buff = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)); String actual = ConcurrentDiskUtil.byteBufferToString(buff, "UTF-8"); - Assert.assertEquals(msg, actual); + assertEquals(msg, actual); } @Test - public void testWriteFileContent() throws IOException { + void testWriteFileContent() throws IOException { File file = mock(File.class); - Assert.assertFalse(ConcurrentDiskUtil.writeFileContent(file, "hello", "UTF-8")); + assertFalse(ConcurrentDiskUtil.writeFileContent(file, "hello", "UTF-8")); } - @Test(expected = IOException.class) - public void testTryLockFailure() throws Throwable { - Method method = ConcurrentDiskUtil.class - .getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class); - method.setAccessible(true); - File file = new File("non-exist"); - FileChannel channel = mock(FileChannel.class); - when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException()); - try { - method.invoke(null, file, channel, true); - } catch (InvocationTargetException e) { - throw e.getCause(); - } + @Test + void testTryLockFailure() throws Throwable { + assertThrows(IOException.class, () -> { + Method method = ConcurrentDiskUtil.class.getDeclaredMethod("tryLock", File.class, FileChannel.class, + boolean.class); + method.setAccessible(true); + File file = new File("non-exist"); + FileChannel channel = mock(FileChannel.class); + when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException()); + try { + method.invoke(null, file, channel, true); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); } - @Test(expected = IOException.class) - public void testTryLockFailureForIntercept() throws Throwable { - Method method = ConcurrentDiskUtil.class - .getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class); - method.setAccessible(true); - File file = new File("non-exist"); - FileChannel channel = mock(FileChannel.class); - Thread.currentThread().interrupt(); - when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException()); - try { - method.invoke(null, file, channel, true); - } catch (InvocationTargetException e) { - throw e.getCause(); - } + @Test + void testTryLockFailureForIntercept() throws Throwable { + assertThrows(IOException.class, () -> { + Method method = ConcurrentDiskUtil.class.getDeclaredMethod("tryLock", File.class, FileChannel.class, + boolean.class); + method.setAccessible(true); + File file = new File("non-exist"); + FileChannel channel = mock(FileChannel.class); + Thread.currentThread().interrupt(); + when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException()); + try { + method.invoke(null, file, channel, true); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java index b081427fbfc..6a4d02ab9bf 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java @@ -16,29 +16,30 @@ package com.alibaba.nacos.client.naming.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; -public class GenericPollerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GenericPollerTest { @Test - public void testNext() { + void testNext() { String item1 = "item1"; String item2 = "item2"; GenericPoller poller = new GenericPoller<>(Arrays.asList(item1, item2)); - Assert.assertEquals(item1, poller.next()); - Assert.assertEquals(item2, poller.next()); - Assert.assertEquals(item1, poller.next()); + assertEquals(item1, poller.next()); + assertEquals(item2, poller.next()); + assertEquals(item1, poller.next()); } @Test - public void testRefresh() { + void testRefresh() { String item1 = "item1"; String item2 = "item2"; GenericPoller poller = new GenericPoller<>(Arrays.asList(item1, item2)); Poller poller1 = poller.refresh(Arrays.asList(item2)); - Assert.assertEquals(item2, poller1.next()); + assertEquals(item2, poller1.next()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java index b64cca489f0..e69d56df043 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java @@ -19,14 +19,15 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.SystemPropertyKeyConst; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -public class InitUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InitUtilsTest { - @After - public void tearDown() { + @AfterEach + void tearDown() { System.clearProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING); System.clearProperty(SystemPropertyKeyConst.ANS_NAMESPACE); System.clearProperty(PropertyKeyConst.NAMESPACE); @@ -42,125 +43,125 @@ public void tearDown() { * current namespace priority 1. system.Properties 2. user.Properties 3. default value */ @Test - public void testInitNamespaceForDefault() { + void testInitNamespaceForDefault() { //DEFAULT final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); + assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } @Test - public void testInitNamespaceFromAnsWithCloudParsing() { + void testInitNamespaceFromAnsWithCloudParsing() { String expect = "ans"; System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, expect); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true"); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } @Test - public void testInitNamespaceFromAliwareWithCloudParsing() { + void testInitNamespaceFromAliwareWithCloudParsing() { String expect = "aliware"; System.setProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE, expect); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } @Test - public void testInitNamespaceFromJvmNamespaceWithCloudParsing() { + void testInitNamespaceFromJvmNamespaceWithCloudParsing() { String expect = "jvm_namespace"; System.setProperty(PropertyKeyConst.NAMESPACE, expect); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String ns = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, ns); + assertEquals(expect, ns); } @Test - public void testInitNamespaceFromPropNamespaceWithCloudParsing() { + void testInitNamespaceFromPropNamespaceWithCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String expect = "ns1"; properties.setProperty(PropertyKeyConst.NAMESPACE, expect); String ns = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, ns); + assertEquals(expect, ns); } @Test - public void testInitNamespaceFromDefaultNamespaceWithCloudParsing() { + void testInitNamespaceFromDefaultNamespaceWithCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true"); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); + assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } @Test - public void testInitNamespaceFromJvmNamespaceWithoutCloudParsing() { + void testInitNamespaceFromJvmNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); String expect = "jvm_namespace"; System.setProperty(PropertyKeyConst.NAMESPACE, expect); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "false"); String ns = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, ns); + assertEquals(expect, ns); } @Test - public void testInitNamespaceFromPropNamespaceWithoutCloudParsing() { + void testInitNamespaceFromPropNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); System.setProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "false"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String expect = "ns1"; properties.setProperty(PropertyKeyConst.NAMESPACE, expect); String ns = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, ns); + assertEquals(expect, ns); } @Test - public void testInitNamespaceFromDefaultNamespaceWithoutCloudParsing() { + void testInitNamespaceFromDefaultNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "false"); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); + assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } @Test - public void testInitWebRootContext() { + void testInitWebRootContext() { String ctx = "/aaa"; final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.CONTEXT_PATH, ctx); InitUtils.initWebRootContext(properties); - Assert.assertEquals(ctx, UtilAndComs.webContext); - Assert.assertEquals(ctx + "/v1/ns", UtilAndComs.nacosUrlBase); - Assert.assertEquals(ctx + "/v1/ns/instance", UtilAndComs.nacosUrlInstance); + assertEquals(ctx, UtilAndComs.webContext); + assertEquals(ctx + "/v1/ns", UtilAndComs.nacosUrlBase); + assertEquals(ctx + "/v1/ns/instance", UtilAndComs.nacosUrlInstance); } @Test - public void testInitWebRootContextWithoutValue() { + void testInitWebRootContextWithoutValue() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); InitUtils.initWebRootContext(properties); - Assert.assertEquals("/nacos", UtilAndComs.webContext); - Assert.assertEquals("/nacos/v1/ns", UtilAndComs.nacosUrlBase); - Assert.assertEquals("/nacos/v1/ns/instance", UtilAndComs.nacosUrlInstance); + assertEquals("/nacos", UtilAndComs.webContext); + assertEquals("/nacos/v1/ns", UtilAndComs.nacosUrlBase); + assertEquals("/nacos/v1/ns/instance", UtilAndComs.nacosUrlInstance); } @Test - public void testInitEndpointForNullProperties() { - Assert.assertEquals("", InitUtils.initEndpoint(null)); + void testInitEndpointForNullProperties() { + assertEquals("", InitUtils.initEndpoint(null)); } @Test - public void testInitEndpointFromDefaultWithoutCloudParsing() { + void testInitEndpointFromDefaultWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "false"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals("", actual); + assertEquals("", actual); } @Test - public void testInitEndpointFromPropertiesWithoutCloudParsing() { + void testInitEndpointFromPropertiesWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "false"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String endpoint = "1.1.1.1"; @@ -168,11 +169,11 @@ public void testInitEndpointFromPropertiesWithoutCloudParsing() { properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals(endpoint + ":" + endpointPort, actual); + assertEquals(endpoint + ":" + endpointPort, actual); } @Test - public void testInitEndpointFromAliwareWithoutCloudParsing() { + void testInitEndpointFromAliwareWithoutCloudParsing() { String endpoint = "aliware_endpoint"; String endpointPort = "1234"; System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "false"); @@ -181,19 +182,19 @@ public void testInitEndpointFromAliwareWithoutCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort + "1"); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals("", actual); + assertEquals("", actual); } @Test - public void testInitEndpointFromDefaultWithCloudParsing() { + void testInitEndpointFromDefaultWithCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals("", actual); + assertEquals("", actual); } @Test - public void testInitEndpointFromPropertiesWithCloudParsing() { + void testInitEndpointFromPropertiesWithCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String endpoint = "1.1.1.1"; @@ -201,11 +202,11 @@ public void testInitEndpointFromPropertiesWithCloudParsing() { properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals(endpoint + ":" + endpointPort, actual); + assertEquals(endpoint + ":" + endpointPort, actual); } @Test - public void testInitEndpointFromAliwareWithCloudParsing() { + void testInitEndpointFromAliwareWithCloudParsing() { String endpoint = "aliware_endpoint"; String endpointPort = "1234"; System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); @@ -214,11 +215,11 @@ public void testInitEndpointFromAliwareWithCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort + "1"); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals(endpoint + ":" + endpointPort, actual); + assertEquals(endpoint + ":" + endpointPort, actual); } @Test - public void testInitEndpointAns() { + void testInitEndpointAns() { try { System.setProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); @@ -226,7 +227,7 @@ public void testInitEndpointAns() { properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); String actual = InitUtils.initEndpoint(properties); //defaultEndpointPort is "8080"; - Assert.assertEquals("test.com:8080", actual); + assertEquals("test.com:8080", actual); } finally { System.clearProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE); } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java index eda626ba41b..c28d634a04f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java @@ -19,20 +19,22 @@ import com.alibaba.nacos.common.constant.HttpHeaderConsts; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.utils.VersionUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class NamingHttpUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class NamingHttpUtilTest { @Test - public void testBuilderHeader() { + void testBuilderHeader() { Header header = NamingHttpUtil.builderHeader(); - Assert.assertNotNull(header); - Assert.assertEquals(header.getValue(HttpHeaderConsts.CLIENT_VERSION_HEADER), VersionUtils.version); - Assert.assertEquals(header.getValue(HttpHeaderConsts.USER_AGENT_HEADER), VersionUtils.getFullClientVersion()); - Assert.assertEquals(header.getValue(HttpHeaderConsts.ACCEPT_ENCODING), "gzip,deflate,sdch"); - Assert.assertEquals(header.getValue(HttpHeaderConsts.CONNECTION), "Keep-Alive"); - Assert.assertNotNull(header.getValue(HttpHeaderConsts.REQUEST_ID)); - Assert.assertEquals(header.getValue(HttpHeaderConsts.REQUEST_MODULE), "Naming"); + assertNotNull(header); + assertEquals(header.getValue(HttpHeaderConsts.CLIENT_VERSION_HEADER), VersionUtils.version); + assertEquals(header.getValue(HttpHeaderConsts.USER_AGENT_HEADER), VersionUtils.getFullClientVersion()); + assertEquals("gzip,deflate,sdch", header.getValue(HttpHeaderConsts.ACCEPT_ENCODING)); + assertEquals("Keep-Alive", header.getValue(HttpHeaderConsts.CONNECTION)); + assertNotNull(header.getValue(HttpHeaderConsts.REQUEST_ID)); + assertEquals("Naming", header.getValue(HttpHeaderConsts.REQUEST_MODULE)); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java index bbdf66b5dc5..069f27a91d1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java @@ -16,17 +16,18 @@ package com.alibaba.nacos.client.naming.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PairTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PairTest { @Test - public void testItem() { + void testItem() { String item = "aa"; double weight = 1.0; Pair pair = new Pair<>(item, weight); - Assert.assertEquals(weight, pair.weight(), 0.01); - Assert.assertEquals(item, pair.item()); + assertEquals(weight, pair.weight(), 0.01); + assertEquals(item, pair.item()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java index ee75d48914a..24288008357 100644 --- a/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java @@ -23,12 +23,13 @@ import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.lang.reflect.Field; import java.util.ArrayList; @@ -37,21 +38,25 @@ import java.util.Map; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class SecurityProxyTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class SecurityProxyTest { private SecurityProxy securityProxy; @Mock private NacosRestTemplate nacosRestTemplate; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { //given HttpRestResult result = new HttpRestResult<>(); result.setData("{\"accessToken\":\"ttttttttttttttttt\",\"tokenTtl\":1000}"); @@ -64,7 +69,7 @@ public void setUp() throws Exception { } @Test - public void testLoginClientAuthService() throws Exception { + void testLoginClientAuthService() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); @@ -73,7 +78,7 @@ public void testLoginClientAuthService() throws Exception { } @Test - public void testGetIdentityContext() { + void testGetIdentityContext() { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); @@ -81,11 +86,11 @@ public void testGetIdentityContext() { //when Map keyMap = securityProxy.getIdentityContext(null); //then - Assert.assertEquals("ttttttttttttttttt", keyMap.get(NacosAuthLoginConstant.ACCESSTOKEN)); + assertEquals("ttttttttttttttttt", keyMap.get(NacosAuthLoginConstant.ACCESSTOKEN)); } @Test - public void testLoginWithoutAnyPlugin() throws NoSuchFieldException, IllegalAccessException { + void testLoginWithoutAnyPlugin() throws NoSuchFieldException, IllegalAccessException { Field clientAuthPluginManagerField = SecurityProxy.class.getDeclaredField("clientAuthPluginManager"); clientAuthPluginManagerField.setAccessible(true); ClientAuthPluginManager clientAuthPluginManager = mock(ClientAuthPluginManager.class); @@ -93,6 +98,6 @@ public void testLoginWithoutAnyPlugin() throws NoSuchFieldException, IllegalAcce when(clientAuthPluginManager.getAuthServiceSpiImplSet()).thenReturn(Collections.emptySet()); securityProxy.login(new Properties()); Map header = securityProxy.getIdentityContext(new RequestResource()); - Assert.assertTrue(header.isEmpty()); + assertTrue(header.isEmpty()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java index 95ddb0265c9..1d41c1ee44f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java @@ -19,20 +19,20 @@ package com.alibaba.nacos.client.utils; import com.alibaba.nacos.client.constant.Constants; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AppNameUtilsTest { +class AppNameUtilsTest { - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { System.clearProperty(Constants.SysEnv.PROJECT_NAME); System.clearProperty("jboss.server.home.dir"); System.clearProperty("jetty.home"); @@ -40,34 +40,34 @@ public void tearDown() throws Exception { } @Test - public void testGetAppNameByDefault() { + void testGetAppNameByDefault() { String appName = AppNameUtils.getAppName(); assertEquals("unknown", appName); } @Test - public void testGetAppNameByProjectName() { + void testGetAppNameByProjectName() { System.setProperty(Constants.SysEnv.PROJECT_NAME, "testAppName"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } @Test - public void testGetAppNameByServerTypeForJboss() { + void testGetAppNameByServerTypeForJboss() { System.setProperty("jboss.server.home.dir", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } @Test - public void testGetAppNameByServerTypeForJetty() { + void testGetAppNameByServerTypeForJetty() { System.setProperty("jetty.home", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } @Test - public void testGetAppNameByServerTypeForTomcat() { + void testGetAppNameByServerTypeForTomcat() { System.setProperty("catalina.base", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java index c1953d8b1e7..3692872939e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java @@ -16,9 +16,9 @@ package com.alibaba.nacos.client.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * ContextPathUtil test. @@ -26,10 +26,10 @@ * @author Wei.Wang * @date 2020/11/26 3:13 PM */ -public class ContextPathUtilTest { +class ContextPathUtilTest { @Test - public void testNormalizeContextPath() { + void testNormalizeContextPath() { assertEquals("/nacos", ContextPathUtil.normalizeContextPath("/nacos")); assertEquals("/nacos", ContextPathUtil.normalizeContextPath("nacos")); assertEquals("", ContextPathUtil.normalizeContextPath("/")); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java index 1be9575ef4e..8a8185ed9fc 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java @@ -19,8 +19,7 @@ package com.alibaba.nacos.client.utils; import com.alibaba.nacos.api.common.Constants; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -28,45 +27,48 @@ import java.util.List; import java.util.Map; -public class EnvUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class EnvUtilTest { @Test - public void testSetSelfEnv() { + void testSetSelfEnv() { Map> headers = new HashMap<>(); headers.put(Constants.AMORY_TAG, Arrays.asList("a", "1")); headers.put(Constants.VIPSERVER_TAG, Arrays.asList("b", "2")); headers.put(Constants.LOCATION_TAG, Arrays.asList("c", "3")); EnvUtil.setSelfEnv(headers); - Assert.assertEquals("a,1", EnvUtil.getSelfAmoryTag()); - Assert.assertEquals("b,2", EnvUtil.getSelfVipserverTag()); - Assert.assertEquals("c,3", EnvUtil.getSelfLocationTag()); + assertEquals("a,1", EnvUtil.getSelfAmoryTag()); + assertEquals("b,2", EnvUtil.getSelfVipserverTag()); + assertEquals("c,3", EnvUtil.getSelfLocationTag()); // reset by empty list headers.put(Constants.AMORY_TAG, Collections.emptyList()); headers.put(Constants.VIPSERVER_TAG, Collections.emptyList()); headers.put(Constants.LOCATION_TAG, Collections.emptyList()); EnvUtil.setSelfEnv(headers); - Assert.assertNull(EnvUtil.getSelfAmoryTag()); - Assert.assertNull(EnvUtil.getSelfVipserverTag()); - Assert.assertNull(EnvUtil.getSelfLocationTag()); + assertNull(EnvUtil.getSelfAmoryTag()); + assertNull(EnvUtil.getSelfVipserverTag()); + assertNull(EnvUtil.getSelfLocationTag()); } @Test - public void testSetSelfEnv2() { + void testSetSelfEnv2() { Map> headers = new HashMap<>(); headers.put(Constants.AMORY_TAG, Arrays.asList("a", "1")); headers.put(Constants.VIPSERVER_TAG, Arrays.asList("b", "2")); headers.put(Constants.LOCATION_TAG, Arrays.asList("c", "3")); EnvUtil.setSelfEnv(headers); - Assert.assertEquals("a,1", EnvUtil.getSelfAmoryTag()); - Assert.assertEquals("b,2", EnvUtil.getSelfVipserverTag()); - Assert.assertEquals("c,3", EnvUtil.getSelfLocationTag()); + assertEquals("a,1", EnvUtil.getSelfAmoryTag()); + assertEquals("b,2", EnvUtil.getSelfVipserverTag()); + assertEquals("c,3", EnvUtil.getSelfLocationTag()); // reset headers.put(Constants.AMORY_TAG, null); headers.put(Constants.VIPSERVER_TAG, null); headers.put(Constants.LOCATION_TAG, null); EnvUtil.setSelfEnv(headers); - Assert.assertNull(EnvUtil.getSelfAmoryTag()); - Assert.assertNull(EnvUtil.getSelfVipserverTag()); - Assert.assertNull(EnvUtil.getSelfLocationTag()); + assertNull(EnvUtil.getSelfAmoryTag()); + assertNull(EnvUtil.getSelfVipserverTag()); + assertNull(EnvUtil.getSelfLocationTag()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java index ec04b5a4e7b..d158de997fa 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java @@ -16,16 +16,17 @@ package com.alibaba.nacos.client.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; -public class LogUtilsTest { +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class LogUtilsTest { @Test - public void testLogger() { + void testLogger() { Logger logger = LogUtils.logger(LogUtilsTest.class); - Assert.assertNotNull(logger); + assertNotNull(logger); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java index 7f16b04f607..5fa229bf58c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java @@ -22,17 +22,18 @@ import com.alibaba.nacos.client.env.NacosClientProperties; import com.alibaba.nacos.common.utils.MD5Utils; import com.alibaba.nacos.common.utils.VersionUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class ParamUtilTest { +class ParamUtilTest { private String defaultAppKey; @@ -48,8 +49,8 @@ public class ParamUtilTest { private String defaultNodesPath; - @Before - public void before() { + @BeforeEach + void before() { defaultAppKey = ""; defaultAppName = "unknown"; defaultContextPath = "nacos"; @@ -59,8 +60,8 @@ public void before() { defaultNodesPath = "serverlist"; } - @After - public void after() { + @AfterEach + void after() { ParamUtil.setAppKey(defaultAppKey); ParamUtil.setAppName(defaultAppName); ParamUtil.setDefaultContextPath(defaultContextPath); @@ -74,7 +75,7 @@ public void after() { } @Test - public void testGetAppKey() { + void testGetAppKey() { String defaultVal = ParamUtil.getAppKey(); assertEquals(defaultAppKey, defaultVal); @@ -84,7 +85,7 @@ public void testGetAppKey() { } @Test - public void testGetAppName() { + void testGetAppName() { String defaultVal = ParamUtil.getAppName(); assertEquals(defaultAppName, defaultVal); @@ -94,7 +95,7 @@ public void testGetAppName() { } @Test - public void testGetDefaultContextPath() { + void testGetDefaultContextPath() { String defaultVal = ParamUtil.getDefaultContextPath(); assertEquals(defaultContextPath, defaultVal); @@ -104,7 +105,7 @@ public void testGetDefaultContextPath() { } @Test - public void testGetClientVersion() { + void testGetClientVersion() { String defaultVal = ParamUtil.getClientVersion(); assertEquals(defaultVersion, defaultVal); @@ -114,7 +115,7 @@ public void testGetClientVersion() { } @Test - public void testSetConnectTimeout() { + void testSetConnectTimeout() { int defaultVal = ParamUtil.getConnectTimeout(); assertEquals(defaultConnectTimeout, defaultVal); @@ -124,7 +125,7 @@ public void testSetConnectTimeout() { } @Test - public void testGetPerTaskConfigSize() { + void testGetPerTaskConfigSize() { double defaultVal = ParamUtil.getPerTaskConfigSize(); assertEquals(defaultPerTaskConfigSize, defaultVal, 0.01); @@ -134,13 +135,13 @@ public void testGetPerTaskConfigSize() { } @Test - public void testGetDefaultServerPort() { + void testGetDefaultServerPort() { String actual = ParamUtil.getDefaultServerPort(); assertEquals("8848", actual); } @Test - public void testGetDefaultNodesPath() { + void testGetDefaultNodesPath() { String defaultVal = ParamUtil.getDefaultNodesPath(); assertEquals("serverlist", defaultVal); @@ -150,7 +151,7 @@ public void testGetDefaultNodesPath() { } @Test - public void testParseNamespace() { + void testParseNamespace() { String expect = "test"; Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.NAMESPACE, expect); @@ -161,50 +162,54 @@ public void testParseNamespace() { } @Test - public void testParsingEndpointRule() { + void testParsingEndpointRule() { String url = "${test:www.example.com}"; String actual = ParamUtil.parsingEndpointRule(url); assertEquals("www.example.com", actual); } - @Test(expected = IllegalArgumentException.class) - public void testInitConnectionTimeoutWithException() throws Throwable { - Method method = ParamUtil.class.getDeclaredMethod("initConnectionTimeout"); - method.setAccessible(true); - System.setProperty("NACOS.CONNECT.TIMEOUT", "test"); - try { - method.invoke(null); - } catch (InvocationTargetException e) { - throw e.getCause(); - } + @Test + void testInitConnectionTimeoutWithException() throws Throwable { + assertThrows(IllegalArgumentException.class, () -> { + Method method = ParamUtil.class.getDeclaredMethod("initConnectionTimeout"); + method.setAccessible(true); + System.setProperty("NACOS.CONNECT.TIMEOUT", "test"); + try { + method.invoke(null); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); } - @Test(expected = IllegalArgumentException.class) - public void testInitPerTaskConfigSizeWithException() throws Throwable { - Method method = ParamUtil.class.getDeclaredMethod("initPerTaskConfigSize"); - method.setAccessible(true); - System.setProperty("PER_TASK_CONFIG_SIZE", "test"); - try { - method.invoke(null); - } catch (InvocationTargetException e) { - throw e.getCause(); - } + @Test + void testInitPerTaskConfigSizeWithException() throws Throwable { + assertThrows(IllegalArgumentException.class, () -> { + Method method = ParamUtil.class.getDeclaredMethod("initPerTaskConfigSize"); + method.setAccessible(true); + System.setProperty("PER_TASK_CONFIG_SIZE", "test"); + try { + method.invoke(null); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); } @Test - public void testParsingEndpointRuleFromSystem() { + void testParsingEndpointRuleFromSystem() { System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url"); assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule(null)); } @Test - public void testParsingEndpointRuleFromSystemWithParam() { + void testParsingEndpointRuleFromSystemWithParam() { System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url"); assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule("${abc:xxx}")); } @Test - public void testSimplyEnvNameIfOverLimit() { + void testSimplyEnvNameIfOverLimit() { StringBuilder envNameOverLimitBuilder = new StringBuilder("test"); for (int i = 0; i < 50; i++) { envNameOverLimitBuilder.append(i); @@ -215,7 +220,8 @@ public void testSimplyEnvNameIfOverLimit() { assertEquals(expect, actual); } - @Test public void testSimplyEnvNameNotOverLimit() { + @Test + void testSimplyEnvNameNotOverLimit() { String expect = "test"; assertEquals(expect, ParamUtil.simplyEnvNameIfOverLimit(expect)); } diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java index 67969c8ef48..19b6c6f0b8e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.client.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -public class PreInitUtilsTest { +class PreInitUtilsTest { @Test - public void testAsyncPreLoadCostComponent() throws InterruptedException { + void testAsyncPreLoadCostComponent() throws InterruptedException { // There is no things need to be assert. // The method will called when nacos-client init to async to load some components to reduce the sync load time. PreInitUtils.asyncPreLoadCostComponent(); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java index 1550888822b..95d13c20c20 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.client.utils; import com.alibaba.nacos.common.utils.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collection; @@ -27,15 +27,15 @@ import static com.alibaba.nacos.common.utils.StringUtils.isNotEmpty; import static com.alibaba.nacos.common.utils.StringUtils.join; import static com.alibaba.nacos.common.utils.StringUtils.substringBetween; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class StringUtilsTest { +class StringUtilsTest { @Test - public void testisNotBlank() { + void testisNotBlank() { assertTrue(isNotBlank("foo")); assertFalse(isNotBlank(" ")); @@ -43,20 +43,20 @@ public void testisNotBlank() { } @Test - public void testIsNotEmpty() { + void testIsNotEmpty() { assertFalse(isNotEmpty("")); assertTrue(isNotEmpty("foo")); } @Test - public void testDefaultIfEmpty() { + void testDefaultIfEmpty() { assertEquals("foo", defaultIfEmpty("", "foo")); assertEquals("bar", defaultIfEmpty("bar", "foo")); } @Test - public void testEquals() { + void testEquals() { assertTrue(StringUtils.equals("foo", "foo")); assertFalse(StringUtils.equals("bar", "foo")); @@ -65,7 +65,7 @@ public void testEquals() { } @Test - public void testSubstringBetween() { + void testSubstringBetween() { assertNull(substringBetween(null, null, null)); assertNull(substringBetween("", "foo", "")); assertNull(substringBetween("foo", "bar", "baz")); @@ -74,7 +74,7 @@ public void testSubstringBetween() { } @Test - public void testJoin() { + void testJoin() { assertNull(join(null, "")); Collection collection = new ArrayList(); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java index 0af54f40bd6..497a3cb2462 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java @@ -18,21 +18,21 @@ package com.alibaba.nacos.client.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.concurrent.Callable; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class TemplateUtilsTest { +class TemplateUtilsTest { @Test - public void testStringNotEmptyAndThenExecuteSuccess() { + void testStringNotEmptyAndThenExecuteSuccess() { String word = "run"; Runnable task = Mockito.mock(Runnable.class); TemplateUtils.stringNotEmptyAndThenExecute(word, task); @@ -40,7 +40,7 @@ public void testStringNotEmptyAndThenExecuteSuccess() { } @Test - public void testStringNotEmptyAndThenExecuteFail() { + void testStringNotEmptyAndThenExecuteFail() { String word = ""; Runnable task = Mockito.mock(Runnable.class); TemplateUtils.stringNotEmptyAndThenExecute(word, task); @@ -48,7 +48,7 @@ public void testStringNotEmptyAndThenExecuteFail() { } @Test - public void testStringNotEmptyAndThenExecuteException() { + void testStringNotEmptyAndThenExecuteException() { String word = "run"; Runnable task = Mockito.mock(Runnable.class); doThrow(new RuntimeException("test")).when(task).run(); @@ -58,22 +58,22 @@ public void testStringNotEmptyAndThenExecuteException() { } @Test - public void testStringEmptyAndThenExecuteSuccess() { + void testStringEmptyAndThenExecuteSuccess() { String word = " "; String actual = TemplateUtils.stringEmptyAndThenExecute(word, () -> "call"); - Assert.assertEquals("", actual); + assertEquals("", actual); } @Test - public void testStringEmptyAndThenExecuteFail() { + void testStringEmptyAndThenExecuteFail() { String word = ""; final String expect = "call"; String actual = TemplateUtils.stringEmptyAndThenExecute(word, () -> expect); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } @Test - public void testStringEmptyAndThenExecuteException() throws Exception { + void testStringEmptyAndThenExecuteException() throws Exception { Callable callable = mock(Callable.class); when(callable.call()).thenThrow(new RuntimeException("test")); String actual = TemplateUtils.stringEmptyAndThenExecute(null, callable); @@ -81,22 +81,22 @@ public void testStringEmptyAndThenExecuteException() throws Exception { } @Test - public void testStringBlankAndThenExecuteSuccess() { + void testStringBlankAndThenExecuteSuccess() { String word = "success"; String actual = TemplateUtils.stringBlankAndThenExecute(word, () -> "call"); - Assert.assertEquals(word, actual); + assertEquals(word, actual); } @Test - public void testStringBlankAndThenExecuteFail() { + void testStringBlankAndThenExecuteFail() { String word = " "; final String expect = "call"; String actual = TemplateUtils.stringBlankAndThenExecute(word, () -> expect); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } @Test - public void testStringBlankAndThenExecuteException() throws Exception { + void testStringBlankAndThenExecuteException() throws Exception { Callable callable = mock(Callable.class); when(callable.call()).thenThrow(new RuntimeException("test")); String actual = TemplateUtils.stringBlankAndThenExecute(null, callable); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java index 4b00504bc3a..a64f3396fbc 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java @@ -18,32 +18,33 @@ package com.alibaba.nacos.client.utils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -public class TenantUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TenantUtilTest { - @After - public void tearDown() { + @AfterEach + void tearDown() { System.clearProperty("acm.namespace"); System.clearProperty("ans.namespace"); } @Test - public void testGetUserTenantForAcm() { + void testGetUserTenantForAcm() { String expect = "test"; System.setProperty("acm.namespace", expect); String actual = TenantUtil.getUserTenantForAcm(); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } @Test - public void testGetUserTenantForAns() { + void testGetUserTenantForAns() { String expect = "test"; System.setProperty("ans.namespace", expect); String actual = TenantUtil.getUserTenantForAns(); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java index a14536facc1..5cefb91b3cf 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java @@ -17,17 +17,18 @@ package com.alibaba.nacos.client.utils; import com.alibaba.nacos.api.PropertyKeyConst; -import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Properties; -public class ValidatorUtilsTest { +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ValidatorUtilsTest { @Test - public void testContextPathLegal() { + void testContextPathLegal() { String contextPath1 = "/nacos"; ValidatorUtils.checkContextPath(contextPath1); String contextPath2 = "nacos"; @@ -40,39 +41,45 @@ public void testContextPathLegal() { ValidatorUtils.checkContextPath(null); } - @Test(expected = IllegalArgumentException.class) - public void testContextPathIllegal1() { - String contextPath1 = "//nacos/"; - ValidatorUtils.checkContextPath(contextPath1); + @Test + void testContextPathIllegal1() { + assertThrows(IllegalArgumentException.class, () -> { + String contextPath1 = "//nacos/"; + ValidatorUtils.checkContextPath(contextPath1); + }); } - @Test(expected = IllegalArgumentException.class) - public void testContextPathIllegal2() { - String contextPath2 = "/nacos//"; - ValidatorUtils.checkContextPath(contextPath2); + @Test + void testContextPathIllegal2() { + assertThrows(IllegalArgumentException.class, () -> { + String contextPath2 = "/nacos//"; + ValidatorUtils.checkContextPath(contextPath2); + }); } - @Test(expected = IllegalArgumentException.class) - public void testContextPathIllegal3() { - String contextPath3 = "///"; - ValidatorUtils.checkContextPath(contextPath3); + @Test + void testContextPathIllegal3() { + assertThrows(IllegalArgumentException.class, () -> { + String contextPath3 = "///"; + ValidatorUtils.checkContextPath(contextPath3); + }); } - @Test(expected = IllegalArgumentException.class) - public void testContextPathIllegal4() { - String contextPath4 = "//"; - ValidatorUtils.checkContextPath(contextPath4); + @Test + void testContextPathIllegal4() { + assertThrows(IllegalArgumentException.class, () -> { + String contextPath4 = "//"; + ValidatorUtils.checkContextPath(contextPath4); + }); } @Test - public void testCheckInitParam() { - try { + void testCheckInitParam() { + Assertions.assertDoesNotThrow(() -> { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.CONTEXT_PATH, "test"); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ValidatorUtils.checkInitParam(nacosClientProperties); - } catch (NacosException e) { - Assert.fail(); - } + }); } }