diff --git a/examples/pom.xml b/examples/pom.xml
index 216b9845f..7f0b86d45 100644
--- a/examples/pom.xml
+++ b/examples/pom.xml
@@ -96,6 +96,7 @@
org.junit.jupiter
junit-jupiter
+ test
org.mockito
diff --git a/pom.xml b/pom.xml
index 779109ba2..5026de175 100644
--- a/pom.xml
+++ b/pom.xml
@@ -37,6 +37,9 @@
../spotbugs-exclude.xml
2.7.8
--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED
+ 3.1.2
+ 3.1.2
+ 5.7.2
@@ -70,16 +73,11 @@
${grpc.version}
- junit
- junit
- 4.13.2
- test
-
-
- org.junit.jupiter
- junit-jupiter
- 5.7.2
- test
+ org.junit
+ junit-bom
+ ${junit-bom.version}
+ import
+ pom
org.mockito
@@ -91,6 +89,33 @@
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${surefire.version}
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+ ${failsafe.version}
+
+
+
+ integration-test
+ verify
+
+
+
+ ${skipITs}
+
+
+
+
+
+
+
org.jacoco
@@ -102,13 +127,6 @@
prepare-agent
-
- report
- test
-
- report
-
-
@@ -165,23 +183,6 @@
true
-
- org.codehaus.mojo
- failsafe-maven-plugin
- 2.4.3-alpha-1
-
-
-
- integration-test
- verify
-
-
-
- ${skipITs}
-
-
-
-
org.apache.maven.plugins
maven-checkstyle-plugin
diff --git a/sdk-actors/pom.xml b/sdk-actors/pom.xml
index 143312c92..32c68625c 100644
--- a/sdk-actors/pom.xml
+++ b/sdk-actors/pom.xml
@@ -27,11 +27,6 @@
dapr-sdk
${project.version}
-
- junit
- junit
- test
-
org.mockito
mockito-core
@@ -45,8 +40,7 @@
org.junit.jupiter
- junit-jupiter-api
- 5.5.2
+ junit-jupiter
test
diff --git a/sdk-actors/src/test/java/io/dapr/actors/ActorIdTest.java b/sdk-actors/src/test/java/io/dapr/actors/ActorIdTest.java
index 1537125fc..cd0b321d2 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/ActorIdTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/ActorIdTest.java
@@ -12,41 +12,44 @@ limitations under the License.
*/
package io.dapr.actors;
-import org.junit.Assert;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* Unit tests for ActorId.
*/
public class ActorIdTest {
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void initializeNewActorIdObjectWithNullId() {
- ActorId actorId = new ActorId(null);
+ assertThrows(IllegalArgumentException.class, () ->{ActorId actorId = new ActorId(null);});
}
@Test
public void getId() {
String id = "123";
ActorId actorId = new ActorId(id);
- Assert.assertEquals(id, actorId.toString());
+ assertEquals(id, actorId.toString());
}
@Test
public void verifyToString() {
String id = "123";
ActorId actorId = new ActorId(id);
- Assert.assertEquals(id, actorId.toString());
+ assertEquals(id, actorId.toString());
}
@Test
public void verifyEqualsByObject() {
List values = createEqualsTestValues();
for (Wrapper w : values) {
- Assert.assertEquals(w.expectedResult, w.item1.equals(w.item2));
+ assertEquals(w.expectedResult, w.item1.equals(w.item2));
}
}
@@ -56,7 +59,7 @@ public class ActorIdTest {
for (Wrapper w : values) {
ActorId a1 = (ActorId) w.item1;
Object a2 = w.item2;
- Assert.assertEquals(w.expectedResult, a1.equals(a2));
+ assertEquals(w.expectedResult, a1.equals(a2));
}
}
@@ -66,7 +69,7 @@ public class ActorIdTest {
for (Wrapper w : values) {
ActorId a1 = (ActorId) w.item1;
ActorId a2 = (ActorId) w.item2;
- Assert.assertEquals(w.expectedResult, a1.compareTo(a2));
+ assertEquals(w.expectedResult, a1.compareTo(a2));
}
}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/client/ActorProxyBuilderTest.java b/sdk-actors/src/test/java/io/dapr/actors/client/ActorProxyBuilderTest.java
index de258a232..a0760b3d4 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/client/ActorProxyBuilderTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/client/ActorProxyBuilderTest.java
@@ -15,51 +15,53 @@ package io.dapr.actors.client;
import io.dapr.actors.ActorId;
import io.dapr.actors.ActorType;
-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.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
public class ActorProxyBuilderTest {
private static ActorClient actorClient;
- @BeforeClass
+ @BeforeAll
public static void initClass() {
actorClient = new ActorClient();
}
- @AfterClass
+ @AfterAll
public static void tearDownClass() {
actorClient.close();
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void buildWithNullActorId() {
- new ActorProxyBuilder("test", Object.class, actorClient)
- .build(null);
+ assertThrows(IllegalArgumentException.class, () -> new ActorProxyBuilder("test", Object.class, actorClient)
+ .build(null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void buildWithEmptyActorType() {
- new ActorProxyBuilder("", Object.class, actorClient);
+ assertThrows(IllegalArgumentException.class, () -> new ActorProxyBuilder("", Object.class, actorClient));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void buildWithNullActorType() {
- new ActorProxyBuilder(null, Object.class, actorClient);
+ assertThrows(IllegalArgumentException.class, () -> new ActorProxyBuilder(null, Object.class, actorClient));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void buildWithNullSerializer() {
- new ActorProxyBuilder("MyActor", Object.class, actorClient)
+ assertThrows(IllegalArgumentException.class, () -> new ActorProxyBuilder("MyActor", Object.class, actorClient)
.withObjectSerializer(null)
- .build(new ActorId("100"));
+ .build(new ActorId("100")));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void buildWithNullClient() {
- new ActorProxyBuilder("MyActor", Object.class, null);
+ assertThrows(IllegalArgumentException.class, () -> new ActorProxyBuilder("MyActor", Object.class, null));
}
@Test()
@@ -67,9 +69,9 @@ public class ActorProxyBuilderTest {
ActorProxyBuilder builder = new ActorProxyBuilder("test", ActorProxy.class, actorClient);
ActorProxy actorProxy = builder.build(new ActorId("100"));
- Assert.assertNotNull(actorProxy);
- Assert.assertEquals("test", actorProxy.getActorType());
- Assert.assertEquals("100", actorProxy.getActorId().toString());
+ Assertions.assertNotNull(actorProxy);
+ Assertions.assertEquals("test", actorProxy.getActorType());
+ Assertions.assertEquals("100", actorProxy.getActorId().toString());
}
@Test()
@@ -77,7 +79,7 @@ public class ActorProxyBuilderTest {
ActorProxyBuilder builder = new ActorProxyBuilder(MyActor.class, actorClient);
MyActor actorProxy = builder.build(new ActorId("100"));
- Assert.assertNotNull(actorProxy);
+ Assertions.assertNotNull(actorProxy);
}
@Test()
@@ -85,7 +87,7 @@ public class ActorProxyBuilderTest {
ActorProxyBuilder builder = new ActorProxyBuilder(ActorWithDefaultName.class, actorClient);
ActorWithDefaultName actorProxy = builder.build(new ActorId("100"));
- Assert.assertNotNull(actorProxy);
+ Assertions.assertNotNull(actorProxy);
}
@ActorType(name = "MyActor")
diff --git a/sdk-actors/src/test/java/io/dapr/actors/client/ActorProxyImplTest.java b/sdk-actors/src/test/java/io/dapr/actors/client/ActorProxyImplTest.java
index 71e09dd71..d60388858 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/client/ActorProxyImplTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/client/ActorProxyImplTest.java
@@ -18,11 +18,12 @@ import io.dapr.actors.ActorMethod;
import io.dapr.exceptions.DaprException;
import io.dapr.serializer.DaprObjectSerializer;
import io.dapr.serializer.DefaultObjectSerializer;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import reactor.core.publisher.Mono;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -38,8 +39,8 @@ public class ActorProxyImplTest {
new ActorId("100"),
serializer,
daprClient);
- Assert.assertEquals(actorProxy.getActorId().toString(), "100");
- Assert.assertEquals(actorProxy.getActorType(), "myActorType");
+ Assertions.assertEquals(actorProxy.getActorId().toString(), "100");
+ Assertions.assertEquals(actorProxy.getActorType(), "myActorType");
}
@Test()
@@ -59,9 +60,9 @@ public class ActorProxyImplTest {
Mono result = actorProxy.invokeMethod("getData", MyData.class);
MyData myData = result.block();
- Assert.assertNotNull(myData);
- Assert.assertEquals("valueA", myData.getPropertyA());
- Assert.assertEquals("valueB", myData.getPropertyB());// propertyB=null
+ Assertions.assertNotNull(myData);
+ Assertions.assertEquals("valueA", myData.getPropertyA());
+ Assertions.assertEquals("valueB", myData.getPropertyB());// propertyB=null
}
@Test()
@@ -80,9 +81,9 @@ public class ActorProxyImplTest {
daprClient);
MyData myData = (MyData) actorProxy.invoke(actorProxy, Actor.class.getMethod("getData"), null);
- Assert.assertNotNull(myData);
- Assert.assertEquals("valueA", myData.getPropertyA());
- Assert.assertEquals("valueB", myData.getPropertyB());// propertyB=null
+ Assertions.assertNotNull(myData);
+ Assertions.assertEquals("valueA", myData.getPropertyA());
+ Assertions.assertEquals("valueB", myData.getPropertyB());// propertyB=null
}
@Test()
@@ -101,11 +102,11 @@ public class ActorProxyImplTest {
daprClient);
Mono res = (Mono) actorProxy.invoke(actorProxy, Actor.class.getMethod("getDataMono"), null);
- Assert.assertNotNull(res);
+ Assertions.assertNotNull(res);
MyData myData = res.block();
- Assert.assertNotNull(myData);
- Assert.assertEquals("valueA", myData.getPropertyA());
- Assert.assertEquals("valueB", myData.getPropertyB());// propertyB=null
+ Assertions.assertNotNull(myData);
+ Assertions.assertEquals("valueA", myData.getPropertyA());
+ Assertions.assertEquals("valueB", myData.getPropertyB());// propertyB=null
}
@Test()
@@ -128,7 +129,7 @@ public class ActorProxyImplTest {
Actor.class.getMethod("echo", String.class),
new Object[] { "hello world" } );
- Assert.assertEquals("OK", res);
+ Assertions.assertEquals("OK", res);
}
@Test()
@@ -151,8 +152,8 @@ public class ActorProxyImplTest {
Actor.class.getMethod("echoMono", String.class),
new Object[] { "hello world" } );
- Assert.assertNotNull(res);
- Assert.assertEquals("OK", res.block());
+ Assertions.assertNotNull(res);
+ Assertions.assertEquals("OK", res.block());
}
@Test()
@@ -170,7 +171,7 @@ public class ActorProxyImplTest {
daprClient);
Object myData = actorProxy.invoke(actorProxy, Actor.class.getMethod("doSomething"), null);
- Assert.assertNull(myData);
+ Assertions.assertNull(myData);
}
@Test()
@@ -188,8 +189,8 @@ public class ActorProxyImplTest {
daprClient);
Mono myData = (Mono)actorProxy.invoke(actorProxy, Actor.class.getMethod("doSomethingMono"), null);
- Assert.assertNotNull(myData);
- Assert.assertNull(myData.block());
+ Assertions.assertNotNull(myData);
+ Assertions.assertNull(myData.block());
}
@Test()
@@ -211,11 +212,11 @@ public class ActorProxyImplTest {
Actor.class.getMethod("doSomethingMonoWithArg", String.class),
new Object[] { "hello world" });
- Assert.assertNotNull(myData);
- Assert.assertNull(myData.block());
+ Assertions.assertNotNull(myData);
+ Assertions.assertNull(myData.block());
}
- @Test(expected = UnsupportedOperationException.class)
+ @Test
public void invokeActorMethodWithTooManyArgsViaReflection() throws NoSuchMethodException {
final ActorClient daprClient = mock(ActorClient.class);
@@ -225,13 +226,10 @@ public class ActorProxyImplTest {
new DefaultObjectSerializer(),
daprClient);
- Mono myData = (Mono)actorProxy.invoke(
+ assertThrows(UnsupportedOperationException.class, () -> actorProxy.invoke(
actorProxy,
Actor.class.getMethod("tooManyArgs", String.class, String.class),
- new Object[] { "hello", "world" });
-
- Assert.assertNotNull(myData);
- Assert.assertNull(myData.block());
+ new Object[] { "hello", "world" }));
}
@Test()
@@ -253,7 +251,7 @@ public class ActorProxyImplTest {
Actor.class.getMethod("process", String.class),
new Object[] { "hello world" } );
- Assert.assertNull(res);
+ Assertions.assertNull(res);
}
@Test()
@@ -270,10 +268,10 @@ public class ActorProxyImplTest {
Mono result = actorProxy.invokeMethod("getData", MyData.class);
MyData myData = result.block();
- Assert.assertNull(myData);
+ Assertions.assertNull(myData);
}
- @Test(expected = RuntimeException.class)
+ @Test
public void invokeActorMethodWithIncorrectReturnType() {
final ActorClient daprClient = mock(ActorClient.class);
when(daprClient.invoke(anyString(), anyString(), anyString(), Mockito.isNull()))
@@ -287,10 +285,7 @@ public class ActorProxyImplTest {
Mono result = actorProxy.invokeMethod("getData", MyData.class);
- result.doOnSuccess(x ->
- Assert.fail("Not exception was throw"))
- .doOnError(Throwable::printStackTrace
- ).block();
+ assertThrows(DaprException.class, () ->result.block());
}
@Test()
@@ -312,13 +307,13 @@ public class ActorProxyImplTest {
Mono result = actorProxy.invokeMethod("getData", saveData, MyData.class);
MyData myData = result.block();
- Assert.assertNotNull(myData);
- Assert.assertEquals("valueA", myData.getPropertyA());
- Assert.assertEquals("valueB", myData.getPropertyB());//propertyB=null
+ Assertions.assertNotNull(myData);
+ Assertions.assertEquals("valueA", myData.getPropertyA());
+ Assertions.assertEquals("valueB", myData.getPropertyB());//propertyB=null
}
- @Test(expected = DaprException.class)
+ @Test
public void invokeActorMethodSavingDataWithIncorrectReturnType() {
final ActorClient daprClient = mock(ActorClient.class);
when(daprClient.invoke(anyString(), anyString(), anyString(), Mockito.isNotNull()))
@@ -335,10 +330,7 @@ public class ActorProxyImplTest {
saveData.setPropertyB("valueB");
Mono result = actorProxy.invokeMethod("getData", saveData, MyData.class);
- result.doOnSuccess(x ->
- Assert.fail("Not exception was throw"))
- .doOnError(Throwable::printStackTrace
- ).block();
+ assertThrows(DaprException.class, () ->result.block());
}
@@ -360,11 +352,11 @@ public class ActorProxyImplTest {
Mono result = actorProxy.invokeMethod("getData", saveData, MyData.class);
MyData myData = result.block();
- Assert.assertNull(myData);
+ Assertions.assertNull(myData);
}
- @Test(expected = DaprException.class)
+ @Test
public void invokeActorMethodSavingDataWithIncorrectInputType() {
final ActorClient daprClient = mock(ActorClient.class);
when(daprClient.invoke(anyString(), anyString(), anyString(), Mockito.isNotNull()))
@@ -381,12 +373,7 @@ public class ActorProxyImplTest {
saveData.setPropertyB("valueB");
saveData.setMyData(saveData);
- Mono result = actorProxy.invokeMethod("getData", saveData, MyData.class);
- result.doOnSuccess(x ->
- Assert.fail("Not exception was throw"))
- .doOnError(Throwable::printStackTrace
- ).block();
-
+ assertThrows(DaprException.class, () -> actorProxy.invokeMethod("getData", saveData, MyData.class));
}
@Test()
@@ -407,11 +394,11 @@ public class ActorProxyImplTest {
Mono result = actorProxy.invokeMethod("getData", saveData);
Void emptyResponse = result.block();
- Assert.assertNull(emptyResponse);
+ Assertions.assertNull(emptyResponse);
}
- @Test(expected = DaprException.class)
+ @Test
public void invokeActorMethodWithDataWithVoidIncorrectInputType() {
MyData saveData = new MyData();
saveData.setPropertyA("valueA");
@@ -428,9 +415,7 @@ public class ActorProxyImplTest {
new DefaultObjectSerializer(),
daprClient);
- Mono result = actorProxy.invokeMethod("getData", saveData);
- Void emptyResponse = result.doOnError(Throwable::printStackTrace).block();
- Assert.assertNull(emptyResponse);
+ assertThrows(DaprException.class, () -> actorProxy.invokeMethod("getData", saveData));
}
@Test()
@@ -447,7 +432,7 @@ public class ActorProxyImplTest {
Mono result = actorProxy.invokeMethod("getData");
Void emptyResponse = result.block();
- Assert.assertNull(emptyResponse);
+ Assertions.assertNull(emptyResponse);
}
interface Actor {
diff --git a/sdk-actors/src/test/java/io/dapr/actors/client/DaprGrpcClientTest.java b/sdk-actors/src/test/java/io/dapr/actors/client/DaprGrpcClientTest.java
index 71360dc16..7f5a229d6 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/client/DaprGrpcClientTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/client/DaprGrpcClientTest.java
@@ -23,16 +23,16 @@ import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.GrpcCleanupRule;
-import org.junit.Before;
import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import static io.dapr.actors.TestUtils.assertThrowsDaprException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Mockito.*;
@@ -91,7 +91,7 @@ public class DaprGrpcClientTest {
private DaprGrpcClient client;
- @Before
+ @BeforeEach
public void setup() throws IOException {
// Generate a unique in-process server name.
String serverName = InProcessServerBuilder.generateName();
diff --git a/sdk-actors/src/test/java/io/dapr/actors/client/DaprHttpClientTest.java b/sdk-actors/src/test/java/io/dapr/actors/client/DaprHttpClientTest.java
index c9da10785..634780a5f 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/client/DaprHttpClientTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/client/DaprHttpClientTest.java
@@ -21,11 +21,12 @@ import okhttp3.mock.Behavior;
import okhttp3.mock.MediaTypes;
import okhttp3.mock.MockInterceptor;
import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import static io.dapr.actors.TestUtils.assertThrowsDaprException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class DaprHttpClientTest {
@@ -37,7 +38,7 @@ public class DaprHttpClientTest {
private final String EXPECTED_RESULT = "{\"data\":\"ewoJCSJwcm9wZXJ0eUEiOiAidmFsdWVBIiwKCQkicHJvcGVydHlCIjogInZhbHVlQiIKCX0=\"}";
- @Before
+ @BeforeEach
public void setUp() {
mockInterceptor = new MockInterceptor(Behavior.UNORDERED);
okHttpClient = new OkHttpClient.Builder().addInterceptor(mockInterceptor).build();
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorCustomSerializerTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorCustomSerializerTest.java
index fe577a987..316c1fdf1 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorCustomSerializerTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorCustomSerializerTest.java
@@ -19,8 +19,8 @@ import io.dapr.actors.client.ActorProxy;
import io.dapr.actors.client.ActorProxyImplForTests;
import io.dapr.actors.client.DaprClientStub;
import io.dapr.serializer.DaprObjectSerializer;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import java.io.Serializable;
@@ -108,8 +108,8 @@ public class ActorCustomSerializerTest {
MyData response = actorProxy.invokeMethod("classInClassOut", d, MyData.class).block();
- Assert.assertEquals("hihi", response.getName());
- Assert.assertEquals(6, response.getNum());
+ Assertions.assertEquals("hihi", response.getName());
+ Assertions.assertEquals(6, response.getNum());
}
@Test
@@ -117,7 +117,7 @@ public class ActorCustomSerializerTest {
ActorProxy actorProxy = createActorProxy();
String response = actorProxy.invokeMethod("stringInStringOut", "oi", String.class).block();
- Assert.assertEquals("oioi", response);
+ Assertions.assertEquals("oioi", response);
}
@Test
@@ -125,7 +125,7 @@ public class ActorCustomSerializerTest {
ActorProxy actorProxy = createActorProxy();
int response = actorProxy.invokeMethod("intInIntOut", 2, int.class).block();
- Assert.assertEquals(4, response);
+ Assertions.assertEquals(4, response);
}
private static ActorId newActorId() {
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorManagerTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorManagerTest.java
index 0e3accc52..7342d04d7 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorManagerTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorManagerTest.java
@@ -1,312 +1,320 @@
-/*
- * Copyright 2021 The Dapr Authors
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package io.dapr.actors.runtime;
-
-import io.dapr.actors.ActorId;
-import io.dapr.actors.ActorType;
-import io.dapr.serializer.DefaultObjectSerializer;
-import io.dapr.utils.TypeRef;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.jupiter.api.Assertions;
-import reactor.core.publisher.Mono;
-
-import java.io.IOException;
-import java.time.Duration;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-/**
- * Unit tests for Actor Manager
- */
-public class ActorManagerTest {
-
- private static final ActorObjectSerializer INTERNAL_SERIALIZER = new ActorObjectSerializer();
-
- private static final AtomicInteger ACTOR_ID_COUNT = new AtomicInteger();
-
- interface MyActor {
- String say(String something);
-
- int getCount();
-
- void incrementCount(int delta);
-
- void throwsException();
-
- Mono throwsExceptionHotMono();
-
- Mono throwsExceptionMono();
- }
-
- public static class NotRemindableActor extends AbstractActor {
- public NotRemindableActor(ActorRuntimeContext runtimeContext, ActorId id) {
- super(runtimeContext, id);
- }
- }
-
- @ActorType(name = "MyActor")
- public static class MyActorImpl extends AbstractActor implements MyActor, Remindable {
-
- private int timeCount = 0;
-
- @Override
- public String say(String something) {
- return executeSayMethod(something);
- }
-
- @Override
- public int getCount() {
- return this.timeCount;
- }
-
- @Override
- public void incrementCount(int delta) {
- this.timeCount = timeCount + delta;
- }
-
- @Override
- public void throwsException() {
- throw new IllegalArgumentException();
- }
-
- @Override
- public Mono throwsExceptionHotMono() {
- throw new IllegalArgumentException();
- }
-
- @Override
- public Mono throwsExceptionMono() {
- return Mono.error(new IllegalArgumentException());
- }
-
- public MyActorImpl(ActorRuntimeContext runtimeContext, ActorId id) {
- super(runtimeContext, id);
- super.registerActorTimer(
- "count",
- "incrementCount",
- 2,
- Duration.ofSeconds(1),
- Duration.ofSeconds(1)
- ).block();
- }
-
- @Override
- public TypeRef getStateType() {
- return TypeRef.STRING;
- }
-
- @Override
- public Mono receiveReminder(String reminderName, String state, Duration dueTime, Duration period) {
- return Mono.empty();
- }
- }
-
- private ActorRuntimeContext context = createContext(MyActorImpl.class);
-
- private ActorManager manager = new ActorManager<>(context);
-
- @Test(expected = IllegalArgumentException.class)
- public void invokeBeforeActivate() throws Exception {
- ActorId actorId = newActorId();
- String message = "something";
- this.manager.invokeMethod(actorId, "say", message.getBytes()).block();
- }
-
- @Test
- public void activateThenInvoke() throws Exception {
- ActorId actorId = newActorId();
- byte[] message = this.context.getObjectSerializer().serialize("something");
- this.manager.activateActor(actorId).block();
- byte[] response = this.manager.invokeMethod(actorId, "say", message).block();
- Assert.assertEquals(executeSayMethod(
- this.context.getObjectSerializer().deserialize(message, TypeRef.STRING)),
- this.context.getObjectSerializer().deserialize(response, TypeRef.STRING));
- }
-
- @Test
- public void activateThenInvokeWithActorImplException() throws Exception {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
-
- Assertions.assertThrows(RuntimeException.class, () -> {
- this.manager.invokeMethod(actorId, "throwsException", null).block();
- });
- }
-
- @Test
- public void activateThenInvokeWithActorImplExceptionButNotSubscribed() throws Exception {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
-
- // Nothing happens because we don't call block().
- this.manager.invokeMethod(actorId, "throwsException", null);
- }
-
- @Test
- public void activateThenInvokeWithActorImplHotMonoException() throws Exception {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
-
- Assertions.assertThrows(RuntimeException.class, () -> {
- this.manager.invokeMethod(actorId, "throwsExceptionHotMono", null).block();
- });
- }
-
- @Test
- public void activateThenInvokeWithActorImplHotMonoExceptionNotSubscribed() throws Exception {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
-
- // Nothing happens because we don't call block().
- this.manager.invokeMethod(actorId, "throwsExceptionHotMono", null);
- }
-
- @Test
- public void activateThenInvokeWithActorImplMonoException() throws Exception {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
-
- Assertions.assertThrows(RuntimeException.class, () -> {
- this.manager.invokeMethod(actorId, "throwsExceptionMono", null).block();
- });
- }
-
- @Test
- public void activateThenInvokeWithActorImplMonoExceptionNotSubscribed() throws Exception {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
-
- // Nothing happens because we don't call block().
- this.manager.invokeMethod(actorId, "throwsExceptionMono", null);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void activateInvokeDeactivateThenInvoke() throws Exception {
- ActorId actorId = newActorId();
- byte[] message = this.context.getObjectSerializer().serialize("something");
- this.manager.activateActor(actorId).block();
- byte[] response = this.manager.invokeMethod(actorId, "say", message).block();
- Assert.assertEquals(executeSayMethod(
- this.context.getObjectSerializer().deserialize(message, TypeRef.STRING)),
- this.context.getObjectSerializer().deserialize(response, TypeRef.STRING));
-
- this.manager.deactivateActor(actorId).block();
- this.manager.invokeMethod(actorId, "say", message).block();
- }
-
- @Test
- public void invokeReminderNotRemindable() throws Exception {
- ActorId actorId = newActorId();
- ActorRuntimeContext context = createContext(NotRemindableActor.class);
- ActorManager manager = new ActorManager<>(context);
- manager.invokeReminder(actorId, "myremind", createReminderParams("hello")).block();
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void invokeReminderBeforeActivate() throws Exception {
- ActorId actorId = newActorId();
- this.manager.invokeReminder(actorId, "myremind", createReminderParams("hello")).block();
- }
-
- @Test
- public void activateThenInvokeReminder() throws Exception {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
- this.manager.invokeReminder(actorId, "myremind", createReminderParams("hello")).block();
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void activateDeactivateThenInvokeReminder() throws Exception {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
- this.manager.deactivateActor(actorId).block();;
- this.manager.invokeReminder(actorId, "myremind", createReminderParams("hello")).block();
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void invokeTimerBeforeActivate() throws IOException {
- ActorId actorId = newActorId();
- this.manager.invokeTimer(actorId, "count", createTimerParams("incrementCount", 2)).block();
- }
-
- @Test
- public void activateThenInvokeTimerBeforeRegister() throws IOException {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
- this.manager.invokeTimer(actorId, "unknown", createTimerParams("incrementCount", 2)).block();
- }
-
- @Test
- public void activateThenInvokeTimer() throws IOException {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
- this.manager.invokeTimer(actorId, "count", createTimerParams("incrementCount", 2)).block();
- byte[] response = this.manager.invokeMethod(actorId, "getCount", null).block();
- Assert.assertEquals("2", new String(response));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void activateInvokeTimerDeactivateThenInvokeTimer() throws IOException {
- ActorId actorId = newActorId();
- this.manager.activateActor(actorId).block();
- this.manager.invokeTimer(actorId, "count", createTimerParams("incrementCount", 2)).block();
- byte[] response = this.manager.invokeMethod(actorId, "getCount", null).block();
- Assert.assertEquals("2", new String(response));
-
- this.manager.deactivateActor(actorId).block();
- this.manager.invokeTimer(actorId, "count", createTimerParams("incrementCount", 2)).block();
- }
-
- private byte[] createReminderParams(String data) throws IOException {
- byte[] serializedData = this.context.getObjectSerializer().serialize(data);
- ActorReminderParams p = new ActorReminderParams(serializedData, Duration.ofSeconds(1), Duration.ofSeconds(1));
- return INTERNAL_SERIALIZER.serialize(p);
- }
-
- private byte[] createTimerParams(String callback, Object data) throws IOException {
- byte[] serializedData = this.context.getObjectSerializer().serialize(data);
- ActorTimerParams p = new ActorTimerParams(callback, serializedData, Duration.ofSeconds(1), Duration.ofSeconds(1));
- return INTERNAL_SERIALIZER.serialize(p);
- }
-
- private static ActorId newActorId() {
- return new ActorId(Integer.toString(ACTOR_ID_COUNT.incrementAndGet()));
- }
-
- private static String executeSayMethod(String something) {
- return "Said: " + (something == null ? "" : something);
- }
-
- private static ActorRuntimeContext createContext(Class clazz) {
- DaprClient daprClient = mock(DaprClient.class);
-
- when(daprClient.registerTimer(any(), any(), any(), any())).thenReturn(Mono.empty());
- when(daprClient.registerReminder(any(), any(), any(), any())).thenReturn(Mono.empty());
- when(daprClient.unregisterTimer(any(), any(), any())).thenReturn(Mono.empty());
- when(daprClient.unregisterReminder(any(), any(), any())).thenReturn(Mono.empty());
-
- return new ActorRuntimeContext(
- mock(ActorRuntime.class),
- new DefaultObjectSerializer(),
- new DefaultActorFactory(),
- ActorTypeInformation.create(clazz),
- daprClient,
- mock(DaprStateAsyncProvider.class)
- );
- }
-}
+/*
+ * Copyright 2021 The Dapr Authors
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package io.dapr.actors.runtime;
+
+import io.dapr.actors.ActorId;
+import io.dapr.actors.ActorType;
+import io.dapr.serializer.DefaultObjectSerializer;
+import io.dapr.utils.TypeRef;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Assertions;
+import reactor.core.publisher.Mono;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.concurrent.atomic.AtomicInteger;
+
+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;
+
+/**
+ * Unit tests for Actor Manager
+ */
+public class ActorManagerTest {
+
+ private static final ActorObjectSerializer INTERNAL_SERIALIZER = new ActorObjectSerializer();
+
+ private static final AtomicInteger ACTOR_ID_COUNT = new AtomicInteger();
+
+ interface MyActor {
+ String say(String something);
+
+ int getCount();
+
+ void incrementCount(int delta);
+
+ void throwsException();
+
+ Mono throwsExceptionHotMono();
+
+ Mono throwsExceptionMono();
+ }
+
+ public static class NotRemindableActor extends AbstractActor {
+ public NotRemindableActor(ActorRuntimeContext runtimeContext, ActorId id) {
+ super(runtimeContext, id);
+ }
+ }
+
+ @ActorType(name = "MyActor")
+ public static class MyActorImpl extends AbstractActor implements MyActor, Remindable {
+
+ private int timeCount = 0;
+
+ @Override
+ public String say(String something) {
+ return executeSayMethod(something);
+ }
+
+ @Override
+ public int getCount() {
+ return this.timeCount;
+ }
+
+ @Override
+ public void incrementCount(int delta) {
+ this.timeCount = timeCount + delta;
+ }
+
+ @Override
+ public void throwsException() {
+ throw new IllegalArgumentException();
+ }
+
+ @Override
+ public Mono throwsExceptionHotMono() {
+ throw new IllegalArgumentException();
+ }
+
+ @Override
+ public Mono throwsExceptionMono() {
+ return Mono.error(new IllegalArgumentException());
+ }
+
+ public MyActorImpl(ActorRuntimeContext runtimeContext, ActorId id) {
+ super(runtimeContext, id);
+ super.registerActorTimer(
+ "count",
+ "incrementCount",
+ 2,
+ Duration.ofSeconds(1),
+ Duration.ofSeconds(1)
+ ).block();
+ }
+
+ @Override
+ public TypeRef getStateType() {
+ return TypeRef.STRING;
+ }
+
+ @Override
+ public Mono receiveReminder(String reminderName, String state, Duration dueTime, Duration period) {
+ return Mono.empty();
+ }
+ }
+
+ private ActorRuntimeContext context = createContext(MyActorImpl.class);
+
+ private ActorManager manager = new ActorManager<>(context);
+
+ @Test
+ public void invokeBeforeActivate() throws Exception {
+ ActorId actorId = newActorId();
+ String message = "something";
+
+ assertThrows(IllegalArgumentException.class, () ->
+ this.manager.invokeMethod(actorId, "say", message.getBytes()).block());
+ }
+
+ @Test
+ public void activateThenInvoke() throws Exception {
+ ActorId actorId = newActorId();
+ byte[] message = this.context.getObjectSerializer().serialize("something");
+ this.manager.activateActor(actorId).block();
+ byte[] response = this.manager.invokeMethod(actorId, "say", message).block();
+ Assertions.assertEquals(executeSayMethod(
+ this.context.getObjectSerializer().deserialize(message, TypeRef.STRING)),
+ this.context.getObjectSerializer().deserialize(response, TypeRef.STRING));
+ }
+
+ @Test
+ public void activateThenInvokeWithActorImplException() throws Exception {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+
+ assertThrows(RuntimeException.class, () -> {
+ this.manager.invokeMethod(actorId, "throwsException", null).block();
+ });
+ }
+
+ @Test
+ public void activateThenInvokeWithActorImplExceptionButNotSubscribed() throws Exception {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+
+ // Nothing happens because we don't call block().
+ this.manager.invokeMethod(actorId, "throwsException", null);
+ }
+
+ @Test
+ public void activateThenInvokeWithActorImplHotMonoException() throws Exception {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+
+ assertThrows(RuntimeException.class, () -> {
+ this.manager.invokeMethod(actorId, "throwsExceptionHotMono", null).block();
+ });
+ }
+
+ @Test
+ public void activateThenInvokeWithActorImplHotMonoExceptionNotSubscribed() throws Exception {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+
+ // Nothing happens because we don't call block().
+ this.manager.invokeMethod(actorId, "throwsExceptionHotMono", null);
+ }
+
+ @Test
+ public void activateThenInvokeWithActorImplMonoException() throws Exception {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+
+ assertThrows(RuntimeException.class, () -> {
+ this.manager.invokeMethod(actorId, "throwsExceptionMono", null).block();
+ });
+ }
+
+ @Test
+ public void activateThenInvokeWithActorImplMonoExceptionNotSubscribed() throws Exception {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+
+ // Nothing happens because we don't call block().
+ this.manager.invokeMethod(actorId, "throwsExceptionMono", null);
+ }
+
+ @Test
+ public void activateInvokeDeactivateThenInvoke() throws Exception {
+ ActorId actorId = newActorId();
+ byte[] message = this.context.getObjectSerializer().serialize("something");
+ this.manager.activateActor(actorId).block();
+ byte[] response = this.manager.invokeMethod(actorId, "say", message).block();
+ Assertions.assertEquals(executeSayMethod(
+ this.context.getObjectSerializer().deserialize(message, TypeRef.STRING)),
+ this.context.getObjectSerializer().deserialize(response, TypeRef.STRING));
+
+ this.manager.deactivateActor(actorId).block();
+ assertThrows(IllegalArgumentException.class, () ->
+ this.manager.invokeMethod(actorId, "say", message).block());
+ }
+
+ @Test
+ public void invokeReminderNotRemindable() throws Exception {
+ ActorId actorId = newActorId();
+ ActorRuntimeContext context = createContext(NotRemindableActor.class);
+ ActorManager manager = new ActorManager<>(context);
+ manager.invokeReminder(actorId, "myremind", createReminderParams("hello")).block();
+ }
+
+ @Test
+ public void invokeReminderBeforeActivate() throws Exception {
+ ActorId actorId = newActorId();
+ assertThrows(IllegalArgumentException.class, () ->
+ this.manager.invokeReminder(actorId, "myremind", createReminderParams("hello")).block());
+ }
+
+ @Test
+ public void activateThenInvokeReminder() throws Exception {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+ this.manager.invokeReminder(actorId, "myremind", createReminderParams("hello")).block();
+ }
+
+ @Test
+ public void activateDeactivateThenInvokeReminder() throws Exception {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+ this.manager.deactivateActor(actorId).block();;
+
+ assertThrows(IllegalArgumentException.class, () -> this.manager.invokeReminder(actorId, "myremind", createReminderParams("hello")).block());
+ }
+
+ @Test
+ public void invokeTimerBeforeActivate() throws IOException {
+ ActorId actorId = newActorId();
+
+ assertThrows(IllegalArgumentException.class, () ->
+ this.manager.invokeTimer(actorId, "count", createTimerParams("incrementCount", 2)).block());
+ }
+
+ @Test
+ public void activateThenInvokeTimerBeforeRegister() throws IOException {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+ this.manager.invokeTimer(actorId, "unknown", createTimerParams("incrementCount", 2)).block();
+ }
+
+ @Test
+ public void activateThenInvokeTimer() throws IOException {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+ this.manager.invokeTimer(actorId, "count", createTimerParams("incrementCount", 2)).block();
+ byte[] response = this.manager.invokeMethod(actorId, "getCount", null).block();
+ Assertions.assertEquals("2", new String(response));
+ }
+
+ @Test
+ public void activateInvokeTimerDeactivateThenInvokeTimer() throws IOException {
+ ActorId actorId = newActorId();
+ this.manager.activateActor(actorId).block();
+ this.manager.invokeTimer(actorId, "count", createTimerParams("incrementCount", 2)).block();
+ byte[] response = this.manager.invokeMethod(actorId, "getCount", null).block();
+ Assertions.assertEquals("2", new String(response));
+
+ this.manager.deactivateActor(actorId).block();
+ assertThrows(IllegalArgumentException.class, () -> this.manager.invokeTimer(actorId, "count", createTimerParams("incrementCount", 2)).block());
+ }
+
+ private byte[] createReminderParams(String data) throws IOException {
+ byte[] serializedData = this.context.getObjectSerializer().serialize(data);
+ ActorReminderParams p = new ActorReminderParams(serializedData, Duration.ofSeconds(1), Duration.ofSeconds(1));
+ return INTERNAL_SERIALIZER.serialize(p);
+ }
+
+ private byte[] createTimerParams(String callback, Object data) throws IOException {
+ byte[] serializedData = this.context.getObjectSerializer().serialize(data);
+ ActorTimerParams p = new ActorTimerParams(callback, serializedData, Duration.ofSeconds(1), Duration.ofSeconds(1));
+ return INTERNAL_SERIALIZER.serialize(p);
+ }
+
+ private static ActorId newActorId() {
+ return new ActorId(Integer.toString(ACTOR_ID_COUNT.incrementAndGet()));
+ }
+
+ private static String executeSayMethod(String something) {
+ return "Said: " + (something == null ? "" : something);
+ }
+
+ private static ActorRuntimeContext createContext(Class clazz) {
+ DaprClient daprClient = mock(DaprClient.class);
+
+ when(daprClient.registerTimer(any(), any(), any(), any())).thenReturn(Mono.empty());
+ when(daprClient.registerReminder(any(), any(), any(), any())).thenReturn(Mono.empty());
+ when(daprClient.unregisterTimer(any(), any(), any())).thenReturn(Mono.empty());
+ when(daprClient.unregisterReminder(any(), any(), any())).thenReturn(Mono.empty());
+
+ return new ActorRuntimeContext(
+ mock(ActorRuntime.class),
+ new DefaultObjectSerializer(),
+ new DefaultActorFactory(),
+ ActorTypeInformation.create(clazz),
+ daprClient,
+ mock(DaprStateAsyncProvider.class)
+ );
+ }
+}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorMethodInfoMapTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorMethodInfoMapTest.java
index 5aec6b9b0..b08d5a148 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorMethodInfoMapTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorMethodInfoMapTest.java
@@ -13,13 +13,15 @@ limitations under the License.
package io.dapr.actors.runtime;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* Unit tests for ActorMethodInfoMap.
*/
@@ -33,23 +35,24 @@ public class ActorMethodInfoMapTest {
try {
Method m1 = m.get("getData");
- Assert.assertEquals("getData", m1.getName());
+ Assertions.assertEquals("getData", m1.getName());
Class c = m1.getReturnType();
- Assert.assertEquals(c.getClass(), String.class.getClass());
+ Assertions.assertEquals(c.getClass(), String.class.getClass());
Parameter[] p = m1.getParameters();
- Assert.assertEquals(p[0].getType().getClass(), String.class.getClass());
+ Assertions.assertEquals(p[0].getType().getClass(), String.class.getClass());
} catch (Exception e) {
- Assert.fail("Exception not expected.");
+ Assertions.fail("Exception not expected.");
}
}
- @Test(expected = NoSuchMethodException.class)
+ @Test
public void lookUpNonExistingMethod() throws NoSuchMethodException {
ArrayList> interfaceTypes = new ArrayList<>();
interfaceTypes.add(TestActor.class);
ActorMethodInfoMap m = new ActorMethodInfoMap(interfaceTypes);
- m.get("thisMethodDoesNotExist");
+ assertThrows(NoSuchMethodException.class, () ->
+ m.get("thisMethodDoesNotExist"));
}
/**
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorNoStateTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorNoStateTest.java
index f74fc3d28..4a6a5fc39 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorNoStateTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorNoStateTest.java
@@ -20,14 +20,15 @@ import io.dapr.actors.client.ActorProxy;
import io.dapr.actors.client.ActorProxyImplForTests;
import io.dapr.actors.client.DaprClientStub;
import io.dapr.serializer.DefaultObjectSerializer;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import java.lang.reflect.Proxy;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -153,7 +154,7 @@ public class ActorNoStateTest {
public void actorId() {
ActorProxy proxy = createActorProxy();
- Assert.assertEquals(
+ Assertions.assertEquals(
proxy.getActorId().toString(),
proxy.invokeMethod("getMyId", String.class).block());
}
@@ -163,7 +164,7 @@ public class ActorNoStateTest {
ActorProxy proxy = createActorProxy();
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
- Assert.assertEquals(
+ Assertions.assertEquals(
"abcabc",
proxy.invokeMethod("stringInStringOut", "abc", String.class).block());
}
@@ -173,21 +174,22 @@ public class ActorNoStateTest {
ActorProxy proxy = createActorProxy();
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
- Assert.assertEquals(
+ Assertions.assertEquals(
false,
proxy.invokeMethod("stringInBooleanOut", "hello world", Boolean.class).block());
- Assert.assertEquals(
+ Assertions.assertEquals(
true,
proxy.invokeMethod("stringInBooleanOut", "true", Boolean.class).block());
}
- @Test(expected = IllegalMonitorStateException.class)
+ @Test
public void stringInVoidOutIntentionallyThrows() {
ActorProxy actorProxy = createActorProxy();
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
- actorProxy.invokeMethod("stringInVoidOutIntentionallyThrows", "hello world").block();
+ assertThrows(IllegalMonitorStateException.class, () ->
+ actorProxy.invokeMethod("stringInVoidOutIntentionallyThrows", "hello world").block());
}
@Test
@@ -204,30 +206,31 @@ public class ActorNoStateTest {
// this should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
MyData response = actorProxy.invokeMethod("classInClassOut", d, MyData.class).block();
- Assert.assertEquals(
+ Assertions.assertEquals(
"hihi",
response.getName());
- Assert.assertEquals(
+ Assertions.assertEquals(
6,
response.getNum());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testBadTimerCallbackName() {
MyActor actor = createActorProxy(MyActor.class);
- actor.registerBadCallbackName().block();
+
+ assertThrows(IllegalArgumentException.class, () -> actor.registerBadCallbackName().block());
}
@Test
public void testAutoTimerName() {
MyActor actor = createActorProxy(MyActor.class);
String firstTimer = actor.registerTimerAutoName();
- Assert.assertTrue((firstTimer != null) && !firstTimer.isEmpty());
+ Assertions.assertTrue((firstTimer != null) && !firstTimer.isEmpty());
String secondTimer = actor.registerTimerAutoName();
- Assert.assertTrue((secondTimer != null) && !secondTimer.isEmpty());
+ Assertions.assertTrue((secondTimer != null) && !secondTimer.isEmpty());
- Assert.assertNotEquals(firstTimer, secondTimer);
+ Assertions.assertNotEquals(firstTimer, secondTimer);
}
private static ActorId newActorId() {
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorReminderParamsTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorReminderParamsTest.java
index 41a30024c..30b210db7 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorReminderParamsTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorReminderParamsTest.java
@@ -13,18 +13,20 @@ limitations under the License.
package io.dapr.actors.runtime;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
public class ActorReminderParamsTest {
private static final ActorObjectSerializer SERIALIZER = new ActorObjectSerializer();
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void outOfRangeDueTime() {
- ActorReminderParams info = new ActorReminderParams(null, Duration.ZERO.plusSeconds(-10), Duration.ZERO.plusMinutes(1));
+ assertThrows(IllegalArgumentException.class, () -> new ActorReminderParams(null, Duration.ZERO.plusSeconds(-10), Duration.ZERO.plusMinutes(1)));
}
@Test
@@ -33,9 +35,9 @@ public class ActorReminderParamsTest {
ActorReminderParams info = new ActorReminderParams(null, Duration.ZERO.plusMinutes(1), Duration.ZERO.plusMillis(-1));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void outOfRangePeriod() {
- ActorReminderParams info = new ActorReminderParams(null, Duration.ZERO.plusMinutes(1), Duration.ZERO.plusMinutes(-10));
+ assertThrows(IllegalArgumentException.class, () ->new ActorReminderParams(null, Duration.ZERO.plusMinutes(1), Duration.ZERO.plusMinutes(-10)));
}
@Test
@@ -48,12 +50,12 @@ public class ActorReminderParamsTest {
}
catch(Exception e) {
System.out.println("The error is: " + e);
- Assert.fail();
+ Assertions.fail();
}
- Assert.assertArrayEquals(original.getData(), recreated.getData());
- Assert.assertEquals(original.getDueTime(), recreated.getDueTime());
- Assert.assertEquals(original.getPeriod(), recreated.getPeriod());
+ Assertions.assertArrayEquals(original.getData(), recreated.getData());
+ Assertions.assertEquals(original.getDueTime(), recreated.getDueTime());
+ Assertions.assertEquals(original.getPeriod(), recreated.getPeriod());
}
@Test
@@ -66,11 +68,11 @@ public class ActorReminderParamsTest {
}
catch(Exception e) {
System.out.println("The error is: " + e);
- Assert.fail();
+ Assertions.fail();
}
- Assert.assertArrayEquals(original.getData(), recreated.getData());
- Assert.assertEquals(original.getDueTime(), recreated.getDueTime());
- Assert.assertEquals(original.getPeriod(), recreated.getPeriod());
+ Assertions.assertArrayEquals(original.getData(), recreated.getData());
+ Assertions.assertEquals(original.getDueTime(), recreated.getDueTime());
+ Assertions.assertEquals(original.getPeriod(), recreated.getPeriod());
}
}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorRuntimeTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorRuntimeTest.java
index 338288daf..62132c9f2 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorRuntimeTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorRuntimeTest.java
@@ -1,236 +1,237 @@
-/*
- * Copyright 2021 The Dapr Authors
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package io.dapr.actors.runtime;
-
-import io.dapr.actors.ActorId;
-import io.dapr.actors.ActorType;
-import io.dapr.serializer.DefaultObjectSerializer;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import reactor.core.publisher.Mono;
-
-import java.lang.reflect.Constructor;
-import java.time.Duration;
-import java.util.Arrays;
-import java.util.UUID;
-
-import static org.mockito.Mockito.mock;
-
-public class ActorRuntimeTest {
-
- private static final String ACTOR_NAME = "MyGreatActor";
-
- public interface MyActor {
- String say();
-
- int count();
- }
-
- @ActorType(name = ACTOR_NAME)
- public static class MyActorImpl extends AbstractActor implements MyActor {
-
- private int count = 0;
-
- private Boolean activated;
-
- public MyActorImpl(ActorRuntimeContext runtimeContext, ActorId id) {
- super(runtimeContext, id);
- }
-
- public Mono onActivate() {
- return Mono.fromRunnable(() -> {
- if (this.activated != null) {
- throw new IllegalStateException("already activated once");
- }
-
- this.activated = true;
- });
- }
-
- public Mono onDeactivate() {
- return Mono.fromRunnable(() -> {
- if (this.activated == null) {
- throw new IllegalStateException("never activated");
- }
-
- if (this.activated == false) {
- throw new IllegalStateException("already deactivated");
- }
-
- if (this.count == 0) {
- throw new IllegalStateException("test expects a call before deactivate");
- }
-
- this.activated = false;
- });
- }
-
- public String say() {
- if (!this.activated) {
- throw new IllegalStateException("not activated");
- }
-
- this.count++;
- return "Nothing to say.";
- }
-
- public int count() {
- return this.count;
- }
- }
-
- private static final ActorObjectSerializer ACTOR_STATE_SERIALIZER = new ActorObjectSerializer();
-
- private static Constructor constructor;
-
- private DaprClient mockDaprClient;
-
- private ActorRuntime runtime;
-
- @BeforeClass
- public static void beforeAll() throws Exception {
- constructor =
- (Constructor) Arrays.stream(ActorRuntime.class.getDeclaredConstructors())
- .filter(c -> c.getParameters().length == 2).map(c -> {
- c.setAccessible(true);
- return c;
- }).findFirst().get();
- }
-
- @Before
- public void setup() throws Exception {
- this.mockDaprClient = mock(DaprClient.class);
- this.runtime = constructor.newInstance(null, this.mockDaprClient);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void registerActorNullClass() {
- this.runtime.registerActor(null);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void registerActorNullFactory() {
- this.runtime.registerActor(MyActorImpl.class, null, new DefaultObjectSerializer(),
- new DefaultObjectSerializer());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void registerActorNullSerializer() {
- this.runtime.registerActor(MyActorImpl.class, new DefaultActorFactory<>(), null,
- new DefaultObjectSerializer());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void registerActorNullStateSerializer() {
- this.runtime.registerActor(MyActorImpl.class, new DefaultActorFactory<>(),
- new DefaultObjectSerializer(), null);
- }
-
- @Test
- public void setActorIdleTimeout() throws Exception {
- this.runtime.getConfig().setActorIdleTimeout(Duration.ofSeconds(123));
- Assert.assertEquals("{\"entities\":[],\"actorIdleTimeout\":\"0h2m3s0ms\"}",
- new String(this.runtime.serializeConfig()));
- }
-
- @Test
- public void setActorScanInterval() throws Exception {
- this.runtime.getConfig().setActorScanInterval(Duration.ofSeconds(123));
- Assert.assertEquals("{\"entities\":[],\"actorScanInterval\":\"0h2m3s0ms\"}",
- new String(this.runtime.serializeConfig()));
- }
-
- @Test
- public void setDrainBalancedActors() throws Exception {
- this.runtime.getConfig().setDrainBalancedActors(true);
- Assert.assertEquals("{\"entities\":[],\"drainBalancedActors\":true}",
- new String(this.runtime.serializeConfig()));
- }
-
- @Test
- public void setDrainOngoingCallTimeout() throws Exception {
- this.runtime.getConfig().setDrainOngoingCallTimeout(Duration.ofSeconds(123));
- Assert.assertEquals("{\"entities\":[],\"drainOngoingCallTimeout\":\"0h2m3s0ms\"}",
- new String(this.runtime.serializeConfig()));
- }
-
- @Test
- public void setRemindersStoragePartitions() throws Exception {
- this.runtime.getConfig().setRemindersStoragePartitions(12);
- Assert.assertEquals("{\"entities\":[],\"remindersStoragePartitions\":12}",
- new String(this.runtime.serializeConfig()));
- }
-
- @Test
- public void invokeActor() throws Exception {
- String actorId = UUID.randomUUID().toString();
- this.runtime.registerActor(MyActorImpl.class);
-
- byte[] response = this.runtime.invoke(ACTOR_NAME, actorId, "say", null).block();
- String message = ACTOR_STATE_SERIALIZER.deserialize(response, String.class);
- Assert.assertEquals("Nothing to say.", message);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void invokeUnknownActor() {
- String actorId = UUID.randomUUID().toString();
- this.runtime.registerActor(MyActorImpl.class);
-
- this.runtime.invoke("UnknownActor", actorId, "say", null).block();
- }
-
- @Test
- public void deactivateActor() throws Exception {
- String actorId = UUID.randomUUID().toString();
- this.runtime.registerActor(MyActorImpl.class);
- this.runtime.deactivate(ACTOR_NAME, actorId).block();
- }
-
- @Test
- public void lazyDeactivate() throws Exception {
- String actorId = UUID.randomUUID().toString();
- this.runtime.registerActor(MyActorImpl.class);
-
- Mono deactivateCall = this.runtime.deactivate(ACTOR_NAME, actorId);
-
- this.runtime.invoke(ACTOR_NAME, actorId, "say", null).block();
-
- deactivateCall.block();
-
- this.runtime.invoke(ACTOR_NAME, actorId, "say", null)
- .doOnError(e -> Assert.assertTrue(e.getMessage().contains("Could not find actor")))
- .doOnSuccess(s -> Assert.fail()).onErrorReturn("".getBytes()).block();
- }
-
- @Test
- public void lazyInvoke() throws Exception {
- String actorId = UUID.randomUUID().toString();
- this.runtime.registerActor(MyActorImpl.class, new DefaultActorFactory<>());
-
- Mono invokeCall = this.runtime.invoke(ACTOR_NAME, actorId, "say", null);
-
- byte[] response = this.runtime.invoke(ACTOR_NAME, actorId, "count", null).block();
- int count = ACTOR_STATE_SERIALIZER.deserialize(response, Integer.class);
- Assert.assertEquals(0, count);
-
- invokeCall.block();
-
- response = this.runtime.invoke(ACTOR_NAME, actorId, "count", null).block();
- count = ACTOR_STATE_SERIALIZER.deserialize(response, Integer.class);
- Assert.assertEquals(1, count);
- }
-
-}
+/*
+ * Copyright 2021 The Dapr Authors
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package io.dapr.actors.runtime;
+
+import io.dapr.actors.ActorId;
+import io.dapr.actors.ActorType;
+import io.dapr.serializer.DefaultObjectSerializer;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Mono;
+
+import java.lang.reflect.Constructor;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.UUID;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+
+public class ActorRuntimeTest {
+
+ private static final String ACTOR_NAME = "MyGreatActor";
+
+ public interface MyActor {
+ String say();
+
+ int count();
+ }
+
+ @ActorType(name = ACTOR_NAME)
+ public static class MyActorImpl extends AbstractActor implements MyActor {
+
+ private int count = 0;
+
+ private Boolean activated;
+
+ public MyActorImpl(ActorRuntimeContext runtimeContext, ActorId id) {
+ super(runtimeContext, id);
+ }
+
+ public Mono onActivate() {
+ return Mono.fromRunnable(() -> {
+ if (this.activated != null) {
+ throw new IllegalStateException("already activated once");
+ }
+
+ this.activated = true;
+ });
+ }
+
+ public Mono onDeactivate() {
+ return Mono.fromRunnable(() -> {
+ if (this.activated == null) {
+ throw new IllegalStateException("never activated");
+ }
+
+ if (this.activated == false) {
+ throw new IllegalStateException("already deactivated");
+ }
+
+ if (this.count == 0) {
+ throw new IllegalStateException("test expects a call before deactivate");
+ }
+
+ this.activated = false;
+ });
+ }
+
+ public String say() {
+ if (!this.activated) {
+ throw new IllegalStateException("not activated");
+ }
+
+ this.count++;
+ return "Nothing to say.";
+ }
+
+ public int count() {
+ return this.count;
+ }
+ }
+
+ private static final ActorObjectSerializer ACTOR_STATE_SERIALIZER = new ActorObjectSerializer();
+
+ private static Constructor constructor;
+
+ private DaprClient mockDaprClient;
+
+ private ActorRuntime runtime;
+
+ @BeforeAll
+ public static void beforeAll() throws Exception {
+ constructor =
+ (Constructor) Arrays.stream(ActorRuntime.class.getDeclaredConstructors())
+ .filter(c -> c.getParameters().length == 2).map(c -> {
+ c.setAccessible(true);
+ return c;
+ }).findFirst().get();
+ }
+
+ @BeforeEach
+ public void setup() throws Exception {
+ this.mockDaprClient = mock(DaprClient.class);
+ this.runtime = constructor.newInstance(null, this.mockDaprClient);
+ }
+
+ @Test
+ public void registerActorNullClass() {
+ assertThrows(IllegalArgumentException.class, () -> this.runtime.registerActor(null));
+ }
+
+ @Test
+ public void registerActorNullFactory() {
+ assertThrows(IllegalArgumentException.class, () -> this.runtime.registerActor(MyActorImpl.class, null, new DefaultObjectSerializer(),
+ new DefaultObjectSerializer()));
+ }
+
+ @Test
+ public void registerActorNullSerializer() {
+ assertThrows(IllegalArgumentException.class, () -> this.runtime.registerActor(MyActorImpl.class, new DefaultActorFactory<>(), null,
+ new DefaultObjectSerializer()));
+ }
+
+ @Test
+ public void registerActorNullStateSerializer() {
+ assertThrows(IllegalArgumentException.class, () -> this.runtime.registerActor(MyActorImpl.class, new DefaultActorFactory<>(),
+ new DefaultObjectSerializer(), null));
+ }
+
+ @Test
+ public void setActorIdleTimeout() throws Exception {
+ this.runtime.getConfig().setActorIdleTimeout(Duration.ofSeconds(123));
+ Assertions.assertEquals("{\"entities\":[],\"actorIdleTimeout\":\"0h2m3s0ms\"}",
+ new String(this.runtime.serializeConfig()));
+ }
+
+ @Test
+ public void setActorScanInterval() throws Exception {
+ this.runtime.getConfig().setActorScanInterval(Duration.ofSeconds(123));
+ Assertions.assertEquals("{\"entities\":[],\"actorScanInterval\":\"0h2m3s0ms\"}",
+ new String(this.runtime.serializeConfig()));
+ }
+
+ @Test
+ public void setDrainBalancedActors() throws Exception {
+ this.runtime.getConfig().setDrainBalancedActors(true);
+ Assertions.assertEquals("{\"entities\":[],\"drainBalancedActors\":true}",
+ new String(this.runtime.serializeConfig()));
+ }
+
+ @Test
+ public void setDrainOngoingCallTimeout() throws Exception {
+ this.runtime.getConfig().setDrainOngoingCallTimeout(Duration.ofSeconds(123));
+ Assertions.assertEquals("{\"entities\":[],\"drainOngoingCallTimeout\":\"0h2m3s0ms\"}",
+ new String(this.runtime.serializeConfig()));
+ }
+
+ @Test
+ public void setRemindersStoragePartitions() throws Exception {
+ this.runtime.getConfig().setRemindersStoragePartitions(12);
+ Assertions.assertEquals("{\"entities\":[],\"remindersStoragePartitions\":12}",
+ new String(this.runtime.serializeConfig()));
+ }
+
+ @Test
+ public void invokeActor() throws Exception {
+ String actorId = UUID.randomUUID().toString();
+ this.runtime.registerActor(MyActorImpl.class);
+
+ byte[] response = this.runtime.invoke(ACTOR_NAME, actorId, "say", null).block();
+ String message = ACTOR_STATE_SERIALIZER.deserialize(response, String.class);
+ Assertions.assertEquals("Nothing to say.", message);
+ }
+
+ @Test
+ public void invokeUnknownActor() {
+ String actorId = UUID.randomUUID().toString();
+ this.runtime.registerActor(MyActorImpl.class);
+
+ assertThrows(IllegalArgumentException.class, () -> this.runtime.invoke("UnknownActor", actorId, "say", null).block());
+ }
+
+ @Test
+ public void deactivateActor() throws Exception {
+ String actorId = UUID.randomUUID().toString();
+ this.runtime.registerActor(MyActorImpl.class);
+ this.runtime.deactivate(ACTOR_NAME, actorId).block();
+ }
+
+ @Test
+ public void lazyDeactivate() throws Exception {
+ String actorId = UUID.randomUUID().toString();
+ this.runtime.registerActor(MyActorImpl.class);
+
+ Mono deactivateCall = this.runtime.deactivate(ACTOR_NAME, actorId);
+
+ this.runtime.invoke(ACTOR_NAME, actorId, "say", null).block();
+
+ deactivateCall.block();
+
+ this.runtime.invoke(ACTOR_NAME, actorId, "say", null)
+ .doOnError(e -> Assertions.assertTrue(e.getMessage().contains("Could not find actor")))
+ .doOnSuccess(s -> Assertions.fail()).onErrorReturn("".getBytes()).block();
+ }
+
+ @Test
+ public void lazyInvoke() throws Exception {
+ String actorId = UUID.randomUUID().toString();
+ this.runtime.registerActor(MyActorImpl.class, new DefaultActorFactory<>());
+
+ Mono invokeCall = this.runtime.invoke(ACTOR_NAME, actorId, "say", null);
+
+ byte[] response = this.runtime.invoke(ACTOR_NAME, actorId, "count", null).block();
+ int count = ACTOR_STATE_SERIALIZER.deserialize(response, Integer.class);
+ Assertions.assertEquals(0, count);
+
+ invokeCall.block();
+
+ response = this.runtime.invoke(ACTOR_NAME, actorId, "count", null).block();
+ count = ACTOR_STATE_SERIALIZER.deserialize(response, Integer.class);
+ Assertions.assertEquals(1, count);
+ }
+
+}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorStatefulTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorStatefulTest.java
index 2bd9af958..88488d30c 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorStatefulTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorStatefulTest.java
@@ -1,669 +1,673 @@
-/*
- * Copyright 2021 The Dapr Authors
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package io.dapr.actors.runtime;
-
-import io.dapr.actors.ActorId;
-import io.dapr.actors.ActorType;
-import io.dapr.actors.client.ActorProxy;
-import io.dapr.actors.client.ActorProxyImplForTests;
-import io.dapr.actors.client.DaprClientStub;
-import io.dapr.serializer.DefaultObjectSerializer;
-import io.dapr.utils.TypeRef;
-import org.junit.Assert;
-import org.junit.Test;
-import reactor.core.publisher.Mono;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.nio.charset.IllegalCharsetNameException;
-import java.time.Duration;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class ActorStatefulTest {
-
- private static final ActorObjectSerializer INTERNAL_SERIALIZER = new ActorObjectSerializer();
-
- private static final AtomicInteger ACTOR_ID_COUNT = new AtomicInteger();
-
- private static final Collection DEACTIVATED_ACTOR_IDS = Collections.synchronizedList(new ArrayList<>());
-
- private final ActorRuntimeContext context = createContext();
-
- private ActorManager manager = new ActorManager<>(context);
-
- public interface MyActor {
- Mono isActive();
-
- MyMethodContext getPreCallMethodContext();
-
- MyMethodContext getPostCallMethodContext();
-
- Mono unregisterTimerAndReminder();
-
- Mono incrementAndGetCount(int increment) throws Exception;
-
- Mono getCountButThrowsException();
-
- Mono addMessage(String message);
-
- Mono setMessage(String message);
-
- Mono getMessage();
-
- Mono hasMessage();
-
- Mono deleteMessage();
-
- Mono forceDuplicateException();
-
- Mono forcePartialChange();
-
- Mono throwsWithoutSaving();
-
- Mono setMethodContext(MyMethodContext context);
-
- Mono getMethodContext();
-
- String getIdString();
- }
-
- @ActorType(name = "MyActor")
- public static class MyActorImpl extends AbstractActor implements MyActor, Remindable {
-
- private final ActorId id;
-
- private boolean activated;
-
- private MyMethodContext preMethodCalled;
-
- private MyMethodContext postMethodCalled;
-
- public MyActorImpl(ActorRuntimeContext runtimeContext, ActorId id) {
- super(runtimeContext, id);
- this.id = id;
- this.activated = true;
- }
-
- @Override
- public Mono isActive() {
- return Mono.fromSupplier(() -> this.activated);
- }
-
- @Override
- public Mono onActivate() {
- return Mono
- .fromRunnable(() -> this.activated = true)
- .then(super.registerActorTimer(
- "mytimer",
- "hasMessage",
- null,
- Duration.ofSeconds(1),
- Duration.ofSeconds(1)))
- .then(super.registerReminder(
- "myreminder",
- null,
- Duration.ofSeconds(1),
- Duration.ofSeconds(1)
- ));
- }
-
- @Override
- public Mono onDeactivate() {
- return Mono.fromRunnable(() -> DEACTIVATED_ACTOR_IDS.add(this.id.toString()));
- }
-
- @Override
- public Mono onPreActorMethod(ActorMethodContext context) {
- // Only keep the first one to make sure we can validate it via another method invocation.
- return Mono.fromRunnable(() -> {
- this.preMethodCalled = this.preMethodCalled != null ? this.preMethodCalled : new MyMethodContext()
- .setName(context.getMethodName())
- .setType(context.getCallType().toString());
- });
- }
-
- @Override
- public Mono onPostActorMethod(ActorMethodContext context) {
- // Only keep the first one to make sure we can validate it via another method invocation.
- return Mono.fromRunnable(() -> {
- this.postMethodCalled = this.postMethodCalled != null ? this.postMethodCalled : new MyMethodContext()
- .setName(context.getMethodName())
- .setType(context.getCallType().toString());
- });
- }
-
- @Override
- public MyMethodContext getPreCallMethodContext() {
- return this.preMethodCalled;
- }
-
- @Override
- public MyMethodContext getPostCallMethodContext() {
- return this.postMethodCalled;
- }
-
- @Override
- public Mono unregisterTimerAndReminder() {
- return super.unregisterReminder("UnknownReminder")
- .then(super.unregisterTimer("UnknownTimer"))
- .then(super.unregisterReminder("myreminder"))
- .then(super.unregisterTimer("mytimer"));
- }
-
- @Override
- public Mono incrementAndGetCount(int increment) {
- return Mono.fromRunnable(() -> {
- if (increment == 0) {
- // Artificial exception case for testing.
- throw new NumberFormatException("increment cannot be zero.");
- }
- })
- .then(super.getActorStateManager().contains("counter"))
- .flatMap(contains -> {
- if (!contains) {
- return Mono.just(0);
- }
-
- return super.getActorStateManager().get("counter", int.class);
- })
- .map(count -> count + increment)
- .flatMap(count -> super.getActorStateManager().set("counter", count).thenReturn(count));
- }
-
- @Override
- public Mono getCountButThrowsException() {
- return super.getActorStateManager().get("counter_WRONG_NAME", int.class);
- }
-
- @Override
- public Mono addMessage(String message) {
- return super.getActorStateManager().add("message", message);
- }
-
- @Override
- public Mono setMessage(String message) {
- return super.getActorStateManager().set("message", message).thenReturn(executeSayMethod(message));
- }
-
- @Override
- public Mono getMessage() {
- return super.getActorStateManager().get("message", String.class);
- }
-
- @Override
- public Mono hasMessage() {
- return super.getActorStateManager().contains("message");
- }
-
- @Override
- public Mono deleteMessage() {
- return super.getActorStateManager().remove("message");
- }
-
- @Override
- public Mono forceDuplicateException() {
- // Second add should throw exception.
- return super.getActorStateManager().add("message", "anything")
- .then(super.getActorStateManager().add("message", "something else"));
- }
-
- @Override
- public Mono forcePartialChange() {
- return super.getActorStateManager().add("message", "first message")
- .then(super.saveState())
- .then(super.getActorStateManager().add("message", "second message"));
- }
-
- @Override
- public Mono throwsWithoutSaving() {
- return super.getActorStateManager().add("message", "first message")
- .then(Mono.error(new IllegalCharsetNameException("random")));
- }
-
- @Override
- public Mono setMethodContext(MyMethodContext context) {
- return super.getActorStateManager().set("context", context);
- }
-
- @Override
- public Mono getMethodContext() {
- return super.getActorStateManager().get("context", MyMethodContext.class);
- }
-
- // Blocking methods are also supported for Actors. Mono is not required.
- @Override
- public String getIdString() {
- return this.id.toString();
- }
-
- @Override
- public TypeRef getStateType() {
- // Remindable type.
- return TypeRef.STRING;
- }
-
- @Override
- public Mono receiveReminder(String reminderName, String state, Duration dueTime, Duration period) {
- return Mono.empty();
- }
- }
-
- // Class used to validate serialization/deserialization
- public static class MyMethodContext implements Serializable {
-
- private String type;
-
- private String name;
-
- public String getType() {
- return type;
- }
-
- public MyMethodContext setType(String type) {
- this.type = type;
- return this;
- }
-
- public String getName() {
- return name;
- }
-
- public MyMethodContext setName(String name) {
- this.name = name;
- return this;
- }
- }
-
- @Test
- public void happyGetSetDeleteContains() {
- ActorProxy proxy = newActorProxy();
- Assert.assertEquals(
- proxy.getActorId().toString(), proxy.invokeMethod("getIdString", String.class).block());
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- proxy.invokeMethod("setMessage", "hello world").block();
- Assert.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- Assert.assertEquals(
- "hello world", proxy.invokeMethod("getMessage", String.class).block());
-
- Assert.assertEquals(
- executeSayMethod("hello world"),
- proxy.invokeMethod("setMessage", "hello world", String.class).block());
-
- proxy.invokeMethod("deleteMessage").block();
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
- }
-
- @Test(expected = IllegalStateException.class)
- public void lazyGet() {
- ActorProxy proxy = newActorProxy();
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
- proxy.invokeMethod("setMessage", "first message").block();
-
- // Creates the mono plan but does not call it yet.
- Mono getMessageCall = proxy.invokeMethod("getMessage", String.class);
-
- proxy.invokeMethod("deleteMessage").block();
-
- // Call should fail because the message was deleted.
- getMessageCall.block();
- }
-
- @Test
- public void lazySet() {
- ActorProxy proxy = newActorProxy();
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- // Creates the mono plan but does not call it yet.
- Mono setMessageCall = proxy.invokeMethod("setMessage", "first message");
-
- // No call executed yet, so message should not be set.
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- setMessageCall.block();
-
- // Now the message has been set.
- Assert.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
- }
-
- @Test
- public void lazyContains() {
- ActorProxy proxy = newActorProxy();
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- // Creates the mono plan but does not call it yet.
- Mono hasMessageCall = proxy.invokeMethod("hasMessage", Boolean.class);
-
- // Sets the message.
- proxy.invokeMethod("setMessage", "hello world").block();
-
- // Now we check if message is set.
- hasMessageCall.block();
-
- // Now the message should be set.
- Assert.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
- }
-
- @Test
- public void lazyDelete() {
- ActorProxy proxy = newActorProxy();
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- proxy.invokeMethod("setMessage", "first message").block();
-
- // Message is set.
- Assert.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- // Created the mono plan but does not execute it yet.
- Mono deleteMessageCall = proxy.invokeMethod("deleteMessage");
-
- // Message is still set.
- Assert.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- deleteMessageCall.block();
-
- // Now message is not set.
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
- }
-
- @Test
- public void lazyAdd() {
- ActorProxy proxy = newActorProxy();
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- proxy.invokeMethod("setMessage", "first message").block();
-
- // Message is set.
- Assert.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- // Created the mono plan but does not execute it yet.
- Mono addMessageCall = proxy.invokeMethod("addMessage", "second message");
-
- // Message is still set.
- Assert.assertEquals("first message",
- proxy.invokeMethod("getMessage", String.class).block());
-
- // Delete message
- proxy.invokeMethod("deleteMessage").block();
-
- // Should work since previous message was deleted.
- addMessageCall.block();
-
- // New message is still set.
- Assert.assertEquals("second message",
- proxy.invokeMethod("getMessage", String.class).block());
- }
-
- @Test
- public void onActivateAndOnDeactivate() {
- ActorProxy proxy = newActorProxy();
-
- Assert.assertTrue(proxy.invokeMethod("isActive", Boolean.class).block());
- Assert.assertFalse(DEACTIVATED_ACTOR_IDS.contains(proxy.getActorId().toString()));
-
- proxy.invokeMethod("hasMessage", Boolean.class).block();
-
- this.manager.deactivateActor(proxy.getActorId()).block();
-
- Assert.assertTrue(DEACTIVATED_ACTOR_IDS.contains(proxy.getActorId().toString()));
- }
-
- @Test
- public void onPreMethodAndOnPostMethod() {
- ActorProxy proxy = newActorProxy();
-
- proxy.invokeMethod("hasMessage", Boolean.class).block();
-
- MyMethodContext preContext =
- proxy.invokeMethod("getPreCallMethodContext", MyMethodContext.class).block();
- Assert.assertEquals("hasMessage", preContext.getName());
- Assert.assertEquals(ActorCallType.ACTOR_INTERFACE_METHOD.toString(), preContext.getType());
-
- MyMethodContext postContext =
- proxy.invokeMethod("getPostCallMethodContext", MyMethodContext.class).block();
- Assert.assertEquals("hasMessage", postContext.getName());
- Assert.assertEquals(ActorCallType.ACTOR_INTERFACE_METHOD.toString(), postContext.getType());
- }
-
- @Test
- public void invokeTimer() {
- ActorProxy proxy = newActorProxy();
-
- this.manager.invokeTimer(proxy.getActorId(), "mytimer", "{ \"callback\": \"hasMessage\" }".getBytes()).block();
-
- MyMethodContext preContext =
- proxy.invokeMethod("getPreCallMethodContext", MyMethodContext.class).block();
- Assert.assertEquals("mytimer", preContext.getName());
- Assert.assertEquals(ActorCallType.TIMER_METHOD.toString(), preContext.getType());
-
- MyMethodContext postContext =
- proxy.invokeMethod("getPostCallMethodContext", MyMethodContext.class).block();
- Assert.assertEquals("mytimer", postContext.getName());
- Assert.assertEquals(ActorCallType.TIMER_METHOD.toString(), postContext.getType());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void invokeTimerAfterDeactivate() {
- ActorProxy proxy = newActorProxy();
-
- this.manager.deactivateActor(proxy.getActorId()).block();
-
- this.manager.invokeTimer(proxy.getActorId(), "mytimer", "{ \"callback\": \"hasMessage\" }".getBytes()).block();
- }
-
- @Test
- public void invokeTimerAfterUnregister() {
- ActorProxy proxy = newActorProxy();
-
- proxy.invokeMethod("unregisterTimerAndReminder").block();
-
- // This call succeeds because the SDK does not control register/unregister timer, the Dapr runtime does.
- this.manager.invokeTimer(proxy.getActorId(), "mytimer", "{ \"callback\": \"hasMessage\" }".getBytes()).block();
- }
-
- @Test
- public void invokeUnknownTimer() {
- ActorProxy proxy = newActorProxy();
-
- // SDK does not control timers, Dapr runtime does - so an "unknown" timer can still be triggered.
- this.manager.invokeTimer(proxy.getActorId(), "unknown", "{ \"callback\": \"hasMessage\" }".getBytes()).block();
- }
-
- @Test
- public void invokeReminder() throws Exception {
- ActorProxy proxy = newActorProxy();
-
- byte[] params = createReminderParams("anything");
-
- this.manager.invokeReminder(proxy.getActorId(), "myreminder", params).block();
-
- MyMethodContext preContext =
- proxy.invokeMethod("getPreCallMethodContext", MyMethodContext.class).block();
- Assert.assertEquals("myreminder", preContext.getName());
- Assert.assertEquals(ActorCallType.REMINDER_METHOD.toString(), preContext.getType());
-
- MyMethodContext postContext =
- proxy.invokeMethod("getPostCallMethodContext", MyMethodContext.class).block();
- Assert.assertEquals("myreminder", postContext.getName());
- Assert.assertEquals(ActorCallType.REMINDER_METHOD.toString(), postContext.getType());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void invokeReminderAfterDeactivate() throws Exception {
- ActorProxy proxy = newActorProxy();
-
- this.manager.deactivateActor(proxy.getActorId()).block();
-
- byte[] params = createReminderParams("anything");
-
- this.manager.invokeReminder(proxy.getActorId(), "myreminder", params).block();
- }
-
- @Test
- public void classTypeRequestResponseInStateStore() {
- ActorProxy proxy = newActorProxy();
-
- MyMethodContext expectedContext = new MyMethodContext().setName("MyName").setType("MyType");
-
- proxy.invokeMethod("setMethodContext", expectedContext).block();
- MyMethodContext context = proxy.invokeMethod("getMethodContext", MyMethodContext.class).block();
-
- Assert.assertEquals(expectedContext.getName(), context.getName());
- Assert.assertEquals(expectedContext.getType(), context.getType());
- }
-
- @Test
- public void intTypeRequestResponseInStateStore() {
- ActorProxy proxy = newActorProxy();
-
- Assert.assertEquals(1, (int)proxy.invokeMethod("incrementAndGetCount", 1, int.class).block());
- Assert.assertEquals(6, (int)proxy.invokeMethod("incrementAndGetCount", 5, int.class).block());
- }
-
- @Test(expected = NumberFormatException.class)
- public void intTypeWithMethodException() {
- ActorProxy proxy = newActorProxy();
-
- // Zero is a magic input that will make method throw an exception.
- proxy.invokeMethod("incrementAndGetCount", 0, int.class).block();
- }
-
- @Test(expected = IllegalStateException.class)
- public void intTypeWithRuntimeException() {
- ActorProxy proxy = newActorProxy();
-
- proxy.invokeMethod("getCountButThrowsException", int.class).block();
- }
-
- @Test(expected = IllegalStateException.class)
- public void actorRuntimeException() {
- ActorProxy proxy = newActorProxy();
-
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- proxy.invokeMethod("forceDuplicateException").block();
- }
-
- @Test(expected = IllegalCharsetNameException.class)
- public void actorMethodException() {
- ActorProxy proxy = newActorProxy();
-
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- proxy.invokeMethod("throwsWithoutSaving").block();
-
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
- }
-
- @Test
- public void rollbackChanges() {
- ActorProxy proxy = newActorProxy();
-
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- // Runs a method that will add one message but fail because tries to add a second one.
- proxy.invokeMethod("forceDuplicateException")
- .onErrorResume(throwable -> Mono.empty())
- .block();
-
- // No message is set
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
- }
-
- @Test
- public void partialChanges() {
- ActorProxy proxy = newActorProxy();
-
- Assert.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- // Runs a method that will add one message, commit but fail because tries to add a second one.
- proxy.invokeMethod("forcePartialChange")
- .onErrorResume(throwable -> Mono.empty())
- .block();
-
- // Message is set.
- Assert.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
-
- // It is first message and not the second due to a save() in the middle but an exception in the end.
- Assert.assertEquals("first message",
- proxy.invokeMethod("getMessage", String.class).block());
- }
-
- private ActorProxy newActorProxy() {
- ActorId actorId = newActorId();
-
- // Mock daprClient for ActorProxy only, not for runtime.
- DaprClientStub daprClient = mock(DaprClientStub.class);
-
- when(daprClient.invoke(
- eq(context.getActorTypeInformation().getName()),
- eq(actorId.toString()),
- any(),
- any()))
- .thenAnswer(invocationOnMock ->
- this.manager.invokeMethod(
- new ActorId(invocationOnMock.getArgument(1, String.class)),
- invocationOnMock.getArgument(2, String.class),
- invocationOnMock.getArgument(3, byte[].class)));
-
- this.manager.activateActor(actorId).block();
-
- return new ActorProxyImplForTests(
- context.getActorTypeInformation().getName(),
- actorId,
- new DefaultObjectSerializer(),
- daprClient);
- }
-
- private byte[] createReminderParams(String data) throws IOException {
- byte[] serialized = this.context.getObjectSerializer().serialize(data);
- ActorReminderParams params = new ActorReminderParams(serialized, Duration.ofSeconds(1), Duration.ofSeconds(1));
- return INTERNAL_SERIALIZER.serialize(params);
- }
-
- private static ActorId newActorId() {
- return new ActorId(Integer.toString(ACTOR_ID_COUNT.incrementAndGet()));
- }
-
- private static String executeSayMethod(String something) {
- return "Said: " + (something == null ? "" : something);
- }
-
- private static ActorRuntimeContext createContext() {
- DaprClient daprClient = mock(DaprClient.class);
-
- when(daprClient.registerTimer(any(), any(), any(), any())).thenReturn(Mono.empty());
- when(daprClient.registerReminder(any(), any(), any(), any())).thenReturn(Mono.empty());
- when(daprClient.unregisterTimer(any(), any(), any())).thenReturn(Mono.empty());
- when(daprClient.unregisterReminder(any(), any(), any())).thenReturn(Mono.empty());
-
- return new ActorRuntimeContext(
- mock(ActorRuntime.class),
- new DefaultObjectSerializer(),
- new DefaultActorFactory(),
- ActorTypeInformation.create(MyActorImpl.class),
- daprClient,
- new DaprInMemoryStateProvider(new JavaSerializer())
- );
- }
-}
+/*
+ * Copyright 2021 The Dapr Authors
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package io.dapr.actors.runtime;
+
+import io.dapr.actors.ActorId;
+import io.dapr.actors.ActorType;
+import io.dapr.actors.client.ActorProxy;
+import io.dapr.actors.client.ActorProxyImplForTests;
+import io.dapr.actors.client.DaprClientStub;
+import io.dapr.serializer.DefaultObjectSerializer;
+import io.dapr.utils.TypeRef;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Mono;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.charset.IllegalCharsetNameException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class ActorStatefulTest {
+
+ private static final ActorObjectSerializer INTERNAL_SERIALIZER = new ActorObjectSerializer();
+
+ private static final AtomicInteger ACTOR_ID_COUNT = new AtomicInteger();
+
+ private static final Collection DEACTIVATED_ACTOR_IDS = Collections.synchronizedList(new ArrayList<>());
+
+ private final ActorRuntimeContext context = createContext();
+
+ private ActorManager manager = new ActorManager<>(context);
+
+ public interface MyActor {
+ Mono isActive();
+
+ MyMethodContext getPreCallMethodContext();
+
+ MyMethodContext getPostCallMethodContext();
+
+ Mono unregisterTimerAndReminder();
+
+ Mono incrementAndGetCount(int increment) throws Exception;
+
+ Mono getCountButThrowsException();
+
+ Mono addMessage(String message);
+
+ Mono setMessage(String message);
+
+ Mono getMessage();
+
+ Mono hasMessage();
+
+ Mono deleteMessage();
+
+ Mono forceDuplicateException();
+
+ Mono forcePartialChange();
+
+ Mono throwsWithoutSaving();
+
+ Mono setMethodContext(MyMethodContext context);
+
+ Mono getMethodContext();
+
+ String getIdString();
+ }
+
+ @ActorType(name = "MyActor")
+ public static class MyActorImpl extends AbstractActor implements MyActor, Remindable {
+
+ private final ActorId id;
+
+ private boolean activated;
+
+ private MyMethodContext preMethodCalled;
+
+ private MyMethodContext postMethodCalled;
+
+ public MyActorImpl(ActorRuntimeContext runtimeContext, ActorId id) {
+ super(runtimeContext, id);
+ this.id = id;
+ this.activated = true;
+ }
+
+ @Override
+ public Mono isActive() {
+ return Mono.fromSupplier(() -> this.activated);
+ }
+
+ @Override
+ public Mono onActivate() {
+ return Mono
+ .fromRunnable(() -> this.activated = true)
+ .then(super.registerActorTimer(
+ "mytimer",
+ "hasMessage",
+ null,
+ Duration.ofSeconds(1),
+ Duration.ofSeconds(1)))
+ .then(super.registerReminder(
+ "myreminder",
+ null,
+ Duration.ofSeconds(1),
+ Duration.ofSeconds(1)
+ ));
+ }
+
+ @Override
+ public Mono onDeactivate() {
+ return Mono.fromRunnable(() -> DEACTIVATED_ACTOR_IDS.add(this.id.toString()));
+ }
+
+ @Override
+ public Mono onPreActorMethod(ActorMethodContext context) {
+ // Only keep the first one to make sure we can validate it via another method invocation.
+ return Mono.fromRunnable(() -> {
+ this.preMethodCalled = this.preMethodCalled != null ? this.preMethodCalled : new MyMethodContext()
+ .setName(context.getMethodName())
+ .setType(context.getCallType().toString());
+ });
+ }
+
+ @Override
+ public Mono onPostActorMethod(ActorMethodContext context) {
+ // Only keep the first one to make sure we can validate it via another method invocation.
+ return Mono.fromRunnable(() -> {
+ this.postMethodCalled = this.postMethodCalled != null ? this.postMethodCalled : new MyMethodContext()
+ .setName(context.getMethodName())
+ .setType(context.getCallType().toString());
+ });
+ }
+
+ @Override
+ public MyMethodContext getPreCallMethodContext() {
+ return this.preMethodCalled;
+ }
+
+ @Override
+ public MyMethodContext getPostCallMethodContext() {
+ return this.postMethodCalled;
+ }
+
+ @Override
+ public Mono unregisterTimerAndReminder() {
+ return super.unregisterReminder("UnknownReminder")
+ .then(super.unregisterTimer("UnknownTimer"))
+ .then(super.unregisterReminder("myreminder"))
+ .then(super.unregisterTimer("mytimer"));
+ }
+
+ @Override
+ public Mono incrementAndGetCount(int increment) {
+ return Mono.fromRunnable(() -> {
+ if (increment == 0) {
+ // Artificial exception case for testing.
+ throw new NumberFormatException("increment cannot be zero.");
+ }
+ })
+ .then(super.getActorStateManager().contains("counter"))
+ .flatMap(contains -> {
+ if (!contains) {
+ return Mono.just(0);
+ }
+
+ return super.getActorStateManager().get("counter", int.class);
+ })
+ .map(count -> count + increment)
+ .flatMap(count -> super.getActorStateManager().set("counter", count).thenReturn(count));
+ }
+
+ @Override
+ public Mono getCountButThrowsException() {
+ return super.getActorStateManager().get("counter_WRONG_NAME", int.class);
+ }
+
+ @Override
+ public Mono addMessage(String message) {
+ return super.getActorStateManager().add("message", message);
+ }
+
+ @Override
+ public Mono setMessage(String message) {
+ return super.getActorStateManager().set("message", message).thenReturn(executeSayMethod(message));
+ }
+
+ @Override
+ public Mono getMessage() {
+ return super.getActorStateManager().get("message", String.class);
+ }
+
+ @Override
+ public Mono hasMessage() {
+ return super.getActorStateManager().contains("message");
+ }
+
+ @Override
+ public Mono deleteMessage() {
+ return super.getActorStateManager().remove("message");
+ }
+
+ @Override
+ public Mono forceDuplicateException() {
+ // Second add should throw exception.
+ return super.getActorStateManager().add("message", "anything")
+ .then(super.getActorStateManager().add("message", "something else"));
+ }
+
+ @Override
+ public Mono forcePartialChange() {
+ return super.getActorStateManager().add("message", "first message")
+ .then(super.saveState())
+ .then(super.getActorStateManager().add("message", "second message"));
+ }
+
+ @Override
+ public Mono throwsWithoutSaving() {
+ return super.getActorStateManager().add("message", "first message")
+ .then(Mono.error(new IllegalCharsetNameException("random")));
+ }
+
+ @Override
+ public Mono setMethodContext(MyMethodContext context) {
+ return super.getActorStateManager().set("context", context);
+ }
+
+ @Override
+ public Mono getMethodContext() {
+ return super.getActorStateManager().get("context", MyMethodContext.class);
+ }
+
+ // Blocking methods are also supported for Actors. Mono is not required.
+ @Override
+ public String getIdString() {
+ return this.id.toString();
+ }
+
+ @Override
+ public TypeRef getStateType() {
+ // Remindable type.
+ return TypeRef.STRING;
+ }
+
+ @Override
+ public Mono receiveReminder(String reminderName, String state, Duration dueTime, Duration period) {
+ return Mono.empty();
+ }
+ }
+
+ // Class used to validate serialization/deserialization
+ public static class MyMethodContext implements Serializable {
+
+ private String type;
+
+ private String name;
+
+ public String getType() {
+ return type;
+ }
+
+ public MyMethodContext setType(String type) {
+ this.type = type;
+ return this;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public MyMethodContext setName(String name) {
+ this.name = name;
+ return this;
+ }
+ }
+
+ @Test
+ public void happyGetSetDeleteContains() {
+ ActorProxy proxy = newActorProxy();
+ Assertions.assertEquals(
+ proxy.getActorId().toString(), proxy.invokeMethod("getIdString", String.class).block());
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ proxy.invokeMethod("setMessage", "hello world").block();
+ Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ Assertions.assertEquals(
+ "hello world", proxy.invokeMethod("getMessage", String.class).block());
+
+ Assertions.assertEquals(
+ executeSayMethod("hello world"),
+ proxy.invokeMethod("setMessage", "hello world", String.class).block());
+
+ proxy.invokeMethod("deleteMessage").block();
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+ }
+
+ @Test
+ public void lazyGet() {
+ ActorProxy proxy = newActorProxy();
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+ proxy.invokeMethod("setMessage", "first message").block();
+
+ // Creates the mono plan but does not call it yet.
+ Mono getMessageCall = proxy.invokeMethod("getMessage", String.class);
+
+ proxy.invokeMethod("deleteMessage").block();
+
+ // Call should fail because the message was deleted.
+ assertThrows(IllegalStateException.class, () -> getMessageCall.block());
+ }
+
+ @Test
+ public void lazySet() {
+ ActorProxy proxy = newActorProxy();
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ // Creates the mono plan but does not call it yet.
+ Mono setMessageCall = proxy.invokeMethod("setMessage", "first message");
+
+ // No call executed yet, so message should not be set.
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ setMessageCall.block();
+
+ // Now the message has been set.
+ Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
+ }
+
+ @Test
+ public void lazyContains() {
+ ActorProxy proxy = newActorProxy();
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ // Creates the mono plan but does not call it yet.
+ Mono hasMessageCall = proxy.invokeMethod("hasMessage", Boolean.class);
+
+ // Sets the message.
+ proxy.invokeMethod("setMessage", "hello world").block();
+
+ // Now we check if message is set.
+ hasMessageCall.block();
+
+ // Now the message should be set.
+ Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
+ }
+
+ @Test
+ public void lazyDelete() {
+ ActorProxy proxy = newActorProxy();
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ proxy.invokeMethod("setMessage", "first message").block();
+
+ // Message is set.
+ Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ // Created the mono plan but does not execute it yet.
+ Mono deleteMessageCall = proxy.invokeMethod("deleteMessage");
+
+ // Message is still set.
+ Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ deleteMessageCall.block();
+
+ // Now message is not set.
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+ }
+
+ @Test
+ public void lazyAdd() {
+ ActorProxy proxy = newActorProxy();
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ proxy.invokeMethod("setMessage", "first message").block();
+
+ // Message is set.
+ Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ // Created the mono plan but does not execute it yet.
+ Mono addMessageCall = proxy.invokeMethod("addMessage", "second message");
+
+ // Message is still set.
+ Assertions.assertEquals("first message",
+ proxy.invokeMethod("getMessage", String.class).block());
+
+ // Delete message
+ proxy.invokeMethod("deleteMessage").block();
+
+ // Should work since previous message was deleted.
+ addMessageCall.block();
+
+ // New message is still set.
+ Assertions.assertEquals("second message",
+ proxy.invokeMethod("getMessage", String.class).block());
+ }
+
+ @Test
+ public void onActivateAndOnDeactivate() {
+ ActorProxy proxy = newActorProxy();
+
+ Assertions.assertTrue(proxy.invokeMethod("isActive", Boolean.class).block());
+ Assertions.assertFalse(DEACTIVATED_ACTOR_IDS.contains(proxy.getActorId().toString()));
+
+ proxy.invokeMethod("hasMessage", Boolean.class).block();
+
+ this.manager.deactivateActor(proxy.getActorId()).block();
+
+ Assertions.assertTrue(DEACTIVATED_ACTOR_IDS.contains(proxy.getActorId().toString()));
+ }
+
+ @Test
+ public void onPreMethodAndOnPostMethod() {
+ ActorProxy proxy = newActorProxy();
+
+ proxy.invokeMethod("hasMessage", Boolean.class).block();
+
+ MyMethodContext preContext =
+ proxy.invokeMethod("getPreCallMethodContext", MyMethodContext.class).block();
+ Assertions.assertEquals("hasMessage", preContext.getName());
+ Assertions.assertEquals(ActorCallType.ACTOR_INTERFACE_METHOD.toString(), preContext.getType());
+
+ MyMethodContext postContext =
+ proxy.invokeMethod("getPostCallMethodContext", MyMethodContext.class).block();
+ Assertions.assertEquals("hasMessage", postContext.getName());
+ Assertions.assertEquals(ActorCallType.ACTOR_INTERFACE_METHOD.toString(), postContext.getType());
+ }
+
+ @Test
+ public void invokeTimer() {
+ ActorProxy proxy = newActorProxy();
+
+ this.manager.invokeTimer(proxy.getActorId(), "mytimer", "{ \"callback\": \"hasMessage\" }".getBytes()).block();
+
+ MyMethodContext preContext =
+ proxy.invokeMethod("getPreCallMethodContext", MyMethodContext.class).block();
+ Assertions.assertEquals("mytimer", preContext.getName());
+ Assertions.assertEquals(ActorCallType.TIMER_METHOD.toString(), preContext.getType());
+
+ MyMethodContext postContext =
+ proxy.invokeMethod("getPostCallMethodContext", MyMethodContext.class).block();
+ Assertions.assertEquals("mytimer", postContext.getName());
+ Assertions.assertEquals(ActorCallType.TIMER_METHOD.toString(), postContext.getType());
+ }
+
+ @Test
+ public void invokeTimerAfterDeactivate() {
+ ActorProxy proxy = newActorProxy();
+
+ this.manager.deactivateActor(proxy.getActorId()).block();
+
+ assertThrows(IllegalArgumentException.class, () ->
+ this.manager.invokeTimer(proxy.getActorId(), "mytimer", "{ \"callback\": \"hasMessage\" }".getBytes()).block());
+ }
+
+ @Test
+ public void invokeTimerAfterUnregister() {
+ ActorProxy proxy = newActorProxy();
+
+ proxy.invokeMethod("unregisterTimerAndReminder").block();
+
+ // This call succeeds because the SDK does not control register/unregister timer, the Dapr runtime does.
+ this.manager.invokeTimer(proxy.getActorId(), "mytimer", "{ \"callback\": \"hasMessage\" }".getBytes()).block();
+ }
+
+ @Test
+ public void invokeUnknownTimer() {
+ ActorProxy proxy = newActorProxy();
+
+ // SDK does not control timers, Dapr runtime does - so an "unknown" timer can still be triggered.
+ this.manager.invokeTimer(proxy.getActorId(), "unknown", "{ \"callback\": \"hasMessage\" }".getBytes()).block();
+ }
+
+ @Test
+ public void invokeReminder() throws Exception {
+ ActorProxy proxy = newActorProxy();
+
+ byte[] params = createReminderParams("anything");
+
+ this.manager.invokeReminder(proxy.getActorId(), "myreminder", params).block();
+
+ MyMethodContext preContext =
+ proxy.invokeMethod("getPreCallMethodContext", MyMethodContext.class).block();
+ Assertions.assertEquals("myreminder", preContext.getName());
+ Assertions.assertEquals(ActorCallType.REMINDER_METHOD.toString(), preContext.getType());
+
+ MyMethodContext postContext =
+ proxy.invokeMethod("getPostCallMethodContext", MyMethodContext.class).block();
+ Assertions.assertEquals("myreminder", postContext.getName());
+ Assertions.assertEquals(ActorCallType.REMINDER_METHOD.toString(), postContext.getType());
+ }
+
+ @Test
+ public void invokeReminderAfterDeactivate() throws Exception {
+ ActorProxy proxy = newActorProxy();
+
+ this.manager.deactivateActor(proxy.getActorId()).block();
+
+ byte[] params = createReminderParams("anything");
+
+ assertThrows(IllegalArgumentException.class, () -> this.manager.invokeReminder(proxy.getActorId(), "myreminder", params).block());
+ }
+
+ @Test
+ public void classTypeRequestResponseInStateStore() {
+ ActorProxy proxy = newActorProxy();
+
+ MyMethodContext expectedContext = new MyMethodContext().setName("MyName").setType("MyType");
+
+ proxy.invokeMethod("setMethodContext", expectedContext).block();
+ MyMethodContext context = proxy.invokeMethod("getMethodContext", MyMethodContext.class).block();
+
+ Assertions.assertEquals(expectedContext.getName(), context.getName());
+ Assertions.assertEquals(expectedContext.getType(), context.getType());
+ }
+
+ @Test
+ public void intTypeRequestResponseInStateStore() {
+ ActorProxy proxy = newActorProxy();
+
+ Assertions.assertEquals(1, (int)proxy.invokeMethod("incrementAndGetCount", 1, int.class).block());
+ Assertions.assertEquals(6, (int)proxy.invokeMethod("incrementAndGetCount", 5, int.class).block());
+ }
+
+ @Test
+ public void intTypeWithMethodException() {
+ ActorProxy proxy = newActorProxy();
+
+ // Zero is a magic input that will make method throw an exception.
+ assertThrows(NumberFormatException.class, () -> proxy.invokeMethod("incrementAndGetCount", 0, int.class).block());
+ }
+
+ @Test
+ public void intTypeWithRuntimeException() {
+ ActorProxy proxy = newActorProxy();
+
+ assertThrows(RuntimeException.class, () ->
+ proxy.invokeMethod("getCountButThrowsException", int.class).block());
+ }
+
+ @Test
+ public void actorRuntimeException() {
+ ActorProxy proxy = newActorProxy();
+
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ assertThrows(RuntimeException.class, () ->
+ proxy.invokeMethod("forceDuplicateException").block());
+ }
+
+ @Test
+ public void actorMethodException() {
+ ActorProxy proxy = newActorProxy();
+
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ assertThrows(IllegalCharsetNameException.class, () -> proxy.invokeMethod("throwsWithoutSaving").block());
+
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+ }
+
+ @Test
+ public void rollbackChanges() {
+ ActorProxy proxy = newActorProxy();
+
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ // Runs a method that will add one message but fail because tries to add a second one.
+ proxy.invokeMethod("forceDuplicateException")
+ .onErrorResume(throwable -> Mono.empty())
+ .block();
+
+ // No message is set
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+ }
+
+ @Test
+ public void partialChanges() {
+ ActorProxy proxy = newActorProxy();
+
+ Assertions.assertFalse(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ // Runs a method that will add one message, commit but fail because tries to add a second one.
+ proxy.invokeMethod("forcePartialChange")
+ .onErrorResume(throwable -> Mono.empty())
+ .block();
+
+ // Message is set.
+ Assertions.assertTrue(proxy.invokeMethod("hasMessage", Boolean.class).block());
+
+ // It is first message and not the second due to a save() in the middle but an exception in the end.
+ Assertions.assertEquals("first message",
+ proxy.invokeMethod("getMessage", String.class).block());
+ }
+
+ private ActorProxy newActorProxy() {
+ ActorId actorId = newActorId();
+
+ // Mock daprClient for ActorProxy only, not for runtime.
+ DaprClientStub daprClient = mock(DaprClientStub.class);
+
+ when(daprClient.invoke(
+ eq(context.getActorTypeInformation().getName()),
+ eq(actorId.toString()),
+ any(),
+ any()))
+ .thenAnswer(invocationOnMock ->
+ this.manager.invokeMethod(
+ new ActorId(invocationOnMock.getArgument(1, String.class)),
+ invocationOnMock.getArgument(2, String.class),
+ invocationOnMock.getArgument(3, byte[].class)));
+
+ this.manager.activateActor(actorId).block();
+
+ return new ActorProxyImplForTests(
+ context.getActorTypeInformation().getName(),
+ actorId,
+ new DefaultObjectSerializer(),
+ daprClient);
+ }
+
+ private byte[] createReminderParams(String data) throws IOException {
+ byte[] serialized = this.context.getObjectSerializer().serialize(data);
+ ActorReminderParams params = new ActorReminderParams(serialized, Duration.ofSeconds(1), Duration.ofSeconds(1));
+ return INTERNAL_SERIALIZER.serialize(params);
+ }
+
+ private static ActorId newActorId() {
+ return new ActorId(Integer.toString(ACTOR_ID_COUNT.incrementAndGet()));
+ }
+
+ private static String executeSayMethod(String something) {
+ return "Said: " + (something == null ? "" : something);
+ }
+
+ private static ActorRuntimeContext createContext() {
+ DaprClient daprClient = mock(DaprClient.class);
+
+ when(daprClient.registerTimer(any(), any(), any(), any())).thenReturn(Mono.empty());
+ when(daprClient.registerReminder(any(), any(), any(), any())).thenReturn(Mono.empty());
+ when(daprClient.unregisterTimer(any(), any(), any())).thenReturn(Mono.empty());
+ when(daprClient.unregisterReminder(any(), any(), any())).thenReturn(Mono.empty());
+
+ return new ActorRuntimeContext(
+ mock(ActorRuntime.class),
+ new DefaultObjectSerializer(),
+ new DefaultActorFactory(),
+ ActorTypeInformation.create(MyActorImpl.class),
+ daprClient,
+ new DaprInMemoryStateProvider(new JavaSerializer())
+ );
+ }
+}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTimerTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTimerTest.java
index 00320e078..204996da0 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTimerTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTimerTest.java
@@ -14,8 +14,8 @@ limitations under the License.
package io.dapr.actors.runtime;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
@@ -43,7 +43,7 @@ public class ActorTimerTest {
String expected = "{\"period\":\"1h0m3s0ms\",\"dueTime\":\"0h7m17s0ms\", \"callback\": \"myfunction\"}";
// Deep comparison via JsonNode.equals method.
- Assert.assertEquals(OBJECT_MAPPER.readTree(expected), OBJECT_MAPPER.readTree(s));
+ Assertions.assertEquals(OBJECT_MAPPER.readTree(expected), OBJECT_MAPPER.readTree(s));
}
@Test
@@ -67,6 +67,6 @@ public class ActorTimerTest {
// A negative period will be serialized to an empty string which is interpreted by Dapr to mean fire once only.
String expected = "{\"period\":\"\",\"dueTime\":\"0h7m17s0ms\", \"callback\": \"myfunction\"}";
// Deep comparison via JsonNode.equals method.
- Assert.assertEquals(OBJECT_MAPPER.readTree(expected), OBJECT_MAPPER.readTree(s));
+ Assertions.assertEquals(OBJECT_MAPPER.readTree(expected), OBJECT_MAPPER.readTree(s));
}
}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTypeInformationTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTypeInformationTest.java
index 93aab6b8a..503d7d53a 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTypeInformationTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTypeInformationTest.java
@@ -1,154 +1,154 @@
-/*
- * Copyright 2021 The Dapr Authors
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package io.dapr.actors.runtime;
-
-import io.dapr.actors.ActorType;
-import io.dapr.utils.TypeRef;
-import org.junit.Assert;
-import org.junit.Test;
-import reactor.core.publisher.Mono;
-
-import java.time.Duration;
-
-/**
- * Unit tests for ActorTypeInformation.
- */
-public class ActorTypeInformationTest {
-
- /**
- * Actor interfaced used in this test only.
- */
- @ActorType(name = "MyActorWithAnnotation")
- private interface MyActorAnnotated {
- }
-
- /**
- * Actor interfaced used in this test only.
- */
- private interface MyActor {
- }
-
- /**
- * Checks information for a non-remindable actor.
- */
- @Test
- public void notRemindable() {
-
- class A extends AbstractActor implements MyActor {
- A() {
- super(null, null);
- }
- }
-
- ActorTypeInformation info = ActorTypeInformation.create(A.class);
- Assert.assertNotNull(info);
- Assert.assertEquals("A", info.getName());
- Assert.assertEquals(A.class, info.getImplementationClass());
- Assert.assertFalse(info.isAbstractClass());
- Assert.assertFalse(info.isRemindable());
- Assert.assertEquals(1, info.getInterfaces().size());
- Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
- }
-
- /**
- * Checks information for a remindable actor.
- */
- @Test
- public void remindable() {
-
- class A extends AbstractActor implements MyActor, Remindable {
- A() {
- super(null, null);
- }
-
- @Override
- public TypeRef getStateType() {
- return null;
- }
-
- @Override
- public Mono receiveReminder(String reminderName, Object state, Duration dueTime, Duration period) {
- return null;
- }
- }
-
- ActorTypeInformation info = ActorTypeInformation.create(A.class);
- Assert.assertNotNull(info);
- Assert.assertEquals("A", info.getName());
- Assert.assertEquals(A.class, info.getImplementationClass());
- Assert.assertFalse(info.isAbstractClass());
- Assert.assertTrue(info.isRemindable());
- Assert.assertEquals(2, info.getInterfaces().size());
- Assert.assertTrue(info.getInterfaces().contains(Remindable.class));
- Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
- }
-
- /**
- * Checks information for an actor renamed via annotation.
- */
- @Test
- public void renamedWithAnnotation() {
- @ActorType(name = "B")
- class A extends AbstractActor implements MyActor {
- A() {
- super(null, null);
- }
- }
-
- ActorTypeInformation info = ActorTypeInformation.create(A.class);
- Assert.assertNotNull(info);
- Assert.assertEquals("B", info.getName());
- Assert.assertEquals(A.class, info.getImplementationClass());
- Assert.assertFalse(info.isAbstractClass());
- Assert.assertFalse(info.isRemindable());
- Assert.assertEquals(1, info.getInterfaces().size());
- Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
- }
-
- /**
- * Checks information for an actor renamed via annotation at interface.
- */
- @Test
- public void renamedWithAnnotationAtInterface() {
- class A extends AbstractActor implements MyActorAnnotated {
- A() {
- super(null, null);
- }
- }
-
- ActorTypeInformation info = ActorTypeInformation.create(A.class);
- Assert.assertNotNull(info);
- Assert.assertEquals("MyActorWithAnnotation", info.getName());
- Assert.assertEquals(A.class, info.getImplementationClass());
- Assert.assertFalse(info.isAbstractClass());
- Assert.assertFalse(info.isRemindable());
- Assert.assertEquals(1, info.getInterfaces().size());
- Assert.assertTrue(info.getInterfaces().contains(MyActorAnnotated.class));
- }
-
- /**
- * Checks information for an actor is invalid due to an non-actor parent.
- */
- @Test
- public void nonActorParentClass() {
- abstract class MyAbstractClass implements MyActor {
- }
-
- class A extends MyAbstractClass {
- }
-
- ActorTypeInformation info = ActorTypeInformation.tryCreate(A.class);
- Assert.assertNull(info);
- }
-}
+/*
+ * Copyright 2021 The Dapr Authors
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package io.dapr.actors.runtime;
+
+import io.dapr.actors.ActorType;
+import io.dapr.utils.TypeRef;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Mono;
+
+import java.time.Duration;
+
+/**
+ * Unit tests for ActorTypeInformation.
+ */
+public class ActorTypeInformationTest {
+
+ /**
+ * Actor interfaced used in this test only.
+ */
+ @ActorType(name = "MyActorWithAnnotation")
+ private interface MyActorAnnotated {
+ }
+
+ /**
+ * Actor interfaced used in this test only.
+ */
+ private interface MyActor {
+ }
+
+ /**
+ * Checks information for a non-remindable actor.
+ */
+ @Test
+ public void notRemindable() {
+
+ class A extends AbstractActor implements MyActor {
+ A() {
+ super(null, null);
+ }
+ }
+
+ ActorTypeInformation info = ActorTypeInformation.create(A.class);
+ Assertions.assertNotNull(info);
+ Assertions.assertEquals("A", info.getName());
+ Assertions.assertEquals(A.class, info.getImplementationClass());
+ Assertions.assertFalse(info.isAbstractClass());
+ Assertions.assertFalse(info.isRemindable());
+ Assertions.assertEquals(1, info.getInterfaces().size());
+ Assertions.assertTrue(info.getInterfaces().contains(MyActor.class));
+ }
+
+ /**
+ * Checks information for a remindable actor.
+ */
+ @Test
+ public void remindable() {
+
+ class A extends AbstractActor implements MyActor, Remindable {
+ A() {
+ super(null, null);
+ }
+
+ @Override
+ public TypeRef getStateType() {
+ return null;
+ }
+
+ @Override
+ public Mono receiveReminder(String reminderName, Object state, Duration dueTime, Duration period) {
+ return null;
+ }
+ }
+
+ ActorTypeInformation info = ActorTypeInformation.create(A.class);
+ Assertions.assertNotNull(info);
+ Assertions.assertEquals("A", info.getName());
+ Assertions.assertEquals(A.class, info.getImplementationClass());
+ Assertions.assertFalse(info.isAbstractClass());
+ Assertions.assertTrue(info.isRemindable());
+ Assertions.assertEquals(2, info.getInterfaces().size());
+ Assertions.assertTrue(info.getInterfaces().contains(Remindable.class));
+ Assertions.assertTrue(info.getInterfaces().contains(MyActor.class));
+ }
+
+ /**
+ * Checks information for an actor renamed via annotation.
+ */
+ @Test
+ public void renamedWithAnnotation() {
+ @ActorType(name = "B")
+ class A extends AbstractActor implements MyActor {
+ A() {
+ super(null, null);
+ }
+ }
+
+ ActorTypeInformation info = ActorTypeInformation.create(A.class);
+ Assertions.assertNotNull(info);
+ Assertions.assertEquals("B", info.getName());
+ Assertions.assertEquals(A.class, info.getImplementationClass());
+ Assertions.assertFalse(info.isAbstractClass());
+ Assertions.assertFalse(info.isRemindable());
+ Assertions.assertEquals(1, info.getInterfaces().size());
+ Assertions.assertTrue(info.getInterfaces().contains(MyActor.class));
+ }
+
+ /**
+ * Checks information for an actor renamed via annotation at interface.
+ */
+ @Test
+ public void renamedWithAnnotationAtInterface() {
+ class A extends AbstractActor implements MyActorAnnotated {
+ A() {
+ super(null, null);
+ }
+ }
+
+ ActorTypeInformation info = ActorTypeInformation.create(A.class);
+ Assertions.assertNotNull(info);
+ Assertions.assertEquals("MyActorWithAnnotation", info.getName());
+ Assertions.assertEquals(A.class, info.getImplementationClass());
+ Assertions.assertFalse(info.isAbstractClass());
+ Assertions.assertFalse(info.isRemindable());
+ Assertions.assertEquals(1, info.getInterfaces().size());
+ Assertions.assertTrue(info.getInterfaces().contains(MyActorAnnotated.class));
+ }
+
+ /**
+ * Checks information for an actor is invalid due to an non-actor parent.
+ */
+ @Test
+ public void nonActorParentClass() {
+ abstract class MyAbstractClass implements MyActor {
+ }
+
+ class A extends MyAbstractClass {
+ }
+
+ ActorTypeInformation info = ActorTypeInformation.tryCreate(A.class);
+ Assertions.assertNull(info);
+ }
+}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTypeUtilitiesTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTypeUtilitiesTest.java
index 5a4b8fae8..12a48ca19 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTypeUtilitiesTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ActorTypeUtilitiesTest.java
@@ -14,14 +14,14 @@ package io.dapr.actors.runtime;
import io.dapr.actors.ActorId;
import io.dapr.utils.TypeRef;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import java.io.Closeable;
import java.time.Duration;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ActorTypeUtilitiesTest {
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprGrpcClientTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprGrpcClientTest.java
index 5d67c610a..94f02d1fa 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprGrpcClientTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprGrpcClientTest.java
@@ -27,9 +27,9 @@ import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.GrpcCleanupRule;
-import org.junit.Before;
import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import java.io.IOException;
@@ -39,7 +39,7 @@ import java.util.List;
import java.util.concurrent.ExecutionException;
import static io.dapr.actors.TestUtils.assertThrowsDaprException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class DaprGrpcClientTest {
@@ -71,7 +71,7 @@ public class DaprGrpcClientTest {
@Rule
public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
- @Before
+ @BeforeEach
public void setup() throws IOException {
// Generate a unique in-process server name.
String serverName = InProcessServerBuilder.generateName();
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprHttpClientTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprHttpClientTest.java
index 8ef2f976c..a267452a6 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprHttpClientTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprHttpClientTest.java
@@ -24,8 +24,8 @@ import okhttp3.mock.Behavior;
import okhttp3.mock.MockInterceptor;
import okhttp3.mock.RuleAnswer;
import okio.Buffer;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import java.io.IOException;
@@ -35,8 +35,8 @@ import java.util.Base64;
import java.util.Collections;
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;
import static org.junit.jupiter.api.Assertions.fail;
public class DaprHttpClientTest {
@@ -49,7 +49,7 @@ public class DaprHttpClientTest {
private final String EXPECTED_RESULT = "{\"data\":\"ewoJCSJwcm9wZXJ0eUEiOiAidmFsdWVBIiwKCQkicHJvcGVydHlCIjogInZhbHVlQiIKCX0=\"}";
- @Before
+ @BeforeEach
public void setUp() throws Exception {
mockInterceptor = new MockInterceptor(Behavior.UNORDERED);
okHttpClient = new OkHttpClient.Builder().addInterceptor(mockInterceptor).build();
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprStateAsyncProviderTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprStateAsyncProviderTest.java
index aebacc31c..a061b6675 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprStateAsyncProviderTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/DaprStateAsyncProviderTest.java
@@ -1,267 +1,267 @@
-/*
- * Copyright 2021 The Dapr Authors
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package io.dapr.actors.runtime;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import io.dapr.actors.ActorId;
-import io.dapr.serializer.DaprObjectSerializer;
-import io.dapr.serializer.DefaultObjectSerializer;
-import io.dapr.utils.TypeRef;
-import org.junit.Assert;
-import org.junit.Test;
-import reactor.core.publisher.Mono;
-
-import java.util.Arrays;
-import java.util.Objects;
-
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-
-/**
- * Tests for the state store facade.
- */
-public class DaprStateAsyncProviderTest {
-
- private static final DaprObjectSerializer SERIALIZER = new DefaultObjectSerializer();
-
- private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
-
- private static final double EPSILON = 1e-10;
-
- /**
- * Class used to test JSON serialization.
- */
- public static final class Customer {
-
- private int id;
-
- private String name;
-
- public int getId() {
- return id;
- }
-
- public Customer setId(int id) {
- this.id = id;
- return this;
- }
-
- public String getName() {
- return name;
- }
-
- public Customer setName(String name) {
- this.name = name;
- return this;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Customer customer = (Customer) o;
- return id == customer.id &&
- Objects.equals(name, customer.name);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(id, name);
- }
-
- }
-
- @Test
- public void happyCaseApply() {
- DaprClient daprClient = mock(DaprClient.class);
- when(daprClient
- .saveStateTransactionally(
- eq("MyActor"),
- eq("123"),
- argThat(operations -> {
- if (operations == null) {
- return false;
- }
-
- if (operations.size() != 4) {
- return false;
- }
-
- boolean foundInsertName = false;
- boolean foundUpdateZipcode = false;
- boolean foundDeleteFlag = false;
- boolean foundUpdateBytes = false;
- for (ActorStateOperation operation : operations) {
- if (operation.getOperationType() == null) {
- return false;
- }
- if (operation.getKey() == null) {
- return false;
- }
-
- String opName = operation.getOperationType();
- String key = operation.getKey();
- Object value = operation.getValue();
-
- foundInsertName |= "upsert".equals(opName) &&
- "name".equals(key) &&
- "\"Jon Doe\"".equals(value);
- foundUpdateZipcode |= "upsert".equals(opName) &&
- "zipcode".equals(key) &&
- "98011".equals(value);
- foundDeleteFlag |= "delete".equals(opName) &&
- "flag".equals(key) &&
- (value == null);
- foundUpdateBytes |= "upsert".equals(opName) &&
- "bytes".equals(key) &&
- Arrays.equals(new byte[]{0x1}, (byte[]) value);
- }
-
- return foundInsertName && foundUpdateZipcode && foundDeleteFlag && foundUpdateBytes;
- })))
- .thenReturn(Mono.empty());
-
- DaprStateAsyncProvider provider = new DaprStateAsyncProvider(daprClient, SERIALIZER);
- provider.apply("MyActor",
- new ActorId("123"),
- createInsertChange("name", "Jon Doe"),
- createUpdateChange("zipcode", 98011),
- createDeleteChange("flag"),
- createUpdateChange("bytes", new byte[]{0x1}))
- .block();
-
- verify(daprClient).saveStateTransactionally(eq("MyActor"), eq("123"), any());
- }
-
- @Test
- public void happyCaseLoad() throws Exception {
- DaprClient daprClient = mock(DaprClient.class);
- when(daprClient
- .getState(any(), any(), eq("name")))
- .thenReturn(Mono.just(SERIALIZER.serialize("Jon Doe")));
- when(daprClient
- .getState(any(), any(), eq("zipcode")))
- .thenReturn(Mono.just(SERIALIZER.serialize(98021)));
- when(daprClient
- .getState(any(), any(), eq("goals")))
- .thenReturn(Mono.just(SERIALIZER.serialize(98)));
- when(daprClient
- .getState(any(), any(), eq("balance")))
- .thenReturn(Mono.just(SERIALIZER.serialize(46.55)));
- when(daprClient
- .getState(any(), any(), eq("active")))
- .thenReturn(Mono.just(SERIALIZER.serialize(true)));
- when(daprClient
- .getState(any(), any(), eq("customer")))
- .thenReturn(Mono.just("{ \"id\": 1000, \"name\": \"Roxane\"}".getBytes()));
- when(daprClient
- .getState(any(), any(), eq("anotherCustomer")))
- .thenReturn(Mono.just("{ \"id\": 2000, \"name\": \"Max\"}".getBytes()));
- when(daprClient
- .getState(any(), any(), eq("nullCustomer")))
- .thenReturn(Mono.empty());
- when(daprClient
- .getState(any(), any(), eq("bytes")))
- .thenReturn(Mono.just("\"QQ==\"".getBytes()));
- when(daprClient
- .getState(any(), any(), eq("emptyBytes")))
- .thenReturn(Mono.just(new byte[0]));
-
- DaprStateAsyncProvider provider = new DaprStateAsyncProvider(daprClient, SERIALIZER);
-
- Assert.assertEquals("Jon Doe",
- provider.load("MyActor", new ActorId("123"), "name", TypeRef.STRING).block());
- Assert.assertEquals(98021,
- (int) provider.load("MyActor", new ActorId("123"), "zipcode", TypeRef.INT).block());
- Assert.assertEquals(98,
- (int) provider.load("MyActor", new ActorId("123"), "goals", TypeRef.INT).block());
- Assert.assertEquals(98,
- (int) provider.load("MyActor", new ActorId("123"), "goals", TypeRef.INT).block());
- Assert.assertEquals(46.55,
- (double) provider.load("MyActor", new ActorId("123"), "balance", TypeRef.DOUBLE).block(),
- EPSILON);
- Assert.assertEquals(true,
- (boolean) provider.load("MyActor", new ActorId("123"), "active", TypeRef.BOOLEAN).block());
- Assert.assertEquals(new Customer().setId(1000).setName("Roxane"),
- provider.load("MyActor", new ActorId("123"), "customer", TypeRef.get(Customer.class)).block());
- Assert.assertNotEquals(new Customer().setId(1000).setName("Roxane"),
- provider.load("MyActor", new ActorId("123"), "anotherCustomer", TypeRef.get(Customer.class)).block());
- Assert.assertNull(
- provider.load("MyActor", new ActorId("123"), "nullCustomer", TypeRef.get(Customer.class)).block());
- Assert.assertArrayEquals("A".getBytes(),
- provider.load("MyActor", new ActorId("123"), "bytes", TypeRef.get(byte[].class)).block());
- Assert.assertNull(
- provider.load("MyActor", new ActorId("123"), "emptyBytes", TypeRef.get(byte[].class)).block());
- }
-
- @Test
- public void happyCaseContains() {
- DaprClient daprClient = mock(DaprClient.class);
-
- // Keys that exists.
- when(daprClient
- .getState(any(), any(), eq("name")))
- .thenReturn(Mono.just("Jon Doe".getBytes()));
- when(daprClient
- .getState(any(), any(), eq("zipcode")))
- .thenReturn(Mono.just("98021".getBytes()));
- when(daprClient
- .getState(any(), any(), eq("goals")))
- .thenReturn(Mono.just("98".getBytes()));
- when(daprClient
- .getState(any(), any(), eq("balance")))
- .thenReturn(Mono.just("46.55".getBytes()));
- when(daprClient
- .getState(any(), any(), eq("active")))
- .thenReturn(Mono.just("true".getBytes()));
- when(daprClient
- .getState(any(), any(), eq("customer")))
- .thenReturn(Mono.just("{ \"id\": \"3000\", \"name\": \"Ely\" }".getBytes()));
-
- // Keys that do not exist.
- when(daprClient
- .getState(any(), any(), eq("Does not exist")))
- .thenReturn(Mono.empty());
- when(daprClient
- .getState(any(), any(), eq("NAME")))
- .thenReturn(Mono.empty());
- when(daprClient
- .getState(any(), any(), eq(null)))
- .thenReturn(Mono.empty());
-
- DaprStateAsyncProvider provider = new DaprStateAsyncProvider(daprClient, SERIALIZER);
-
- Assert.assertTrue(provider.contains("MyActor", new ActorId("123"), "name").block());
- Assert.assertFalse(provider.contains("MyActor", new ActorId("123"), "NAME").block());
- Assert.assertTrue(provider.contains("MyActor", new ActorId("123"), "zipcode").block());
- Assert.assertTrue(provider.contains("MyActor", new ActorId("123"), "goals").block());
- Assert.assertTrue(provider.contains("MyActor", new ActorId("123"), "balance").block());
- Assert.assertTrue(provider.contains("MyActor", new ActorId("123"), "active").block());
- Assert.assertTrue(provider.contains("MyActor", new ActorId("123"), "customer").block());
- Assert.assertFalse(provider.contains("MyActor", new ActorId("123"), "Does not exist").block());
- Assert.assertFalse(provider.contains("MyActor", new ActorId("123"), null).block());
- }
-
- private final ActorStateChange createInsertChange(String name, T value) {
- return new ActorStateChange(name, value, ActorStateChangeKind.ADD);
- }
-
- private final ActorStateChange createUpdateChange(String name, T value) {
- return new ActorStateChange(name, value, ActorStateChangeKind.UPDATE);
- }
-
- private final ActorStateChange createDeleteChange(String name) {
- return new ActorStateChange(name, null, ActorStateChangeKind.REMOVE);
- }
-}
+/*
+ * Copyright 2021 The Dapr Authors
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package io.dapr.actors.runtime;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.dapr.actors.ActorId;
+import io.dapr.serializer.DaprObjectSerializer;
+import io.dapr.serializer.DefaultObjectSerializer;
+import io.dapr.utils.TypeRef;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Mono;
+
+import java.util.Arrays;
+import java.util.Objects;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * Tests for the state store facade.
+ */
+public class DaprStateAsyncProviderTest {
+
+ private static final DaprObjectSerializer SERIALIZER = new DefaultObjectSerializer();
+
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ private static final double EPSILON = 1e-10;
+
+ /**
+ * Class used to test JSON serialization.
+ */
+ public static final class Customer {
+
+ private int id;
+
+ private String name;
+
+ public int getId() {
+ return id;
+ }
+
+ public Customer setId(int id) {
+ this.id = id;
+ return this;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Customer setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Customer customer = (Customer) o;
+ return id == customer.id &&
+ Objects.equals(name, customer.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name);
+ }
+
+ }
+
+ @Test
+ public void happyCaseApply() {
+ DaprClient daprClient = mock(DaprClient.class);
+ when(daprClient
+ .saveStateTransactionally(
+ eq("MyActor"),
+ eq("123"),
+ argThat(operations -> {
+ if (operations == null) {
+ return false;
+ }
+
+ if (operations.size() != 4) {
+ return false;
+ }
+
+ boolean foundInsertName = false;
+ boolean foundUpdateZipcode = false;
+ boolean foundDeleteFlag = false;
+ boolean foundUpdateBytes = false;
+ for (ActorStateOperation operation : operations) {
+ if (operation.getOperationType() == null) {
+ return false;
+ }
+ if (operation.getKey() == null) {
+ return false;
+ }
+
+ String opName = operation.getOperationType();
+ String key = operation.getKey();
+ Object value = operation.getValue();
+
+ foundInsertName |= "upsert".equals(opName) &&
+ "name".equals(key) &&
+ "\"Jon Doe\"".equals(value);
+ foundUpdateZipcode |= "upsert".equals(opName) &&
+ "zipcode".equals(key) &&
+ "98011".equals(value);
+ foundDeleteFlag |= "delete".equals(opName) &&
+ "flag".equals(key) &&
+ (value == null);
+ foundUpdateBytes |= "upsert".equals(opName) &&
+ "bytes".equals(key) &&
+ Arrays.equals(new byte[]{0x1}, (byte[]) value);
+ }
+
+ return foundInsertName && foundUpdateZipcode && foundDeleteFlag && foundUpdateBytes;
+ })))
+ .thenReturn(Mono.empty());
+
+ DaprStateAsyncProvider provider = new DaprStateAsyncProvider(daprClient, SERIALIZER);
+ provider.apply("MyActor",
+ new ActorId("123"),
+ createInsertChange("name", "Jon Doe"),
+ createUpdateChange("zipcode", 98011),
+ createDeleteChange("flag"),
+ createUpdateChange("bytes", new byte[]{0x1}))
+ .block();
+
+ verify(daprClient).saveStateTransactionally(eq("MyActor"), eq("123"), any());
+ }
+
+ @Test
+ public void happyCaseLoad() throws Exception {
+ DaprClient daprClient = mock(DaprClient.class);
+ when(daprClient
+ .getState(any(), any(), eq("name")))
+ .thenReturn(Mono.just(SERIALIZER.serialize("Jon Doe")));
+ when(daprClient
+ .getState(any(), any(), eq("zipcode")))
+ .thenReturn(Mono.just(SERIALIZER.serialize(98021)));
+ when(daprClient
+ .getState(any(), any(), eq("goals")))
+ .thenReturn(Mono.just(SERIALIZER.serialize(98)));
+ when(daprClient
+ .getState(any(), any(), eq("balance")))
+ .thenReturn(Mono.just(SERIALIZER.serialize(46.55)));
+ when(daprClient
+ .getState(any(), any(), eq("active")))
+ .thenReturn(Mono.just(SERIALIZER.serialize(true)));
+ when(daprClient
+ .getState(any(), any(), eq("customer")))
+ .thenReturn(Mono.just("{ \"id\": 1000, \"name\": \"Roxane\"}".getBytes()));
+ when(daprClient
+ .getState(any(), any(), eq("anotherCustomer")))
+ .thenReturn(Mono.just("{ \"id\": 2000, \"name\": \"Max\"}".getBytes()));
+ when(daprClient
+ .getState(any(), any(), eq("nullCustomer")))
+ .thenReturn(Mono.empty());
+ when(daprClient
+ .getState(any(), any(), eq("bytes")))
+ .thenReturn(Mono.just("\"QQ==\"".getBytes()));
+ when(daprClient
+ .getState(any(), any(), eq("emptyBytes")))
+ .thenReturn(Mono.just(new byte[0]));
+
+ DaprStateAsyncProvider provider = new DaprStateAsyncProvider(daprClient, SERIALIZER);
+
+ Assertions.assertEquals("Jon Doe",
+ provider.load("MyActor", new ActorId("123"), "name", TypeRef.STRING).block());
+ Assertions.assertEquals(98021,
+ (int) provider.load("MyActor", new ActorId("123"), "zipcode", TypeRef.INT).block());
+ Assertions.assertEquals(98,
+ (int) provider.load("MyActor", new ActorId("123"), "goals", TypeRef.INT).block());
+ Assertions.assertEquals(98,
+ (int) provider.load("MyActor", new ActorId("123"), "goals", TypeRef.INT).block());
+ Assertions.assertEquals(46.55,
+ (double) provider.load("MyActor", new ActorId("123"), "balance", TypeRef.DOUBLE).block(),
+ EPSILON);
+ Assertions.assertEquals(true,
+ (boolean) provider.load("MyActor", new ActorId("123"), "active", TypeRef.BOOLEAN).block());
+ Assertions.assertEquals(new Customer().setId(1000).setName("Roxane"),
+ provider.load("MyActor", new ActorId("123"), "customer", TypeRef.get(Customer.class)).block());
+ Assertions.assertNotEquals(new Customer().setId(1000).setName("Roxane"),
+ provider.load("MyActor", new ActorId("123"), "anotherCustomer", TypeRef.get(Customer.class)).block());
+ Assertions.assertNull(
+ provider.load("MyActor", new ActorId("123"), "nullCustomer", TypeRef.get(Customer.class)).block());
+ Assertions.assertArrayEquals("A".getBytes(),
+ provider.load("MyActor", new ActorId("123"), "bytes", TypeRef.get(byte[].class)).block());
+ Assertions.assertNull(
+ provider.load("MyActor", new ActorId("123"), "emptyBytes", TypeRef.get(byte[].class)).block());
+ }
+
+ @Test
+ public void happyCaseContains() {
+ DaprClient daprClient = mock(DaprClient.class);
+
+ // Keys that exists.
+ when(daprClient
+ .getState(any(), any(), eq("name")))
+ .thenReturn(Mono.just("Jon Doe".getBytes()));
+ when(daprClient
+ .getState(any(), any(), eq("zipcode")))
+ .thenReturn(Mono.just("98021".getBytes()));
+ when(daprClient
+ .getState(any(), any(), eq("goals")))
+ .thenReturn(Mono.just("98".getBytes()));
+ when(daprClient
+ .getState(any(), any(), eq("balance")))
+ .thenReturn(Mono.just("46.55".getBytes()));
+ when(daprClient
+ .getState(any(), any(), eq("active")))
+ .thenReturn(Mono.just("true".getBytes()));
+ when(daprClient
+ .getState(any(), any(), eq("customer")))
+ .thenReturn(Mono.just("{ \"id\": \"3000\", \"name\": \"Ely\" }".getBytes()));
+
+ // Keys that do not exist.
+ when(daprClient
+ .getState(any(), any(), eq("Does not exist")))
+ .thenReturn(Mono.empty());
+ when(daprClient
+ .getState(any(), any(), eq("NAME")))
+ .thenReturn(Mono.empty());
+ when(daprClient
+ .getState(any(), any(), eq(null)))
+ .thenReturn(Mono.empty());
+
+ DaprStateAsyncProvider provider = new DaprStateAsyncProvider(daprClient, SERIALIZER);
+
+ Assertions.assertTrue(provider.contains("MyActor", new ActorId("123"), "name").block());
+ Assertions.assertFalse(provider.contains("MyActor", new ActorId("123"), "NAME").block());
+ Assertions.assertTrue(provider.contains("MyActor", new ActorId("123"), "zipcode").block());
+ Assertions.assertTrue(provider.contains("MyActor", new ActorId("123"), "goals").block());
+ Assertions.assertTrue(provider.contains("MyActor", new ActorId("123"), "balance").block());
+ Assertions.assertTrue(provider.contains("MyActor", new ActorId("123"), "active").block());
+ Assertions.assertTrue(provider.contains("MyActor", new ActorId("123"), "customer").block());
+ Assertions.assertFalse(provider.contains("MyActor", new ActorId("123"), "Does not exist").block());
+ Assertions.assertFalse(provider.contains("MyActor", new ActorId("123"), null).block());
+ }
+
+ private final ActorStateChange createInsertChange(String name, T value) {
+ return new ActorStateChange(name, value, ActorStateChangeKind.ADD);
+ }
+
+ private final ActorStateChange createUpdateChange(String name, T value) {
+ return new ActorStateChange(name, value, ActorStateChangeKind.UPDATE);
+ }
+
+ private final ActorStateChange createDeleteChange(String name) {
+ return new ActorStateChange(name, null, ActorStateChangeKind.REMOVE);
+ }
+}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/DefaultActorFactoryTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/DefaultActorFactoryTest.java
index f017499dd..ecda0072f 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/DefaultActorFactoryTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/DefaultActorFactoryTest.java
@@ -1,89 +1,91 @@
-/*
- * Copyright 2021 The Dapr Authors
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package io.dapr.actors.runtime;
-
-import io.dapr.actors.ActorId;
-import io.dapr.serializer.DaprObjectSerializer;
-import org.junit.Assert;
-import org.junit.Test;
-
-import static org.mockito.Mockito.mock;
-
-/**
- * Testing the default constructor of an Actor.
- */
-public class DefaultActorFactoryTest {
-
- /**
- * A compliant implementation of Actor to be used in the tests below.
- */
- static class MyActor extends AbstractActor {
-
- ActorRuntimeContext context;
-
- ActorId actorId;
-
- public MyActor(ActorRuntimeContext context, ActorId actorId) {
- super(context, actorId);
- this.context = context;
- this.actorId = actorId;
- }
- }
-
- /**
- * A non-compliant implementation of Actor to be used in the tests below.
- */
- static class InvalidActor extends AbstractActor {
- InvalidActor() {
- super(null, null);
- }
- }
-
- /**
- * Happy case.
- */
- @Test
- public void happyActor() {
- DefaultActorFactory factory = new DefaultActorFactory<>();
-
- ActorId actorId = ActorId.createRandom();
- MyActor actor = factory.createActor(createActorRuntimeContext(MyActor.class), actorId);
-
- Assert.assertEquals(actorId, actor.actorId);
- Assert.assertNotNull(actor.context);
- }
-
- /**
- * Class is not an actor.
- */
- @Test(expected = RuntimeException.class)
- public void noValidConstructor() {
- DefaultActorFactory factory = new DefaultActorFactory<>();
-
- ActorId actorId = ActorId.createRandom();
-
- factory.createActor(createActorRuntimeContext(InvalidActor.class), actorId);
- }
-
- private static ActorRuntimeContext createActorRuntimeContext(Class clazz) {
- return new ActorRuntimeContext(
- mock(ActorRuntime.class),
- mock(DaprObjectSerializer.class),
- mock(ActorFactory.class),
- ActorTypeInformation.create(clazz),
- mock(DaprClient.class),
- mock(DaprStateAsyncProvider.class));
- }
-
-}
+/*
+ * Copyright 2021 The Dapr Authors
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package io.dapr.actors.runtime;
+
+import io.dapr.actors.ActorId;
+import io.dapr.serializer.DaprObjectSerializer;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Testing the default constructor of an Actor.
+ */
+public class DefaultActorFactoryTest {
+
+ /**
+ * A compliant implementation of Actor to be used in the tests below.
+ */
+ static class MyActor extends AbstractActor {
+
+ ActorRuntimeContext context;
+
+ ActorId actorId;
+
+ public MyActor(ActorRuntimeContext context, ActorId actorId) {
+ super(context, actorId);
+ this.context = context;
+ this.actorId = actorId;
+ }
+ }
+
+ /**
+ * A non-compliant implementation of Actor to be used in the tests below.
+ */
+ static class InvalidActor extends AbstractActor {
+ InvalidActor() {
+ super(null, null);
+ }
+ }
+
+ /**
+ * Happy case.
+ */
+ @Test
+ public void happyActor() {
+ DefaultActorFactory factory = new DefaultActorFactory<>();
+
+ ActorId actorId = ActorId.createRandom();
+ MyActor actor = factory.createActor(createActorRuntimeContext(MyActor.class), actorId);
+
+ Assertions.assertEquals(actorId, actor.actorId);
+ Assertions.assertNotNull(actor.context);
+ }
+
+ /**
+ * Class is not an actor.
+ */
+ @Test
+ public void noValidConstructor() {
+ DefaultActorFactory factory = new DefaultActorFactory<>();
+
+ ActorId actorId = ActorId.createRandom();
+
+ assertThrows(RuntimeException.class, () ->
+ factory.createActor(createActorRuntimeContext(InvalidActor.class), actorId));
+ }
+
+ private static ActorRuntimeContext createActorRuntimeContext(Class clazz) {
+ return new ActorRuntimeContext(
+ mock(ActorRuntime.class),
+ mock(DaprObjectSerializer.class),
+ mock(ActorFactory.class),
+ ActorTypeInformation.create(clazz),
+ mock(DaprClient.class),
+ mock(DaprStateAsyncProvider.class));
+ }
+
+}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/DerivedActorTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/DerivedActorTest.java
index 73ccfc723..c83daa4c3 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/DerivedActorTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/DerivedActorTest.java
@@ -19,12 +19,13 @@ import io.dapr.actors.client.ActorProxy;
import io.dapr.actors.client.ActorProxyImplForTests;
import io.dapr.actors.client.DaprClientStub;
import io.dapr.serializer.DefaultObjectSerializer;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import java.util.concurrent.atomic.AtomicInteger;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -229,7 +230,7 @@ public class DerivedActorTest {
ActorProxy proxy = createActorProxyForActorChild();
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
- Assert.assertEquals(
+ Assertions.assertEquals(
"abcabc",
proxy.invokeMethod("stringInStringOut", "abc", String.class).block());
}
@@ -239,11 +240,11 @@ public class DerivedActorTest {
ActorProxy proxy = createActorProxyForActorChild();
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
- Assert.assertEquals(
+ Assertions.assertEquals(
false,
proxy.invokeMethod("stringInBooleanOut", "hello world", Boolean.class).block());
- Assert.assertEquals(
+ Assertions.assertEquals(
true,
proxy.invokeMethod("stringInBooleanOut", "true", Boolean.class).block());
}
@@ -253,24 +254,26 @@ public class DerivedActorTest {
ActorProxy actorProxy = createActorProxyForActorChild();
// stringInVoidOut() has not been invoked so this is false
- Assert.assertEquals(
+ Assertions.assertEquals(
false,
actorProxy.invokeMethod("methodReturningVoidInvoked", Boolean.class).block());
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
actorProxy.invokeMethod("stringInVoidOut", "hello world").block();
- Assert.assertEquals(
+ Assertions.assertEquals(
true,
actorProxy.invokeMethod("methodReturningVoidInvoked", Boolean.class).block());
}
- @Test(expected = IllegalMonitorStateException.class)
+ @Test
public void stringInVoidOutIntentionallyThrows() {
ActorProxy actorProxy = createActorProxyForActorChild();
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
- actorProxy.invokeMethod("stringInVoidOutIntentionallyThrows", "hello world").block();
+
+ assertThrows(IllegalMonitorStateException.class, () ->
+ actorProxy.invokeMethod("stringInVoidOutIntentionallyThrows", "hello world").block());
}
@Test
@@ -281,10 +284,10 @@ public class DerivedActorTest {
// this should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
MyData response = actorProxy.invokeMethod("classInClassOut", d, MyData.class).block();
- Assert.assertEquals(
+ Assertions.assertEquals(
"hihi",
response.getName());
- Assert.assertEquals(
+ Assertions.assertEquals(
6,
response.getNum());
}
@@ -294,33 +297,33 @@ public class DerivedActorTest {
public void testInheritedActorMethods() {
ActorProxy actorProxy = createActorProxyForActorChild();
- Assert.assertEquals(
+ Assertions.assertEquals(
"www",
actorProxy.invokeMethod("onlyImplementedInParentStringInStringOut", "w", String.class).block());
- Assert.assertEquals(
+ Assertions.assertEquals(
true,
actorProxy.invokeMethod("onlyImplementedInParentStringInBooleanOut", "icecream", Boolean.class).block());
// onlyImplementedInParentStringInVoidOut() has not been invoked so this is false
- Assert.assertEquals(
+ Assertions.assertEquals(
false,
actorProxy.invokeMethod("methodReturningVoidInvoked", Boolean.class).block());
actorProxy.invokeMethod("onlyImplementedInParentStringInVoidOut", "icecream", Boolean.class).block();
// now it should return true.
- Assert.assertEquals(
+ Assertions.assertEquals(
true,
actorProxy.invokeMethod("methodReturningVoidInvoked", Boolean.class).block());
MyData d = new MyData("hi", 3);
MyData response = actorProxy.invokeMethod("onlyImplementedInParentClassInClassOut", d, MyData.class).block();
- Assert.assertEquals(
+ Assertions.assertEquals(
"hihihi",
response.getName());
- Assert.assertEquals(
+ Assertions.assertEquals(
9,
response.getNum());
}
diff --git a/sdk-actors/src/test/java/io/dapr/actors/runtime/ThrowFromPreAndPostActorMethodsTest.java b/sdk-actors/src/test/java/io/dapr/actors/runtime/ThrowFromPreAndPostActorMethodsTest.java
index 1395a0116..885a9f078 100644
--- a/sdk-actors/src/test/java/io/dapr/actors/runtime/ThrowFromPreAndPostActorMethodsTest.java
+++ b/sdk-actors/src/test/java/io/dapr/actors/runtime/ThrowFromPreAndPostActorMethodsTest.java
@@ -19,12 +19,13 @@ import io.dapr.actors.client.ActorProxy;
import io.dapr.actors.client.ActorProxyImplForTests;
import io.dapr.actors.client.DaprClientStub;
import io.dapr.serializer.DefaultObjectSerializer;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import java.util.concurrent.atomic.AtomicInteger;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -122,25 +123,23 @@ public class ThrowFromPreAndPostActorMethodsTest {
// IllegalMonitorStateException should be intentionally thrown. This type was chosen for this test just because
// it is unlikely to collide.
- @Test(expected = IllegalMonitorStateException.class)
+ @Test
public void stringInBooleanOut1() {
ActorProxy proxy = createActorProxyForActorChild();
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
- Assert.assertEquals(
- false,
+ assertThrows(IllegalMonitorStateException.class, () ->
proxy.invokeMethod("stringInBooleanOut", "hello world", Boolean.class).block());
}
// IllegalMonitorStateException should be intentionally thrown. This type was chosen for this test just because
// it is unlikely to collide.
- @Test(expected = IllegalMonitorStateException.class)
+ @Test
public void stringInBooleanOut2() {
ActorProxy proxy = createActorProxyForActorChild();
// these should only call the actor methods for ActorChild. The implementations in ActorParent will throw.
- Assert.assertEquals(
- true,
+ assertThrows(IllegalMonitorStateException.class, () ->
proxy.invokeMethod("stringInBooleanOut", "true", Boolean.class).block());
}
diff --git a/sdk-springboot/pom.xml b/sdk-springboot/pom.xml
index 688542519..cb29a2f18 100644
--- a/sdk-springboot/pom.xml
+++ b/sdk-springboot/pom.xml
@@ -87,8 +87,13 @@
true
- junit
- junit
+ org.junit.jupiter
+ junit-jupiter
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-params
test
diff --git a/sdk-springboot/src/test/java/io/dapr/springboot/DaprBeanPostProcessorSubscribeTest.java b/sdk-springboot/src/test/java/io/dapr/springboot/DaprBeanPostProcessorSubscribeTest.java
index 33303435f..456e88b3e 100644
--- a/sdk-springboot/src/test/java/io/dapr/springboot/DaprBeanPostProcessorSubscribeTest.java
+++ b/sdk-springboot/src/test/java/io/dapr/springboot/DaprBeanPostProcessorSubscribeTest.java
@@ -13,8 +13,8 @@
package io.dapr.springboot;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import org.springframework.util.StringValueResolver;
import java.lang.reflect.Constructor;
@@ -42,7 +42,7 @@ public class DaprBeanPostProcessorSubscribeTest {
DaprTopicSubscription[] topicSubscriptions = runtime.listSubscribedTopics();
// There should be three subscriptions.
- Assert.assertEquals(2, topicSubscriptions.length);
+ Assertions.assertEquals(2, topicSubscriptions.length);
DaprTopicSubscription[] expectedDaprTopicSubscriptions = getTestDaprTopicSubscriptions();
@@ -55,16 +55,16 @@ public class DaprBeanPostProcessorSubscribeTest {
}
private void assertTopicSubscriptionEquality(DaprTopicSubscription s1, DaprTopicSubscription s2) {
- Assert.assertEquals(s1.getPubsubName(), s2.getPubsubName());
- Assert.assertEquals(s1.getTopic(), s2.getTopic());
- Assert.assertEquals(s1.getRoute(), s2.getRoute());
- Assert.assertEquals(s1.getMetadata(), s2.getMetadata());
+ Assertions.assertEquals(s1.getPubsubName(), s2.getPubsubName());
+ Assertions.assertEquals(s1.getTopic(), s2.getTopic());
+ Assertions.assertEquals(s1.getRoute(), s2.getRoute());
+ Assertions.assertEquals(s1.getMetadata(), s2.getMetadata());
if (s1.getBulkSubscribe() == null) {
- Assert.assertNull(s2.getBulkSubscribe());
+ Assertions.assertNull(s2.getBulkSubscribe());
} else {
- Assert.assertEquals(s1.getBulkSubscribe().isEnabled(), s2.getBulkSubscribe().isEnabled());
- Assert.assertEquals(s1.getBulkSubscribe().getMaxAwaitDurationMs(), s2.getBulkSubscribe().getMaxAwaitDurationMs());
- Assert.assertEquals(s1.getBulkSubscribe().getMaxMessagesCount(), s2.getBulkSubscribe().getMaxMessagesCount());
+ Assertions.assertEquals(s1.getBulkSubscribe().isEnabled(), s2.getBulkSubscribe().isEnabled());
+ Assertions.assertEquals(s1.getBulkSubscribe().getMaxAwaitDurationMs(), s2.getBulkSubscribe().getMaxAwaitDurationMs());
+ Assertions.assertEquals(s1.getBulkSubscribe().getMaxMessagesCount(), s2.getBulkSubscribe().getMaxMessagesCount());
}
}
diff --git a/sdk-springboot/src/test/java/io/dapr/springboot/DaprBeanPostProcessorTest.java b/sdk-springboot/src/test/java/io/dapr/springboot/DaprBeanPostProcessorTest.java
index 18bfc35b0..1916686fb 100644
--- a/sdk-springboot/src/test/java/io/dapr/springboot/DaprBeanPostProcessorTest.java
+++ b/sdk-springboot/src/test/java/io/dapr/springboot/DaprBeanPostProcessorTest.java
@@ -13,54 +13,41 @@
package io.dapr.springboot;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
-import java.util.Collection;
import java.util.List;
+import java.util.stream.Stream;
-@RunWith(Parameterized.class)
public class DaprBeanPostProcessorTest {
-
- private final Class> clazzToBeTested;
- private final String methodToBeTested;
- private final String[] expected;
- private final boolean expectedResult;
private static final String TOPIC_NAME = "topicName1";
- public DaprBeanPostProcessorTest(Class> clazzToBeTested, String methodToBeTested, String[] expected,
- boolean expectedResult) {
- this.clazzToBeTested = clazzToBeTested;
- this.methodToBeTested = methodToBeTested;
- this.expected = expected;
- this.expectedResult = expectedResult;
+ public static Stream routesTester() {
+ return Stream.of(
+ Arguments.of(MockController.class, "testMethod1", new String[] {"v1", "v2", "v1/page1", "v2/page1", "v1/page2", "v2/page2"},
+ true),
+ Arguments.of(MockController.class, "testMethod2", new String[] {"v1", "v2", "v1/page3", "v2/page3", "v1/page4", "v2/page4"},
+ true),
+ Arguments.of(MockController.class, "testMethod3", new String[] {"v1/foo", "v2/foo"}, true),
+ Arguments.of(MockController.class, "testMethod4", new String[] {"v1/foo1", "v2/foo1", "v1/foo2", "v2/foo2"}, true),
+ Arguments.of(MockController.class, "testMethod5", new String[] {"v1/" + TOPIC_NAME, "v2/" + TOPIC_NAME}, true),
+ Arguments.of(MockControllerNoClazzAnnotation.class, "testMethod1", new String[] {"", "page1", "page2"}, true),
+ Arguments.of(MockControllerNoClazzAnnotation.class, "testMethod2", new String[] {"", "page3", "page4"}, true),
+ Arguments.of(MockControllerNoClazzAnnotation.class, "testMethod3", new String[] {"foo"}, true),
+ Arguments.of(MockControllerNoClazzAnnotation.class, "testMethod4", new String[] {"foo1", "foo2"}, true),
+ Arguments.of(MockControllerNoClazzAnnotation.class, "testMethod5", new String[] {TOPIC_NAME}, true)
+ );
}
- @Parameterized.Parameters
- public static Collection> routesTester() {
- return Arrays.asList(new Object[][] {
- {MockController.class, "testMethod1", new String[] {"v1", "v2", "v1/page1", "v2/page1", "v1/page2", "v2/page2"},
- true},
- {MockController.class, "testMethod2", new String[] {"v1", "v2", "v1/page3", "v2/page3", "v1/page4", "v2/page4"},
- true},
- {MockController.class, "testMethod3", new String[] {"v1/foo", "v2/foo"}, true},
- {MockController.class, "testMethod4", new String[] {"v1/foo1", "v2/foo1", "v1/foo2", "v2/foo2"}, true},
- {MockController.class, "testMethod5", new String[] {"v1/" + TOPIC_NAME, "v2/" + TOPIC_NAME}, true},
- {MockControllerNoClazzAnnotation.class, "testMethod1", new String[] {"", "page1", "page2"}, true},
- {MockControllerNoClazzAnnotation.class, "testMethod2", new String[] {"", "page3", "page4"}, true},
- {MockControllerNoClazzAnnotation.class, "testMethod3", new String[] {"foo"}, true},
- {MockControllerNoClazzAnnotation.class, "testMethod4", new String[] {"foo1", "foo2"}, true},
- {MockControllerNoClazzAnnotation.class, "testMethod5", new String[] {TOPIC_NAME}, true}
- });
- }
-
- @Test
- public void testAllPostRoutesGeneration() throws NoSuchMethodException {
+ @ParameterizedTest
+ @MethodSource("routesTester")
+ public void testAllPostRoutesGeneration(Class> clazzToBeTested, String methodToBeTested, String[] expected,
+ boolean expectedResult) throws NoSuchMethodException {
Method allPostRoutesMethod = DaprBeanPostProcessor.class.
getDeclaredMethod("getAllCompleteRoutesForPost", Class.class, Method.class, String.class);
allPostRoutesMethod.setAccessible(true);
@@ -71,7 +58,7 @@ public class DaprBeanPostProcessorTest {
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
- Assert.assertEquals(expectedResult,
+ Assertions.assertEquals(expectedResult,
testingListForOrderAgnosticEquality(Arrays.asList(expected), routesArrayTestMethod1));
}
diff --git a/sdk-springboot/src/test/java/io/dapr/springboot/DaprRuntimeTest.java b/sdk-springboot/src/test/java/io/dapr/springboot/DaprRuntimeTest.java
index e49a5bcda..08d19152e 100644
--- a/sdk-springboot/src/test/java/io/dapr/springboot/DaprRuntimeTest.java
+++ b/sdk-springboot/src/test/java/io/dapr/springboot/DaprRuntimeTest.java
@@ -1,12 +1,14 @@
package io.dapr.springboot;
import io.dapr.Rule;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation;
import java.util.HashMap;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
public class DaprRuntimeTest {
@Test
@@ -33,7 +35,7 @@ public class DaprRuntimeTest {
};
DaprRuntime runtime = DaprRuntime.getInstance();
- Assert.assertNotNull(runtime);
+ Assertions.assertNotNull(runtime);
// We should be able to register the same route multiple times
runtime.addSubscribedTopic(
@@ -42,7 +44,7 @@ public class DaprRuntimeTest {
pubSubName, topicName, match, rule.priority(), route,deadLetterTopic, metadata);
}
- @Test(expected = RuntimeException.class)
+ @Test
public void testPubsubDefaultPathDifferentRegistration() {
String pubSubName = "pubsub";
String topicName = "topic";
@@ -70,14 +72,13 @@ public class DaprRuntimeTest {
DaprRuntime runtime = DaprRuntime.getInstance();
- Assert.assertNotNull(runtime);
+ Assertions.assertNotNull(runtime);
runtime.addSubscribedTopic(
pubSubName, topicName, match, rule.priority(), firstRoute, deadLetterTopic, metadata);
// Supplying the same pubsub bits but a different route should fail
- runtime.addSubscribedTopic(
- pubSubName, topicName, match, rule.priority(), secondRoute, deadLetterTopic, metadata);
-
+ assertThrows(RuntimeException.class, () -> runtime.addSubscribedTopic(
+ pubSubName, topicName, match, rule.priority(), secondRoute, deadLetterTopic, metadata));
}
}
diff --git a/sdk-springboot/src/test/java/io/dapr/springboot/DaprTopicBulkSubscribeTest.java b/sdk-springboot/src/test/java/io/dapr/springboot/DaprTopicBulkSubscribeTest.java
index e640d276e..a6237af36 100644
--- a/sdk-springboot/src/test/java/io/dapr/springboot/DaprTopicBulkSubscribeTest.java
+++ b/sdk-springboot/src/test/java/io/dapr/springboot/DaprTopicBulkSubscribeTest.java
@@ -13,8 +13,8 @@
package io.dapr.springboot;
-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;
@@ -26,12 +26,12 @@ public class DaprTopicBulkSubscribeTest {
bulkSubscribe.setMaxMessagesCount(100);
bulkSubscribe.setMaxAwaitDurationMs(200);
- Assert.assertTrue(bulkSubscribe.isEnabled());
- Assert.assertEquals(100, bulkSubscribe.getMaxMessagesCount().longValue());
- Assert.assertEquals(200, bulkSubscribe.getMaxAwaitDurationMs().longValue());
+ Assertions.assertTrue(bulkSubscribe.isEnabled());
+ Assertions.assertEquals(100, bulkSubscribe.getMaxMessagesCount().longValue());
+ Assertions.assertEquals(200, bulkSubscribe.getMaxAwaitDurationMs().longValue());
bulkSubscribe.setEnabled(false);
- Assert.assertFalse(bulkSubscribe.isEnabled());
+ Assertions.assertFalse(bulkSubscribe.isEnabled());
}
@Test
@@ -48,9 +48,9 @@ public class DaprTopicBulkSubscribeTest {
for (Map.Entry testCase: testCases.entrySet()) {
try {
bulkSubscribe.setMaxMessagesCount(testCase.getKey());
- Assert.assertFalse(testCase.getValue());
+ Assertions.assertFalse(testCase.getValue());
} catch (IllegalArgumentException e) {
- Assert.assertTrue(testCase.getValue());
+ Assertions.assertTrue(testCase.getValue());
}
}
}
@@ -69,9 +69,9 @@ public class DaprTopicBulkSubscribeTest {
for (Map.Entry testCase: testCases.entrySet()) {
try {
bulkSubscribe.setMaxAwaitDurationMs(testCase.getKey());
- Assert.assertFalse(testCase.getValue());
+ Assertions.assertFalse(testCase.getValue());
} catch (IllegalArgumentException e) {
- Assert.assertTrue(testCase.getValue());
+ Assertions.assertTrue(testCase.getValue());
}
}
}
diff --git a/sdk-tests/pom.xml b/sdk-tests/pom.xml
index 7238dfef6..43ce0bda0 100644
--- a/sdk-tests/pom.xml
+++ b/sdk-tests/pom.xml
@@ -33,6 +33,13 @@
pom
import
+
+ org.junit
+ junit-bom
+ 5.7.2
+ pom
+ import
+
@@ -101,15 +108,13 @@
test
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter
test
org.junit.jupiter
- junit-jupiter-engine
- 5.5.2
+ junit-jupiter-params
test
@@ -201,9 +206,9 @@
- org.codehaus.mojo
- failsafe-maven-plugin
- 2.4.3-alpha-1
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+ 3.1.2
diff --git a/sdk-tests/src/test/java/io/dapr/it/BaseIT.java b/sdk-tests/src/test/java/io/dapr/it/BaseIT.java
index f8dc006be..c4f9d3cde 100644
--- a/sdk-tests/src/test/java/io/dapr/it/BaseIT.java
+++ b/sdk-tests/src/test/java/io/dapr/it/BaseIT.java
@@ -17,7 +17,7 @@ import io.dapr.actors.client.ActorClient;
import io.dapr.client.DaprApiProtocol;
import io.dapr.client.resiliency.ResiliencyOptions;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.AfterClass;
+import org.junit.jupiter.api.AfterAll;
import java.util.HashMap;
import java.util.LinkedList;
@@ -184,7 +184,7 @@ public abstract class BaseIT {
return runs;
}
- @AfterClass
+ @AfterAll
public static void cleanUp() throws Exception {
while (!TO_BE_CLOSED.isEmpty()) {
TO_BE_CLOSED.remove().close();
diff --git a/sdk-tests/src/test/java/io/dapr/it/actors/ActivationDeactivationIT.java b/sdk-tests/src/test/java/io/dapr/it/actors/ActivationDeactivationIT.java
index 0565da9cb..f57ce0905 100644
--- a/sdk-tests/src/test/java/io/dapr/it/actors/ActivationDeactivationIT.java
+++ b/sdk-tests/src/test/java/io/dapr/it/actors/ActivationDeactivationIT.java
@@ -18,7 +18,7 @@ import io.dapr.actors.client.ActorProxyBuilder;
import io.dapr.it.BaseIT;
import io.dapr.it.actors.services.springboot.DemoActor;
import io.dapr.it.actors.services.springboot.DemoActorService;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -26,9 +26,9 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static io.dapr.it.Retry.callWithRetry;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ActivationDeactivationIT extends BaseIT {
@@ -62,14 +62,14 @@ public class ActivationDeactivationIT extends BaseIT {
logger.debug("Retrieving active Actors");
List activeActors = proxy.retrieveActiveActors();
logger.debug("Active actors: [" + activeActors.toString() + "]");
- assertTrue("Expecting actorId:[" + actorId1.toString() + "]", activeActors.contains(actorId1.toString()));
+ assertTrue(activeActors.contains(actorId1.toString()),"Expecting actorId:[" + actorId1.toString() + "]");
ActorId actorId2 = new ActorId(Integer.toString(atomicInteger.getAndIncrement()));
DemoActor proxy2 = proxyBuilder.build(actorId2);
callWithRetry(() -> {
List activeActorsSecondTry = proxy2.retrieveActiveActors();
logger.debug("Active actors: [" + activeActorsSecondTry.toString() + "]");
- assertFalse("NOT Expecting actorId:[" + actorId1.toString() + "]", activeActorsSecondTry.contains(actorId1.toString()));
+ assertFalse(activeActorsSecondTry.contains(actorId1.toString()), "NOT Expecting actorId:[" + actorId1.toString() + "]");
}, 15000);
}
}
diff --git a/sdk-tests/src/test/java/io/dapr/it/actors/ActorExceptionIT.java b/sdk-tests/src/test/java/io/dapr/it/actors/ActorExceptionIT.java
index c86b75b86..91c17459d 100644
--- a/sdk-tests/src/test/java/io/dapr/it/actors/ActorExceptionIT.java
+++ b/sdk-tests/src/test/java/io/dapr/it/actors/ActorExceptionIT.java
@@ -14,22 +14,17 @@ limitations under the License.
package io.dapr.it.actors;
import io.dapr.actors.ActorId;
-import io.dapr.actors.client.ActorProxy;
import io.dapr.actors.client.ActorProxyBuilder;
import io.dapr.it.BaseIT;
import io.dapr.it.actors.app.MyActor;
import io.dapr.it.actors.app.MyActorService;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.ExecutionException;
-
import static io.dapr.it.Retry.callWithRetry;
-import static io.dapr.it.TestUtils.assertThrowsDaprException;
import static io.dapr.it.TestUtils.assertThrowsDaprExceptionSubstring;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+
public class ActorExceptionIT extends BaseIT {
@@ -59,8 +54,5 @@ public class ActorExceptionIT extends BaseIT {
"INTERNAL: error invoke actor method: error from actor service",
() -> proxy.throwException());
}, 5000);
-
-
-
}
}
diff --git a/sdk-tests/src/test/java/io/dapr/it/actors/ActorMethodNameIT.java b/sdk-tests/src/test/java/io/dapr/it/actors/ActorMethodNameIT.java
index 8c631e704..65c6232c8 100644
--- a/sdk-tests/src/test/java/io/dapr/it/actors/ActorMethodNameIT.java
+++ b/sdk-tests/src/test/java/io/dapr/it/actors/ActorMethodNameIT.java
@@ -19,12 +19,12 @@ import io.dapr.actors.client.ActorProxyBuilder;
import io.dapr.it.BaseIT;
import io.dapr.it.actors.app.MyActor;
import io.dapr.it.actors.app.MyActorService;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.dapr.it.Retry.callWithRetry;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ActorMethodNameIT extends BaseIT {
diff --git a/sdk-tests/src/test/java/io/dapr/it/actors/ActorReminderFailoverIT.java b/sdk-tests/src/test/java/io/dapr/it/actors/ActorReminderFailoverIT.java
index 5bf04c6ec..efd9aebac 100644
--- a/sdk-tests/src/test/java/io/dapr/it/actors/ActorReminderFailoverIT.java
+++ b/sdk-tests/src/test/java/io/dapr/it/actors/ActorReminderFailoverIT.java
@@ -19,9 +19,9 @@ import io.dapr.actors.client.ActorProxyBuilder;
import io.dapr.it.BaseIT;
import io.dapr.it.DaprRun;
import io.dapr.it.actors.app.MyActorService;
-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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,7 +31,7 @@ import java.util.UUID;
import static io.dapr.it.actors.MyActorTestUtils.countMethodCalls;
import static io.dapr.it.actors.MyActorTestUtils.fetchMethodCallLogs;
import static io.dapr.it.actors.MyActorTestUtils.validateMethodCalls;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class ActorReminderFailoverIT extends BaseIT {
@@ -47,7 +47,7 @@ public class ActorReminderFailoverIT extends BaseIT {
private DaprRun clientAppRun;
- @Before
+ @BeforeEach
public void init() throws Exception {
firstAppRun = startDaprApp(
ActorReminderFailoverIT.class.getSimpleName() + "One",
@@ -78,7 +78,7 @@ public class ActorReminderFailoverIT extends BaseIT {
proxy = proxyBuilder.build(actorId);
}
- @After
+ @AfterEach
public void tearDown() {
// call unregister
logger.debug("Calling actor method 'stopReminder' to unregister reminder");
diff --git a/sdk-tests/src/test/java/io/dapr/it/actors/ActorReminderRecoveryIT.java b/sdk-tests/src/test/java/io/dapr/it/actors/ActorReminderRecoveryIT.java
index 0f4ce44ee..daaeefaab 100644
--- a/sdk-tests/src/test/java/io/dapr/it/actors/ActorReminderRecoveryIT.java
+++ b/sdk-tests/src/test/java/io/dapr/it/actors/ActorReminderRecoveryIT.java
@@ -22,21 +22,23 @@ import io.dapr.it.DaprRun;
import io.dapr.it.actors.app.ActorReminderDataParam;
import io.dapr.it.actors.app.MyActorService;
import org.apache.commons.lang3.tuple.ImmutablePair;
-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.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.*;
+import java.util.stream.Stream;
import static io.dapr.it.Retry.callWithRetry;
import static io.dapr.it.actors.MyActorTestUtils.*;
-@RunWith(Parameterized.class)
public class ActorReminderRecoveryIT extends BaseIT {
private static final Logger logger = LoggerFactory.getLogger(ActorReminderRecoveryIT.class);
@@ -49,38 +51,30 @@ public class ActorReminderRecoveryIT extends BaseIT {
*
* @return Collection of parameter tuples.
*/
- @Parameterized.Parameters
- public static Collection
-
- junit
- junit
- test
-
org.mockito
mockito-core
diff --git a/sdk-workflows/src/test/java/io/dapr/workflows/DaprWorkflowContextImplTest.java b/sdk-workflows/src/test/java/io/dapr/workflows/DaprWorkflowContextImplTest.java
index e584acead..6da3756ca 100644
--- a/sdk-workflows/src/test/java/io/dapr/workflows/DaprWorkflowContextImplTest.java
+++ b/sdk-workflows/src/test/java/io/dapr/workflows/DaprWorkflowContextImplTest.java
@@ -17,8 +17,9 @@ import com.microsoft.durabletask.RetryPolicy;
import com.microsoft.durabletask.Task;
import com.microsoft.durabletask.TaskOptions;
import com.microsoft.durabletask.TaskOrchestrationContext;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import java.time.Duration;
@@ -31,12 +32,13 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static org.junit.jupiter.api.Assertions.assertThrows;
public class DaprWorkflowContextImplTest {
private DaprWorkflowContextImpl context;
private TaskOrchestrationContext mockInnerContext;
- @Before
+ @BeforeEach
public void setUp() {
mockInnerContext = mock(TaskOrchestrationContext.class);
context = new DaprWorkflowContextImpl(mockInnerContext);
@@ -87,15 +89,17 @@ public class DaprWorkflowContextImplTest {
verify(mockInnerContext, times(1)).callActivity(expectedName, expectedInput, null, String.class);
}
-
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void DaprWorkflowContextWithEmptyInnerContext() {
- context = new DaprWorkflowContextImpl(mockInnerContext, null);
- }
+ assertThrows(IllegalArgumentException.class, () -> {
+ context = new DaprWorkflowContextImpl(mockInnerContext, null);
+ }); }
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void DaprWorkflowContextWithEmptyLogger() {
- context = new DaprWorkflowContextImpl(null, null);
+ assertThrows(IllegalArgumentException.class, () -> {
+ context = new DaprWorkflowContextImpl(null, null);
+ });
}
@Test
@@ -170,9 +174,9 @@ public class DaprWorkflowContextImplTest {
verify(mockInnerContext, times(1)).createTimer(Duration.ofSeconds(10));
}
- @Test(expected = UnsupportedOperationException.class)
+ @Test
public void createTimerWithZonedDateTimeThrowsTest() {
- context.createTimer(ZonedDateTime.now());
+ assertThrows(UnsupportedOperationException.class, () -> context.createTimer(ZonedDateTime.now()));
}
@Test
diff --git a/sdk-workflows/src/test/java/io/dapr/workflows/client/DaprWorkflowClientTest.java b/sdk-workflows/src/test/java/io/dapr/workflows/client/DaprWorkflowClientTest.java
index c5fb789ee..50b69f93b 100644
--- a/sdk-workflows/src/test/java/io/dapr/workflows/client/DaprWorkflowClientTest.java
+++ b/sdk-workflows/src/test/java/io/dapr/workflows/client/DaprWorkflowClientTest.java
@@ -20,17 +20,17 @@ import io.dapr.workflows.Workflow;
import io.dapr.workflows.WorkflowContext;
import io.dapr.workflows.WorkflowStub;
import io.grpc.ManagedChannel;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.time.Duration;
import java.util.Arrays;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -50,7 +50,7 @@ public class DaprWorkflowClientTest {
}
}
- @BeforeClass
+ @BeforeAll
public static void beforeAll() {
constructor =
Constructor.class.cast(Arrays.stream(DaprWorkflowClient.class.getDeclaredConstructors())
@@ -60,7 +60,7 @@ public class DaprWorkflowClientTest {
}).findFirst().get());
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
mockInnerClient = mock(DurableTaskClient.class);
mockGrpcChannel = mock(ManagedChannel.class);
diff --git a/sdk-workflows/src/test/java/io/dapr/workflows/runtime/OrchestratorWrapperTest.java b/sdk-workflows/src/test/java/io/dapr/workflows/runtime/OrchestratorWrapperTest.java
index 6d6efa15a..4921d8d6e 100644
--- a/sdk-workflows/src/test/java/io/dapr/workflows/runtime/OrchestratorWrapperTest.java
+++ b/sdk-workflows/src/test/java/io/dapr/workflows/runtime/OrchestratorWrapperTest.java
@@ -18,8 +18,8 @@ import com.microsoft.durabletask.TaskOrchestrationContext;
import io.dapr.workflows.Workflow;
import io.dapr.workflows.WorkflowContext;
import io.dapr.workflows.WorkflowStub;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -37,7 +37,7 @@ public class OrchestratorWrapperTest {
@Test
public void getName() {
OrchestratorWrapper wrapper = new OrchestratorWrapper<>(TestWorkflow.class);
- Assert.assertEquals(
+ Assertions.assertEquals(
"io.dapr.workflows.runtime.OrchestratorWrapperTest.TestWorkflow",
wrapper.getName()
);
diff --git a/sdk-workflows/src/test/java/io/dapr/workflows/runtime/WorkflowRuntimeBuilderTest.java b/sdk-workflows/src/test/java/io/dapr/workflows/runtime/WorkflowRuntimeBuilderTest.java
index 23fb5254a..faded869b 100644
--- a/sdk-workflows/src/test/java/io/dapr/workflows/runtime/WorkflowRuntimeBuilderTest.java
+++ b/sdk-workflows/src/test/java/io/dapr/workflows/runtime/WorkflowRuntimeBuilderTest.java
@@ -3,7 +3,7 @@ package io.dapr.workflows.runtime;
import io.dapr.workflows.Workflow;
import io.dapr.workflows.WorkflowStub;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
diff --git a/sdk-workflows/src/test/java/io/dapr/workflows/runtime/WorkflowRuntimeTest.java b/sdk-workflows/src/test/java/io/dapr/workflows/runtime/WorkflowRuntimeTest.java
index 63fdf42e4..42e2b7489 100644
--- a/sdk-workflows/src/test/java/io/dapr/workflows/runtime/WorkflowRuntimeTest.java
+++ b/sdk-workflows/src/test/java/io/dapr/workflows/runtime/WorkflowRuntimeTest.java
@@ -18,7 +18,7 @@ import com.microsoft.durabletask.DurableTaskGrpcWorker;
import com.microsoft.durabletask.DurableTaskGrpcWorkerBuilder;
import io.dapr.workflows.Workflow;
import io.dapr.workflows.WorkflowStub;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
diff --git a/sdk/pom.xml b/sdk/pom.xml
index 27929e24a..66520bcef 100644
--- a/sdk/pom.xml
+++ b/sdk/pom.xml
@@ -46,16 +46,16 @@
reactor-core
3.5.0
+
+ io.projectreactor
+ reactor-test
+ 3.5.0
+
com.squareup.okhttp3
okhttp
4.9.0
-
- junit
- junit
- test
-
org.mockito
mockito-core
@@ -87,8 +87,12 @@
org.junit.jupiter
- junit-jupiter-engine
- 5.7.0
+ junit-jupiter
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-params
test
@@ -109,6 +113,17 @@
${grpc.version}
test
+
+ uk.org.webcompere
+ system-stubs-jupiter
+ 2.1.1
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-migrationsupport
+ test
+
diff --git a/sdk/src/main/java/io/dapr/client/DaprHttp.java b/sdk/src/main/java/io/dapr/client/DaprHttp.java
index 9b1fc374a..d6e92956d 100644
--- a/sdk/src/main/java/io/dapr/client/DaprHttp.java
+++ b/sdk/src/main/java/io/dapr/client/DaprHttp.java
@@ -102,7 +102,7 @@ public class DaprHttp implements AutoCloseable {
*/
public Response(byte[] body, Map headers, int statusCode) {
this.body = body == null ? EMPTY_BYTES : Arrays.copyOf(body, body.length);
- this.headers = headers;
+ this.headers = headers == null ? null : Collections.unmodifiableMap(headers);
this.statusCode = statusCode;
}
diff --git a/sdk/src/main/java/io/dapr/client/domain/BulkSubscribeAppResponse.java b/sdk/src/main/java/io/dapr/client/domain/BulkSubscribeAppResponse.java
index 5043aa070..511e3468f 100644
--- a/sdk/src/main/java/io/dapr/client/domain/BulkSubscribeAppResponse.java
+++ b/sdk/src/main/java/io/dapr/client/domain/BulkSubscribeAppResponse.java
@@ -17,6 +17,7 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
/**
@@ -32,8 +33,7 @@ public final class BulkSubscribeAppResponse {
@JsonCreator
public BulkSubscribeAppResponse(
@JsonProperty("statuses") List statuses) {
- this.statuses = new ArrayList<>();
- this.statuses.addAll(statuses);
+ this.statuses = Collections.unmodifiableList(statuses);
}
public List getStatuses() {
diff --git a/sdk/src/main/java/io/dapr/client/domain/GetBulkStateRequest.java b/sdk/src/main/java/io/dapr/client/domain/GetBulkStateRequest.java
index 47a20e2e0..2f5270879 100644
--- a/sdk/src/main/java/io/dapr/client/domain/GetBulkStateRequest.java
+++ b/sdk/src/main/java/io/dapr/client/domain/GetBulkStateRequest.java
@@ -27,7 +27,7 @@ public class GetBulkStateRequest {
private final List keys;
- private Map metadata;
+ private Map metadata = Collections.emptyMap();
private int parallelism = 1;
diff --git a/sdk/src/main/java/io/dapr/client/domain/GetConfigurationRequest.java b/sdk/src/main/java/io/dapr/client/domain/GetConfigurationRequest.java
index a8de2bd61..78235230c 100644
--- a/sdk/src/main/java/io/dapr/client/domain/GetConfigurationRequest.java
+++ b/sdk/src/main/java/io/dapr/client/domain/GetConfigurationRequest.java
@@ -33,7 +33,7 @@ public class GetConfigurationRequest {
*/
public GetConfigurationRequest(String storeName, List keys) {
this.storeName = storeName;
- this.keys = keys == null ? Collections.EMPTY_LIST : Collections.unmodifiableList(keys);
+ this.keys = keys == null ? Collections.emptyList() : Collections.unmodifiableList(keys);
}
public GetConfigurationRequest setMetadata(Map metadata) {
diff --git a/sdk/src/main/java/io/dapr/client/domain/PublishEventRequest.java b/sdk/src/main/java/io/dapr/client/domain/PublishEventRequest.java
index fbb58bdbf..a2e65955a 100644
--- a/sdk/src/main/java/io/dapr/client/domain/PublishEventRequest.java
+++ b/sdk/src/main/java/io/dapr/client/domain/PublishEventRequest.java
@@ -30,7 +30,7 @@ public class PublishEventRequest {
private String contentType;
- private Map metadata = new HashMap<>();
+ private Map metadata = Collections.emptyMap();
/**
* Constructor for PublishEventRequest.
diff --git a/sdk/src/main/java/io/dapr/client/domain/State.java b/sdk/src/main/java/io/dapr/client/domain/State.java
index 3ec521773..ae087d986 100644
--- a/sdk/src/main/java/io/dapr/client/domain/State.java
+++ b/sdk/src/main/java/io/dapr/client/domain/State.java
@@ -13,6 +13,7 @@ limitations under the License.
package io.dapr.client.domain;
+import java.util.Collections;
import java.util.Map;
/**
@@ -116,7 +117,7 @@ public class State {
this.value = value;
this.key = key;
this.etag = etag;
- this.metadata = metadata;
+ this.metadata = metadata == null ? null : Collections.unmodifiableMap(metadata);
this.options = options;
this.error = null;
}
diff --git a/sdk/src/main/java/io/dapr/client/domain/SubscribeConfigurationRequest.java b/sdk/src/main/java/io/dapr/client/domain/SubscribeConfigurationRequest.java
index 25118c400..9b7e5545b 100644
--- a/sdk/src/main/java/io/dapr/client/domain/SubscribeConfigurationRequest.java
+++ b/sdk/src/main/java/io/dapr/client/domain/SubscribeConfigurationRequest.java
@@ -33,7 +33,7 @@ public class SubscribeConfigurationRequest {
*/
public SubscribeConfigurationRequest(String storeName, List keys) {
this.storeName = storeName;
- this.keys = keys == null ? Collections.EMPTY_LIST : Collections.unmodifiableList(keys);
+ this.keys = keys == null ? Collections.emptyList() : Collections.unmodifiableList(keys);
}
public SubscribeConfigurationRequest setMetadata(Map metadata) {
diff --git a/sdk/src/main/java/io/dapr/client/domain/TransactionalStateRequest.java b/sdk/src/main/java/io/dapr/client/domain/TransactionalStateRequest.java
index 6eb5969fa..e0c3fdced 100644
--- a/sdk/src/main/java/io/dapr/client/domain/TransactionalStateRequest.java
+++ b/sdk/src/main/java/io/dapr/client/domain/TransactionalStateRequest.java
@@ -39,12 +39,12 @@ public class TransactionalStateRequest {
* @param metadata Metadata used for transactional operations.
*/
public TransactionalStateRequest(List> operations, Map metadata) {
- this.operations = operations;
- this.metadata = metadata;
+ this.operations = operations == null ? null : Collections.unmodifiableList(operations);
+ this.metadata = metadata == null ? null : Collections.unmodifiableMap(metadata);
}
public List> getOperations() {
- return Collections.unmodifiableList(operations);
+ return operations;
}
public Map getMetadata() {
diff --git a/sdk/src/test/java/io/dapr/client/CloudEventCustomTest.java b/sdk/src/test/java/io/dapr/client/CloudEventCustomTest.java
index 35282bbf3..3d62fcfbd 100644
--- a/sdk/src/test/java/io/dapr/client/CloudEventCustomTest.java
+++ b/sdk/src/test/java/io/dapr/client/CloudEventCustomTest.java
@@ -13,11 +13,11 @@ limitations under the License.
package io.dapr.client;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import io.dapr.serializer.DaprObjectSerializer;
import io.dapr.serializer.DefaultObjectSerializer;
diff --git a/sdk/src/test/java/io/dapr/client/CloudEventTest.java b/sdk/src/test/java/io/dapr/client/CloudEventTest.java
index 5a71b3968..fac624dab 100644
--- a/sdk/src/test/java/io/dapr/client/CloudEventTest.java
+++ b/sdk/src/test/java/io/dapr/client/CloudEventTest.java
@@ -15,11 +15,11 @@ package io.dapr.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dapr.client.domain.CloudEvent;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class CloudEventTest {
diff --git a/sdk/src/test/java/io/dapr/client/DaprClientBuilderTest.java b/sdk/src/test/java/io/dapr/client/DaprClientBuilderTest.java
index c543c1b93..2b31a8879 100644
--- a/sdk/src/test/java/io/dapr/client/DaprClientBuilderTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprClientBuilderTest.java
@@ -14,9 +14,11 @@ limitations under the License.
package io.dapr.client;
import io.dapr.serializer.DaprObjectSerializer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -34,19 +36,19 @@ public class DaprClientBuilderTest {
assertNotNull(daprClient);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void noObjectSerializer() {
- new DaprClientBuilder().withObjectSerializer(null);
+ assertThrows(IllegalArgumentException.class, () -> { new DaprClientBuilder().withObjectSerializer(null);});
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void blankContentTypeInObjectSerializer() {
- new DaprClientBuilder().withObjectSerializer(mock(DaprObjectSerializer.class));
+ assertThrows(IllegalArgumentException.class, () -> { new DaprClientBuilder().withObjectSerializer(mock(DaprObjectSerializer.class));});
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void noStateSerializer() {
- new DaprClientBuilder().withStateSerializer(null);
+ assertThrows(IllegalArgumentException.class, () -> { new DaprClientBuilder().withStateSerializer(null);});
}
}
diff --git a/sdk/src/test/java/io/dapr/client/DaprClientGrpcTelemetryTest.java b/sdk/src/test/java/io/dapr/client/DaprClientGrpcTelemetryTest.java
index fedae450d..9c835a3b1 100644
--- a/sdk/src/test/java/io/dapr/client/DaprClientGrpcTelemetryTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprClientGrpcTelemetryTest.java
@@ -29,26 +29,26 @@ import io.grpc.ServerServiceDefinition;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.testing.GrpcCleanupRule;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Rule;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
-import java.io.Closeable;
import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collection;
+import java.util.stream.Stream;
+
import reactor.util.context.ContextView;
-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;
-@RunWith(Parameterized.class)
+@EnableRuleMigrationSupport
public class DaprClientGrpcTelemetryTest {
private static final Metadata.Key GRPC_TRACE_BIN_KEY = Metadata.Key.of(Headers.GRPC_TRACE_BIN,
@@ -69,62 +69,42 @@ public class DaprClientGrpcTelemetryTest {
private DaprClient client;
- @Parameterized.Parameter
- public Scenario scenario;
-
- @Parameterized.Parameters
- public static Collection data() {
- return Arrays.asList(new Scenario[][]{
- {
- new Scenario() {{
- traceparent = "00-0af7651916cd43dd8448eb211c80319c-b9c7c989f97918e1-01";
- tracestate = "congo=ucfJifl5GOE,rojo=00f067aa0ba902b7";
- expectGrpcTraceBin = true;
- }}
- },
- {
- new Scenario() {{
- traceparent = null;
- tracestate = null;
- expectGrpcTraceBin = false;
- }}
- },
- {
- new Scenario() {{
- traceparent = null;
- tracestate = "congo=ucfJifl5GOE,rojo=00f067aa0ba902b7";
- expectGrpcTraceBin = false;
- }}
- },
- {
- new Scenario() {{
- traceparent = "00-0af7651916cd43dd8448eb211c80319c-b9c7c989f97918e1-01";
- tracestate = null;
- expectGrpcTraceBin = true;
- }},
- },
- {
- new Scenario() {{
- traceparent = "BAD FORMAT";
- tracestate = null;
- expectGrpcTraceBin = false;
- }},
- },
- {
- new Scenario() {{
- traceparent = "00-0af7651916cd43dd8448eb211c80319c-b9c7c989f97918e1-01";
- tracestate = "INVALID";
- expectGrpcTraceBin = false;
- }},
- },
- {
- null
- }
- });
+ public static Stream data() {
+ return Stream.of(
+ Arguments.of(
+ "00-0af7651916cd43dd8448eb211c80319c-b9c7c989f97918e1-01",
+ "congo=ucfJifl5GOE,rojo=00f067aa0ba902b7",
+ true
+ ),
+ Arguments.of(
+null,
+ null,
+ false
+ ),
+ Arguments.of(
+ null,
+ "congo=ucfJifl5GOE,rojo=00f067aa0ba902b7",
+ false
+ ),
+ Arguments.of(
+ "00-0af7651916cd43dd8448eb211c80319c-b9c7c989f97918e1-01",
+ null,
+ true
+ ),
+ Arguments.of(
+ "BAD FORMAT",
+ null,
+ false
+ ),
+ Arguments.of(
+ "00-0af7651916cd43dd8448eb211c80319c-b9c7c989f97918e1-01",
+ "INVALID",
+ false
+ )
+ );
}
- @Before
- public void setup() throws IOException {
+ public void setup(String traceparent, String tracestate, boolean expectGrpcTraceBin) throws IOException {
DaprGrpc.DaprImplBase daprImplBase = new DaprGrpc.DaprImplBase() {
public void invokeService(io.dapr.v1.DaprProtos.InvokeServiceRequest request,
@@ -140,16 +120,10 @@ public class DaprClientGrpcTelemetryTest {
public ServerCall.Listener interceptCall(ServerCall serverCall,
Metadata metadata,
ServerCallHandler serverCallHandler) {
- if (scenario == null) {
- assertNull(metadata.get(TRACEPARENT_KEY));
- assertNull(metadata.get(TRACESTATE_KEY));
- assertNull(metadata.get(GRPC_TRACE_BIN_KEY));
- return serverCallHandler.startCall(serverCall, metadata);
- }
- assertEquals(scenario.traceparent, metadata.get(TRACEPARENT_KEY));
- assertEquals(scenario.tracestate, metadata.get(TRACESTATE_KEY));
- assertTrue((metadata.get(GRPC_TRACE_BIN_KEY) != null) == scenario.expectGrpcTraceBin);
+ assertEquals(traceparent, metadata.get(TRACEPARENT_KEY));
+ assertEquals(tracestate, metadata.get(TRACESTATE_KEY));
+ assertEquals((metadata.get(GRPC_TRACE_BIN_KEY) != null), expectGrpcTraceBin);
return serverCallHandler.startCall(serverCall, metadata);
}
});
@@ -168,35 +142,81 @@ public class DaprClientGrpcTelemetryTest {
new GrpcChannelFacade(channel), asyncStub, new DefaultObjectSerializer(), new DefaultObjectSerializer());
}
- @Test
- public void invokeServiceVoidWithTracingTest() {
- Context context = null;
- if (scenario != null) {
- context = Context.empty();
- if (scenario.traceparent != null) {
- context = context.put("traceparent", scenario.traceparent);
+ public void setup() throws IOException {
+ DaprGrpc.DaprImplBase daprImplBase = new DaprGrpc.DaprImplBase() {
+
+ public void invokeService(io.dapr.v1.DaprProtos.InvokeServiceRequest request,
+ io.grpc.stub.StreamObserver responseObserver) {
+ responseObserver.onNext(CommonProtos.InvokeResponse.getDefaultInstance());
+ responseObserver.onCompleted();
}
- if (scenario.tracestate != null) {
- context = context.put("tracestate", scenario.tracestate);
+
+ };
+
+ ServerServiceDefinition service = ServerInterceptors.intercept(daprImplBase, new ServerInterceptor() {
+ @Override
+ public ServerCall.Listener interceptCall(ServerCall serverCall,
+ Metadata metadata,
+ ServerCallHandler serverCallHandler) {
+
+ assertNull(metadata.get(TRACEPARENT_KEY));
+ assertNull(metadata.get(TRACESTATE_KEY));
+ assertNull(metadata.get(GRPC_TRACE_BIN_KEY));
+ return serverCallHandler.startCall(serverCall, metadata);
+
}
- }
+ });
+
+ // Generate a unique in-process server name.
+ String serverName = InProcessServerBuilder.generateName();
+ // Create a server, add service, start, and register for automatic graceful shutdown.
+ grpcCleanup.register(InProcessServerBuilder.forName(serverName).directExecutor()
+ .addService(service)
+ .build().start());
+
+ // Create a client channel and register for automatic graceful shutdown.
+ ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build();
+ DaprGrpc.DaprStub asyncStub = DaprGrpc.newStub(channel);
+ client = new DaprClientGrpc(
+ new GrpcChannelFacade(channel), asyncStub, new DefaultObjectSerializer(), new DefaultObjectSerializer());
+ }
+
+ @ParameterizedTest
+ @MethodSource("data")
+ public void invokeServiceVoidWithTracingTest(String traceparent, String tracestate, boolean expectGrpcTraceBin) throws IOException {
+ // setup server
+ setup(traceparent, tracestate, expectGrpcTraceBin);
+
+ Context context = Context.empty();
+ if (traceparent != null) {
+ context = context.put("traceparent", traceparent);
+ }
+ if (tracestate != null) {
+ context = context.put("tracestate", tracestate);
+ }
+
final Context contextCopy = context;
InvokeMethodRequest req = new InvokeMethodRequest("appId", "method")
.setBody("request")
.setHttpExtension(HttpExtension.NONE);
Mono result = this.client.invokeMethod(req, TypeRef.get(Void.class))
- .contextWrite(it -> it.putAll(contextCopy == null ? (ContextView) Context.empty() : contextCopy));
+ .contextWrite(it -> it.putAll(contextCopy));
result.block();
}
- @After
- public void tearDown() throws Exception {
- client.close();
- }
+ @Test
+ public void invokeServiceVoidWithTracingTestAndEmptyContext() throws IOException {
+ // setup server
+ setup();
- public static class Scenario {
- public String traceparent;
- public String tracestate;
- public boolean expectGrpcTraceBin;
+ Context context = null;
+
+ final Context contextCopy = context;
+ InvokeMethodRequest req = new InvokeMethodRequest("appId", "method")
+ .setBody("request")
+ .setHttpExtension(HttpExtension.NONE);
+ Mono result = this.client.invokeMethod(req, TypeRef.get(Void.class))
+ .contextWrite(it -> it.putAll(contextCopy == null ? (ContextView) Context.empty() : contextCopy));
+ result.block();
}
}
diff --git a/sdk/src/test/java/io/dapr/client/DaprClientGrpcTest.java b/sdk/src/test/java/io/dapr/client/DaprClientGrpcTest.java
index 0948a4cd6..bff92e405 100644
--- a/sdk/src/test/java/io/dapr/client/DaprClientGrpcTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprClientGrpcTest.java
@@ -38,9 +38,9 @@ import io.dapr.v1.DaprProtos;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
-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 org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.mockito.ArgumentMatchers;
@@ -62,8 +62,14 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static io.dapr.utils.TestUtils.assertThrowsDaprException;
-import static org.junit.Assert.*;
+import static io.dapr.utils.TestUtils.findFreePort;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@@ -80,7 +86,7 @@ public class DaprClientGrpcTest {
private DaprClient client;
private ObjectSerializer serializer;
- @Before
+ @BeforeEach
public void setup() throws IOException {
channel = mock(GrpcChannelFacade.class);
daprStub = mock(DaprGrpc.DaprStub.class);
@@ -92,7 +98,7 @@ public class DaprClientGrpcTest {
doNothing().when(channel).close();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
client.close();
verify(channel).close();
@@ -583,7 +589,7 @@ public class DaprClientGrpcTest {
.build();
String expected = "Value";
- doAnswer((Answer) invocation -> {
+ doAnswer(invocation -> {
StreamObserver observer = (StreamObserver) invocation.getArguments()[1];
observer.onNext(CommonProtos.InvokeResponse.newBuilder().setData(getAny(expected)).build());
observer.onCompleted();
@@ -909,7 +915,7 @@ public class DaprClientGrpcTest {
String expectedValue = "Expected state";
State expectedState = buildStateKey(expectedValue, key, etag, new HashMap<>(), null);
DaprProtos.GetStateResponse responseEnvelope = buildGetStateResponse(expectedValue, etag);
- doAnswer((Answer) invocation -> {
+ doAnswer(invocation -> {
StreamObserver observer = (StreamObserver) invocation.getArguments()[1];
observer.onNext(responseEnvelope);
observer.onCompleted();
@@ -2127,10 +2133,10 @@ public class DaprClientGrpcTest {
Map cis = client.getConfiguration(CONFIG_STORE_NAME, "configkey1","configkey2").block();
assertEquals(2, cis.size());
- assertTrue("configkey1", cis.containsKey("configkey1"));
+ assertTrue(cis.containsKey("configkey1"), "configkey1");
assertEquals("configvalue1", cis.get("configkey1").getValue());
assertEquals("1", cis.get("configkey1").getVersion());
- assertTrue("configkey2", cis.containsKey("configkey2"));
+ assertTrue(cis.containsKey("configkey2"), "configkey2");
assertEquals("configvalue2", cis.get("configkey2").getValue());
assertEquals("1", cis.get("configkey2").getVersion());
}
@@ -2150,7 +2156,7 @@ public class DaprClientGrpcTest {
List keys = Arrays.asList("configkey1","configkey2");
Map cis = client.getConfiguration(CONFIG_STORE_NAME, keys, reqMetadata).block();
assertEquals(2, cis.size());
- assertTrue("configkey1", cis.containsKey("configkey1"));
+ assertTrue(cis.containsKey("configkey1"), "configkey1");
assertEquals("configvalue1", cis.get("configkey1").getValue());
}
diff --git a/sdk/src/test/java/io/dapr/client/DaprClientHttpTest.java b/sdk/src/test/java/io/dapr/client/DaprClientHttpTest.java
index 9988d6462..2e93cbc61 100644
--- a/sdk/src/test/java/io/dapr/client/DaprClientHttpTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprClientHttpTest.java
@@ -41,8 +41,8 @@ import okhttp3.mock.MockInterceptor;
import okhttp3.mock.matchers.Matcher;
import okio.Buffer;
import okio.BufferedSink;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
@@ -62,11 +62,11 @@ import reactor.util.context.ContextView;
import static io.dapr.utils.TestUtils.assertThrowsDaprException;
import static io.dapr.utils.TestUtils.findFreePort;
-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.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.assertThrows;
import static org.mockito.Mockito.mock;
@@ -91,7 +91,7 @@ public class DaprClientHttpTest {
private MockInterceptor mockInterceptor;
- @Before
+ @BeforeEach
public void setUp() {
mockInterceptor = new MockInterceptor(Behavior.UNORDERED);
okHttpClient = new OkHttpClient.Builder().addInterceptor(mockInterceptor).build();
diff --git a/sdk/src/test/java/io/dapr/client/DaprClientProxyTest.java b/sdk/src/test/java/io/dapr/client/DaprClientProxyTest.java
index 807aa43bb..375e8b083 100644
--- a/sdk/src/test/java/io/dapr/client/DaprClientProxyTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprClientProxyTest.java
@@ -13,7 +13,7 @@ limitations under the License.
package io.dapr.client;
import io.dapr.client.domain.HttpExtension;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import reactor.core.publisher.Mono;
diff --git a/sdk/src/test/java/io/dapr/client/DaprHttpBuilderTest.java b/sdk/src/test/java/io/dapr/client/DaprHttpBuilderTest.java
index fa25398c3..e299cb083 100644
--- a/sdk/src/test/java/io/dapr/client/DaprHttpBuilderTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprHttpBuilderTest.java
@@ -14,12 +14,12 @@ limitations under the License.
package io.dapr.client;
import okhttp3.OkHttpClient;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
public class DaprHttpBuilderTest {
diff --git a/sdk/src/test/java/io/dapr/client/DaprHttpTest.java b/sdk/src/test/java/io/dapr/client/DaprHttpTest.java
index 4d475560c..562ca38d6 100644
--- a/sdk/src/test/java/io/dapr/client/DaprHttpTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprHttpTest.java
@@ -14,17 +14,20 @@ package io.dapr.client;
import io.dapr.config.Properties;
import io.dapr.exceptions.DaprException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.extension.ExtendWith;
+import reactor.test.StepVerifier;
import reactor.util.context.Context;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.mock.Behavior;
import okhttp3.mock.MockInterceptor;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.contrib.java.lang.system.EnvironmentVariables;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
+import uk.org.webcompere.systemstubs.environment.EnvironmentVariables;
+import uk.org.webcompere.systemstubs.jupiter.SystemStub;
+import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
import java.io.IOException;
import java.util.Collections;
@@ -32,14 +35,15 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-
+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.fail;
+@ExtendWith(SystemStubsExtension.class)
public class DaprHttpTest {
- @Rule
+ @SystemStub
public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
private static final String STATE_PATH = DaprHttp.API_VERSION + "/state";
@@ -53,7 +57,7 @@ public class DaprHttpTest {
private ObjectSerializer serializer = new ObjectSerializer();
- @Before
+ @BeforeEach
public void setUp() {
mockInterceptor = new MockInterceptor(Behavior.UNORDERED);
okHttpClient = new OkHttpClient.Builder().addInterceptor(mockInterceptor).build();
@@ -164,7 +168,7 @@ public class DaprHttpTest {
assertEquals(EXPECTED_RESULT, body);
}
- @Test(expected = RuntimeException.class)
+ @Test
public void invokePostMethodRuntime() throws IOException {
mockInterceptor.addRule()
.post("http://127.0.0.1:3500/v1.0/state")
@@ -172,26 +176,21 @@ public class DaprHttpTest {
DaprHttp daprHttp = new DaprHttp(Properties.SIDECAR_IP.get(), 3500, okHttpClient);
Mono mono =
daprHttp.invokeApi("POST", "v1.0/state".split("/"), null, null, Context.empty());
- DaprHttp.Response response = mono.block();
- String body = serializer.deserialize(response.getBody(), String.class);
- assertEquals(EXPECTED_RESULT, body);
+ StepVerifier.create(mono).expectError(RuntimeException.class);
}
- @Test(expected = RuntimeException.class)
+ @Test
public void invokePostDaprError() throws IOException {
-
mockInterceptor.addRule()
.post("http://127.0.0.1:3500/v1.0/state")
.respond(500, ResponseBody.create(MediaType.parse("text"),
"{\"errorCode\":null,\"message\":null}"));
DaprHttp daprHttp = new DaprHttp(Properties.SIDECAR_IP.get(), 3500, okHttpClient);
Mono mono = daprHttp.invokeApi("POST", "v1.0/state".split("/"), null, null, Context.empty());
- DaprHttp.Response response = mono.block();
- String body = serializer.deserialize(response.getBody(), String.class);
- assertEquals(EXPECTED_RESULT, body);
+ StepVerifier.create(mono).expectError(RuntimeException.class);
}
- @Test(expected = RuntimeException.class)
+ @Test
public void invokePostMethodUnknownError() throws IOException {
mockInterceptor.addRule()
.post("http://127.0.0.1:3500/v1.0/state")
@@ -199,9 +198,7 @@ public class DaprHttpTest {
"{\"errorCode\":\"null\",\"message\":\"null\"}"));
DaprHttp daprHttp = new DaprHttp(Properties.SIDECAR_IP.get(), 3500, okHttpClient);
Mono mono = daprHttp.invokeApi("POST", "v1.0/state".split("/"), null, null, Context.empty());
- DaprHttp.Response response = mono.block();
- String body = serializer.deserialize(response.getBody(), String.class);
- assertEquals(EXPECTED_RESULT, body);
+ StepVerifier.create(mono).expectError(RuntimeException.class);
}
/**
diff --git a/sdk/src/test/java/io/dapr/client/DaprPreviewClientGrpcTest.java b/sdk/src/test/java/io/dapr/client/DaprPreviewClientGrpcTest.java
index 871e3dccd..1292de68c 100644
--- a/sdk/src/test/java/io/dapr/client/DaprPreviewClientGrpcTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprPreviewClientGrpcTest.java
@@ -32,15 +32,14 @@ import io.dapr.v1.DaprProtos;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
-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.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.stubbing.Answer;
import reactor.core.publisher.Mono;
-import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -50,8 +49,8 @@ import java.util.Map;
import java.util.concurrent.ExecutionException;
import static io.dapr.utils.TestUtils.assertThrowsDaprException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
@@ -64,16 +63,20 @@ import static org.mockito.Mockito.when;
public class DaprPreviewClientGrpcTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
+
private static final String QUERY_STORE_NAME = "testQueryStore";
+
private static final String PUBSUB_NAME = "testPubsub";
+
private static final String TOPIC_NAME = "testTopic";
+
private static final String LOCK_STORE_NAME = "MyLockStore";
private GrpcChannelFacade channel;
private DaprGrpc.DaprStub daprStub;
private DaprPreviewClient previewClient;
- @Before
+ @BeforeEach
public void setup() throws IOException {
channel = mock(GrpcChannelFacade.class);
daprStub = mock(DaprGrpc.DaprStub.class);
@@ -83,7 +86,7 @@ public class DaprPreviewClientGrpcTest {
doNothing().when(channel).close();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
previewClient.close();
verify(channel).close();
@@ -121,7 +124,7 @@ public class DaprPreviewClientGrpcTest {
Collections.EMPTY_LIST)).block());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void publishEventsContentTypeMismatchException() throws IOException {
DaprObjectSerializer mockSerializer = mock(DaprObjectSerializer.class);
doAnswer((Answer) invocation -> {
@@ -137,7 +140,8 @@ public class DaprPreviewClientGrpcTest {
, "application/octet-stream", null);
BulkPublishRequest wrongReq = new BulkPublishRequest<>(PUBSUB_NAME, TOPIC_NAME,
Collections.singletonList(entry));
- previewClient.publishEvents(wrongReq).block();
+
+ assertThrows(IllegalArgumentException.class, () -> previewClient.publishEvents(wrongReq).block());
}
@Test
@@ -182,8 +186,8 @@ public class DaprPreviewClientGrpcTest {
Collections.singletonList(entry));
Mono> result = previewClient.publishEvents(req);
BulkPublishResponse res = result.block();
- Assert.assertNotNull(res);
- assertEquals("expected no entry in failed entries list", 0, res.getFailedEntries().size());
+ Assertions.assertNotNull(res);
+ assertEquals( 0, res.getFailedEntries().size(), "expected no entry in failed entries list");
}
@Test
@@ -200,8 +204,8 @@ public class DaprPreviewClientGrpcTest {
Mono> result = previewClient.publishEvents(PUBSUB_NAME, TOPIC_NAME,
"text/plain", Collections.singletonList("test"));
BulkPublishResponse res = result.block();
- Assert.assertNotNull(res);
- assertEquals("expected no entries in failed entries list", 0, res.getFailedEntries().size());
+ Assertions.assertNotNull(res);
+ assertEquals( 0, res.getFailedEntries().size(), "expected no entries in failed entries list");
}
@Test
@@ -220,8 +224,8 @@ public class DaprPreviewClientGrpcTest {
put("ttlInSeconds", "123");
}}, Collections.singletonList("test"));
BulkPublishResponse res = result.block();
- Assert.assertNotNull(res);
- assertEquals("expected no entry in failed entries list", 0, res.getFailedEntries().size());
+ Assertions.assertNotNull(res);
+ assertEquals( 0, res.getFailedEntries().size(), "expected no entry in failed entries list");
}
@Test
@@ -252,8 +256,8 @@ public class DaprPreviewClientGrpcTest {
BulkPublishRequest req = new BulkPublishRequest<>(PUBSUB_NAME, TOPIC_NAME,
Collections.singletonList(entry));
BulkPublishResponse result = previewClient.publishEvents(req).block();
- Assert.assertNotNull(result);
- Assert.assertEquals("expected no entries to be failed", 0, result.getFailedEntries().size());
+ Assertions.assertNotNull(result);
+ Assertions.assertEquals(0, result.getFailedEntries().size(), "expected no entries to be failed");
}
@Test
@@ -281,8 +285,8 @@ public class DaprPreviewClientGrpcTest {
BulkPublishRequest req = new BulkPublishRequest<>(PUBSUB_NAME, TOPIC_NAME,
Collections.singletonList(entry));
BulkPublishResponse result = previewClient.publishEvents(req).block();
- Assert.assertNotNull(result);
- Assert.assertEquals("expected no entries to be failed", 0, result.getFailedEntries().size());
+ Assertions.assertNotNull(result);
+ Assertions.assertEquals( 0, result.getFailedEntries().size(), "expected no entries to be failed");
}
@Test
@@ -312,8 +316,8 @@ public class DaprPreviewClientGrpcTest {
List> resp = new ArrayList<>();
resp.add(new QueryStateItem("1", (Object)"testData", "6f54ad94-dfb9-46f0-a371-e42d550adb7d"));
DaprProtos.QueryStateResponse responseEnvelope = buildQueryStateResponse(resp, "");
- doAnswer((Answer) invocation -> {
- DaprProtos.QueryStateRequest req = invocation.getArgument(0);
+ doAnswer(invocation -> {
+ DaprProtos.QueryStateRequest req = (DaprProtos.QueryStateRequest) invocation.getArgument(0);
assertEquals(QUERY_STORE_NAME, req.getStoreName());
assertEquals("query", req.getQuery());
assertEquals(0, req.getMetadataCount());
@@ -327,10 +331,10 @@ public class DaprPreviewClientGrpcTest {
QueryStateResponse response = previewClient.queryState(QUERY_STORE_NAME, "query", String.class).block();
assertNotNull(response);
- assertEquals("result size must be 1", 1, response.getResults().size());
- assertEquals("result must be same", "1", response.getResults().get(0).getKey());
- assertEquals("result must be same", "testData", response.getResults().get(0).getValue());
- assertEquals("result must be same", "6f54ad94-dfb9-46f0-a371-e42d550adb7d", response.getResults().get(0).getEtag());
+ assertEquals(1, response.getResults().size(), "result size must be 1");
+ assertEquals("1", response.getResults().get(0).getKey(), "result must be same");
+ assertEquals("testData", response.getResults().get(0).getValue(), "result must be same");
+ assertEquals("6f54ad94-dfb9-46f0-a371-e42d550adb7d", response.getResults().get(0).getEtag(), "result must be same");
}
@Test
@@ -338,8 +342,8 @@ public class DaprPreviewClientGrpcTest {
List> resp = new ArrayList<>();
resp.add(new QueryStateItem("1", null, "error data"));
DaprProtos.QueryStateResponse responseEnvelope = buildQueryStateResponse(resp, "");
- doAnswer((Answer) invocation -> {
- DaprProtos.QueryStateRequest req = invocation.getArgument(0);
+ doAnswer(invocation -> {
+ DaprProtos.QueryStateRequest req = (DaprProtos.QueryStateRequest) invocation.getArgument(0);
assertEquals(QUERY_STORE_NAME, req.getStoreName());
assertEquals("query", req.getQuery());
assertEquals(1, req.getMetadataCount());
@@ -355,9 +359,9 @@ public class DaprPreviewClientGrpcTest {
QueryStateResponse response = previewClient.queryState(QUERY_STORE_NAME, "query",
new HashMap(){{ put("key", "error"); }}, String.class).block();
assertNotNull(response);
- assertEquals("result size must be 1", 1, response.getResults().size());
- assertEquals("result must be same", "1", response.getResults().get(0).getKey());
- assertEquals("result must be same", "error data", response.getResults().get(0).getError());
+ assertEquals(1, response.getResults().size(), "result size must be 1");
+ assertEquals( "1", response.getResults().get(0).getKey(), "result must be same");
+ assertEquals( "error data", response.getResults().get(0).getError(), "result must be same");
}
@Test
diff --git a/sdk/src/test/java/io/dapr/client/DaprPreviewClientHttpTest.java b/sdk/src/test/java/io/dapr/client/DaprPreviewClientHttpTest.java
index 5d34ee330..c96e8260d 100644
--- a/sdk/src/test/java/io/dapr/client/DaprPreviewClientHttpTest.java
+++ b/sdk/src/test/java/io/dapr/client/DaprPreviewClientHttpTest.java
@@ -24,13 +24,13 @@ import io.dapr.utils.TypeRef;
import okhttp3.OkHttpClient;
import okhttp3.mock.Behavior;
import okhttp3.mock.MockInterceptor;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class DaprPreviewClientHttpTest {
@@ -45,7 +45,7 @@ public class DaprPreviewClientHttpTest {
private MockInterceptor mockInterceptor;
- @Before
+ @BeforeEach
public void setUp() {
mockInterceptor = new MockInterceptor(Behavior.UNORDERED);
okHttpClient = new OkHttpClient.Builder().addInterceptor(mockInterceptor).build();
@@ -99,10 +99,10 @@ public class DaprPreviewClientHttpTest {
+ "\"etag\": \"6f54ad94-dfb9-46f0-a371-e42d550adb7d\"}]}");
QueryStateResponse response = daprPreviewClientHttp.queryState("testStore", "query", String.class).block();
assertNotNull(response);
- assertEquals("result size must be 1", 1, response.getResults().size());
- assertEquals("result must be same", "1", response.getResults().get(0).getKey());
- assertEquals("result must be same", "testData", response.getResults().get(0).getValue());
- assertEquals("result must be same", "6f54ad94-dfb9-46f0-a371-e42d550adb7d", response.getResults().get(0).getEtag());
+ assertEquals(1, response.getResults().size(), "result size must be 1");
+ assertEquals( "1", response.getResults().get(0).getKey(), "result must be same");
+ assertEquals("testData", response.getResults().get(0).getValue(), "result must be same");
+ assertEquals( "6f54ad94-dfb9-46f0-a371-e42d550adb7d", response.getResults().get(0).getEtag(), "result must be same");
}
@Test
diff --git a/sdk/src/test/java/io/dapr/client/domain/BulkPublishRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/BulkPublishRequestTest.java
index 9033d9fe7..e4932c4e9 100644
--- a/sdk/src/test/java/io/dapr/client/domain/BulkPublishRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/BulkPublishRequestTest.java
@@ -13,8 +13,8 @@ limitations under the License.
package io.dapr.client.domain;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
@@ -22,7 +22,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class BulkPublishRequestTest {
@@ -38,6 +38,6 @@ public class BulkPublishRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- Assert.assertNotSame("Should not be same map", request.getMetadata(), initial);
+ Assertions.assertNotSame( request.getMetadata(), initial, "Should not be same map");
}
}
diff --git a/sdk/src/test/java/io/dapr/client/domain/DeleteStateRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/DeleteStateRequestTest.java
index 4a06e7474..a22b51005 100644
--- a/sdk/src/test/java/io/dapr/client/domain/DeleteStateRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/DeleteStateRequestTest.java
@@ -1,13 +1,13 @@
package io.dapr.client.domain;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class DeleteStateRequestTest {
@@ -26,6 +26,6 @@ public class DeleteStateRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- Assert.assertNotSame("Should not be same map", request.getMetadata(), initial);
+ Assertions.assertNotSame(request.getMetadata(), initial, "Should not be same map");
}
}
diff --git a/sdk/src/test/java/io/dapr/client/domain/ExecuteStateTransactionRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/ExecuteStateTransactionRequestTest.java
index 944d558ac..f7fe8ad0c 100644
--- a/sdk/src/test/java/io/dapr/client/domain/ExecuteStateTransactionRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/ExecuteStateTransactionRequestTest.java
@@ -1,14 +1,14 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class ExecuteStateTransactionRequestTest {
@@ -26,7 +26,7 @@ public class ExecuteStateTransactionRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- assertNotSame("Should not be same map", request.getMetadata(), initial);
+ assertNotSame(request.getMetadata(), initial, "Should not be same map");
}
@Test
@@ -41,6 +41,6 @@ public class ExecuteStateTransactionRequestTest {
request.setOperations(operations);
List> initial = request.getOperations();
request.setOperations(operations);
- assertNotSame("Should not be same list", request.getOperations(), initial);
+ assertNotSame(request.getOperations(), initial, "Should not be same list");
}
}
diff --git a/sdk/src/test/java/io/dapr/client/domain/GetBulkSecretRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/GetBulkSecretRequestTest.java
index b88f5911c..e115fbba5 100644
--- a/sdk/src/test/java/io/dapr/client/domain/GetBulkSecretRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/GetBulkSecretRequestTest.java
@@ -1,12 +1,12 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class GetBulkSecretRequestTest {
@@ -24,6 +24,6 @@ public class GetBulkSecretRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- assertNotSame("Should not be same map", request.getMetadata(), initial);
+ assertNotSame(request.getMetadata(), initial, "Should not be same map");
}
}
\ No newline at end of file
diff --git a/sdk/src/test/java/io/dapr/client/domain/GetBulkStateRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/GetBulkStateRequestTest.java
index f5472dbcf..55e7d1ea3 100644
--- a/sdk/src/test/java/io/dapr/client/domain/GetBulkStateRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/GetBulkStateRequestTest.java
@@ -1,14 +1,17 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
public class GetBulkStateRequestTest {
@@ -32,7 +35,7 @@ public class GetBulkStateRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- assertNotSame("Should not be same map", request.getMetadata(), initial);
+ assertNotSame(request.getMetadata(), initial, "Should not be same map");
// Var args constructor
request = new GetBulkStateRequest(STORE_NAME, "test var key");
@@ -53,6 +56,6 @@ public class GetBulkStateRequestTest {
request.setMetadata(metadata);
initial = request.getMetadata();
request.setMetadata(metadata);
- assertNotSame("Should not be same map", request.getMetadata(), initial);
+ assertNotSame( request.getMetadata(), initial, "Should not be same map");
}
}
diff --git a/sdk/src/test/java/io/dapr/client/domain/GetSecretRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/GetSecretRequestTest.java
index 5473ee0db..e37640344 100644
--- a/sdk/src/test/java/io/dapr/client/domain/GetSecretRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/GetSecretRequestTest.java
@@ -1,15 +1,15 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
public class GetSecretRequestTest {
@@ -27,6 +27,6 @@ public class GetSecretRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- assertNotSame("Should not be same map", request.getMetadata(), initial);
+ assertNotSame(request.getMetadata(), initial, "Should not be same map");
}
}
\ No newline at end of file
diff --git a/sdk/src/test/java/io/dapr/client/domain/GetStateRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/GetStateRequestTest.java
index 6e4b47843..54ac6d1db 100644
--- a/sdk/src/test/java/io/dapr/client/domain/GetStateRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/GetStateRequestTest.java
@@ -1,12 +1,12 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class GetStateRequestTest {
@@ -24,6 +24,6 @@ public class GetStateRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- assertNotSame("Should not be same map", request.getMetadata(), initial);
+ assertNotSame(request.getMetadata(), initial, "Should not be same map");
}
}
\ No newline at end of file
diff --git a/sdk/src/test/java/io/dapr/client/domain/InvokeBindingRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/InvokeBindingRequestTest.java
index bd9bfd90b..c241ec4ce 100644
--- a/sdk/src/test/java/io/dapr/client/domain/InvokeBindingRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/InvokeBindingRequestTest.java
@@ -1,12 +1,12 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class InvokeBindingRequestTest {
@@ -24,6 +24,6 @@ public class InvokeBindingRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- assertNotSame("Should not be same map", request.getMetadata(), initial);
+ assertNotSame(request.getMetadata(), initial, "Should not be same map");
}
}
\ No newline at end of file
diff --git a/sdk/src/test/java/io/dapr/client/domain/PublishEventRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/PublishEventRequestTest.java
index d73201011..392fef578 100644
--- a/sdk/src/test/java/io/dapr/client/domain/PublishEventRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/PublishEventRequestTest.java
@@ -1,13 +1,13 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class PublishEventRequestTest {
@@ -27,6 +27,6 @@ public class PublishEventRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- assertNotSame("Should not be same map", request.getMetadata(), initial);
+ assertNotSame(request.getMetadata(), initial, "Should not be same map");
}
}
\ No newline at end of file
diff --git a/sdk/src/test/java/io/dapr/client/domain/QueryStateRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/QueryStateRequestTest.java
index 0c88e1aa9..ef418d4d6 100644
--- a/sdk/src/test/java/io/dapr/client/domain/QueryStateRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/QueryStateRequestTest.java
@@ -2,13 +2,14 @@ package io.dapr.client.domain;
import io.dapr.client.domain.query.Query;
import io.dapr.client.domain.query.filters.EqFilter;
-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;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
public class QueryStateRequestTest {
@@ -27,20 +28,20 @@ public class QueryStateRequestTest {
request.setMetadata(metadata);
Map initial = request.getMetadata();
request.setMetadata(metadata);
- Assert.assertNotSame("Should not be same map", request.getMetadata(), initial);
+ Assertions.assertNotSame(request.getMetadata(), initial, "Should not be same map");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testSetNullQuery() {
QueryStateRequest request = new QueryStateRequest(STORE_NAME);
- request.setQuery(null);
+ assertThrows(IllegalArgumentException.class, () -> request.setQuery(null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testSetNullFilterQuery() {
QueryStateRequest request = new QueryStateRequest(STORE_NAME);
Query query = new Query();
- request.setQuery(query);
+ assertThrows(IllegalArgumentException.class, () -> request.setQuery(query));
}
@Test
@@ -49,6 +50,6 @@ public class QueryStateRequestTest {
Query query = new Query();
query.setFilter(new EqFilter<>("key", "value"));
request.setQuery(query);
- Assert.assertEquals(query, request.getQuery());
+ Assertions.assertEquals(query, request.getQuery());
}
}
diff --git a/sdk/src/test/java/io/dapr/client/domain/SaveStateRequestTest.java b/sdk/src/test/java/io/dapr/client/domain/SaveStateRequestTest.java
index d62fe1b57..09889bd54 100644
--- a/sdk/src/test/java/io/dapr/client/domain/SaveStateRequestTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/SaveStateRequestTest.java
@@ -1,13 +1,13 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
public class SaveStateRequestTest {
@@ -24,11 +24,11 @@ public class SaveStateRequestTest {
request.setStates(states);
List> initial = request.getStates();
request.setStates(states);
- assertNotSame("Should not be same list", request.getStates(), initial);
+ assertNotSame( request.getStates(), initial, "Should not be same list");
// With var args method
request.setStates(new State<>("test var args 1"), new State<>("test var args 2"));
- assertEquals("Value incorrectly set", "test var args 1", request.getStates().get(0).getKey());
- assertEquals("Value incorrectly set", "test var args 2", request.getStates().get(1).getKey());
+ assertEquals("test var args 1", request.getStates().get(0).getKey(), "Value incorrectly set");
+ assertEquals("test var args 2", request.getStates().get(1).getKey(), "Value incorrectly set");
}
}
\ No newline at end of file
diff --git a/sdk/src/test/java/io/dapr/client/domain/StateTest.java b/sdk/src/test/java/io/dapr/client/domain/StateTest.java
index 95b5528bc..30870d9cd 100644
--- a/sdk/src/test/java/io/dapr/client/domain/StateTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/StateTest.java
@@ -1,14 +1,14 @@
package io.dapr.client.domain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+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;
public class StateTest {
diff --git a/sdk/src/test/java/io/dapr/client/domain/query/QueryTest.java b/sdk/src/test/java/io/dapr/client/domain/query/QueryTest.java
index 220a7f209..957fea929 100644
--- a/sdk/src/test/java/io/dapr/client/domain/query/QueryTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/query/QueryTest.java
@@ -3,11 +3,13 @@ package io.dapr.client.domain.query;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dapr.client.domain.query.filters.*;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
public class QueryTest {
ObjectMapper mapper = new ObjectMapper();
@@ -35,7 +37,7 @@ public class QueryTest {
q.setPagination(new Pagination(10, "test-token"));
q.setSort(Arrays.asList(new Sorting("value.person.org", Sorting.Order.ASC),
new Sorting("value.state", Sorting.Order.DESC)));
- Assert.assertEquals(json, mapper.writeValueAsString(q));
+ Assertions.assertEquals(json, mapper.writeValueAsString(q));
}
@@ -44,61 +46,61 @@ public class QueryTest {
Query query = mapper.readValue(json, Query.class);
- Assert.assertNotNull(query.getPagination());
- Assert.assertNotNull(query.getFilter());
- Assert.assertNotNull(query.getSort());
+ Assertions.assertNotNull(query.getPagination());
+ Assertions.assertNotNull(query.getFilter());
+ Assertions.assertNotNull(query.getSort());
// Assert Pagination
- Assert.assertEquals(10, query.getPagination().getLimit());
- Assert.assertEquals("test-token", query.getPagination().getToken());
+ Assertions.assertEquals(10, query.getPagination().getLimit());
+ Assertions.assertEquals("test-token", query.getPagination().getToken());
// Assert Sort
- Assert.assertEquals(2, query.getSort().size());
- Assert.assertEquals("value.person.org", query.getSort().get(0).getKey());
- Assert.assertEquals(Sorting.Order.ASC, query.getSort().get(0).getOrder());
- Assert.assertEquals("value.state", query.getSort().get(1).getKey());
- Assert.assertEquals(Sorting.Order.DESC, query.getSort().get(1).getOrder());
+ Assertions.assertEquals(2, query.getSort().size());
+ Assertions.assertEquals("value.person.org", query.getSort().get(0).getKey());
+ Assertions.assertEquals(Sorting.Order.ASC, query.getSort().get(0).getOrder());
+ Assertions.assertEquals("value.state", query.getSort().get(1).getKey());
+ Assertions.assertEquals(Sorting.Order.DESC, query.getSort().get(1).getOrder());
// Assert Filter
// Top level AND filter
- Assert.assertEquals("AND", query.getFilter().getName());
+ Assertions.assertEquals("AND", query.getFilter().getName());
// Type cast to AND filter
AndFilter filter = (AndFilter) query.getFilter();
// Assert 3 AND clauses
- Assert.assertEquals(3, filter.getClauses().length);
+ Assertions.assertEquals(3, filter.getClauses().length);
Filter>[] andClauses = filter.getClauses();
// First EQ
- Assert.assertEquals("EQ", andClauses[0].getName());
- Assert.assertSame(EqFilter.class, andClauses[0].getClass());
+ Assertions.assertEquals("EQ", andClauses[0].getName());
+ Assertions.assertSame(EqFilter.class, andClauses[0].getClass());
EqFilter> eq = (EqFilter>) andClauses[0];
- Assert.assertEquals("key", eq.getKey());
- Assert.assertEquals("value", eq.getValue());
+ Assertions.assertEquals("key", eq.getKey());
+ Assertions.assertEquals("value", eq.getValue());
// Second IN
- Assert.assertEquals("IN", andClauses[1].getName());
- Assert.assertSame(InFilter.class, andClauses[1].getClass());
+ Assertions.assertEquals("IN", andClauses[1].getName());
+ Assertions.assertSame(InFilter.class, andClauses[1].getClass());
InFilter> in = (InFilter>) andClauses[1];
- Assert.assertEquals("key2", in.getKey());
- Assert.assertArrayEquals(new String[]{ "v1", "v2" }, in.getValues().toArray());
+ Assertions.assertEquals("key2", in.getKey());
+ Assertions.assertArrayEquals(new String[]{ "v1", "v2" }, in.getValues().toArray());
// Third OR
- Assert.assertEquals("OR", andClauses[2].getName());
- Assert.assertSame(OrFilter.class, andClauses[2].getClass());
+ Assertions.assertEquals("OR", andClauses[2].getName());
+ Assertions.assertSame(OrFilter.class, andClauses[2].getClass());
OrFilter orFilter = (OrFilter) andClauses[2];
Filter>[] orClauses = orFilter.getClauses();
// First EQ in OR
- Assert.assertEquals("EQ", orClauses[0].getName());
- Assert.assertSame(EqFilter.class, orClauses[0].getClass());
+ Assertions.assertEquals("EQ", orClauses[0].getName());
+ Assertions.assertSame(EqFilter.class, orClauses[0].getClass());
eq = (EqFilter>) orClauses[0];
- Assert.assertEquals("v2", eq.getKey());
- Assert.assertEquals(true, eq.getValue());
+ Assertions.assertEquals("v2", eq.getKey());
+ Assertions.assertEquals(true, eq.getValue());
// Second IN in OR
- Assert.assertEquals("IN", orClauses[1].getName());
- Assert.assertSame(InFilter.class, orClauses[1].getClass());
+ Assertions.assertEquals("IN", orClauses[1].getName());
+ Assertions.assertSame(InFilter.class, orClauses[1].getClass());
in = (InFilter>) orClauses[1];
- Assert.assertEquals("v3", in.getKey());
- Assert.assertArrayEquals(new Double[]{ 1.3, 1.5 }, in.getValues().toArray());
+ Assertions.assertEquals("v3", in.getKey());
+ Assertions.assertArrayEquals(new Double[]{ 1.3, 1.5 }, in.getValues().toArray());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testQueryInValidFilter() throws JsonProcessingException {
Query q = new Query();
@@ -113,6 +115,6 @@ public class QueryTest {
filter.addClause((Filter>) orFilter);
// Add Filter
- q.setFilter(filter);
+ assertThrows(IllegalArgumentException.class, () -> q.setFilter(filter));
}
}
\ No newline at end of file
diff --git a/sdk/src/test/java/io/dapr/client/domain/query/filters/AndFilterTest.java b/sdk/src/test/java/io/dapr/client/domain/query/filters/AndFilterTest.java
index 36133fd3d..18002091e 100644
--- a/sdk/src/test/java/io/dapr/client/domain/query/filters/AndFilterTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/query/filters/AndFilterTest.java
@@ -2,8 +2,8 @@ package io.dapr.client.domain.query.filters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class AndFilterTest {
@@ -18,7 +18,7 @@ public class AndFilterTest {
filter.addClause(new EqFilter<>("key", "value"));
filter.addClause(new InFilter<>("key2", "v1", "v2"));
- Assert.assertEquals(json, MAPPER.writeValueAsString((Filter) filter));
+ Assertions.assertEquals(json, MAPPER.writeValueAsString((Filter) filter));
}
@Test
@@ -26,34 +26,34 @@ public class AndFilterTest {
Filter> res = MAPPER.readValue(json, Filter.class);
// Check for AndFilter
- Assert.assertEquals("AND", res.getName());
- Assert.assertSame(AndFilter.class, res.getClass());
+ Assertions.assertEquals("AND", res.getName());
+ Assertions.assertSame(AndFilter.class, res.getClass());
AndFilter filter = (AndFilter) res;
// Check 2 clauses
- Assert.assertEquals(2, filter.getClauses().length);
+ Assertions.assertEquals(2, filter.getClauses().length);
// First EQ
- Assert.assertSame(EqFilter.class, filter.getClauses()[0].getClass());
+ Assertions.assertSame(EqFilter.class, filter.getClauses()[0].getClass());
EqFilter> eq = (EqFilter>) filter.getClauses()[0];
- Assert.assertEquals("key", eq.getKey());
- Assert.assertEquals("value", eq.getValue());
+ Assertions.assertEquals("key", eq.getKey());
+ Assertions.assertEquals("value", eq.getValue());
// Second IN
- Assert.assertSame(InFilter.class, filter.getClauses()[1].getClass());
+ Assertions.assertSame(InFilter.class, filter.getClauses()[1].getClass());
InFilter> in = (InFilter>) filter.getClauses()[1];
- Assert.assertEquals("key2", in.getKey());
- Assert.assertArrayEquals(new String[]{ "v1", "v2" }, in.getValues().toArray());
+ Assertions.assertEquals("key2", in.getKey());
+ Assertions.assertArrayEquals(new String[]{ "v1", "v2" }, in.getValues().toArray());
}
@Test
public void testValidation() {
AndFilter filter = new AndFilter();
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter.addClause(new EqFilter<>("key1", "v2"));
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter.addClause(new EqFilter<>("key2", "v3"));
- Assert.assertTrue(filter.isValid());
+ Assertions.assertTrue(filter.isValid());
}
}
diff --git a/sdk/src/test/java/io/dapr/client/domain/query/filters/EqFilterTest.java b/sdk/src/test/java/io/dapr/client/domain/query/filters/EqFilterTest.java
index ac7611bc3..12c72faa2 100644
--- a/sdk/src/test/java/io/dapr/client/domain/query/filters/EqFilterTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/query/filters/EqFilterTest.java
@@ -2,8 +2,8 @@ package io.dapr.client.domain.query.filters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class EqFilterTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@@ -14,32 +14,32 @@ public class EqFilterTest {
public void testSerialization() throws JsonProcessingException {
EqFilter> filter = new EqFilter<>("key", 1.5);
- Assert.assertEquals(json, MAPPER.writeValueAsString(filter));
+ Assertions.assertEquals(json, MAPPER.writeValueAsString(filter));
}
@Test
public void testDeserialization() throws JsonProcessingException {
EqFilter> filter = MAPPER.readValue(json, EqFilter.class);
- Assert.assertEquals("key", filter.getKey());
- Assert.assertEquals(1.5, filter.getValue());
+ Assertions.assertEquals("key", filter.getKey());
+ Assertions.assertEquals(1.5, filter.getValue());
}
@Test
public void testValidation() {
EqFilter> filter = new EqFilter<>(null, "val");
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter = new EqFilter<>("", "");
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter = new EqFilter<>("", true);
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter = new EqFilter<>(" ", "valid");
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter = new EqFilter<>("valid", "");
- Assert.assertTrue(filter.isValid());
+ Assertions.assertTrue(filter.isValid());
}
}
diff --git a/sdk/src/test/java/io/dapr/client/domain/query/filters/InFilterTest.java b/sdk/src/test/java/io/dapr/client/domain/query/filters/InFilterTest.java
index 47aa6bcbc..07a884cfa 100644
--- a/sdk/src/test/java/io/dapr/client/domain/query/filters/InFilterTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/query/filters/InFilterTest.java
@@ -2,8 +2,8 @@ package io.dapr.client.domain.query.filters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class InFilterTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@@ -14,35 +14,35 @@ public class InFilterTest {
public void testSerialization() throws JsonProcessingException {
InFilter> filter = new InFilter<>("key", 1.5, 44.0);
- Assert.assertEquals(json, MAPPER.writeValueAsString(filter));
+ Assertions.assertEquals(json, MAPPER.writeValueAsString(filter));
}
@Test
public void testDeserialization() throws JsonProcessingException {
InFilter> filter = MAPPER.readValue(json, InFilter.class);
- Assert.assertEquals("key", filter.getKey());
- Assert.assertArrayEquals(new Double[]{ 1.5, 44.0 }, filter.getValues().toArray());
+ Assertions.assertEquals("key", filter.getKey());
+ Assertions.assertArrayEquals(new Double[]{ 1.5, 44.0 }, filter.getValues().toArray());
}
@Test
public void testValidation() {
InFilter> filter = new InFilter<>(null, "val");
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter = new InFilter<>("", "");
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter = new InFilter<>("", true);
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter = new InFilter<>(" ", "valid");
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter = new InFilter<>("valid", "");
- Assert.assertTrue(filter.isValid());
+ Assertions.assertTrue(filter.isValid());
filter = new InFilter<>("valid", "1.5", "2.5");
- Assert.assertTrue(filter.isValid());
+ Assertions.assertTrue(filter.isValid());
}
}
diff --git a/sdk/src/test/java/io/dapr/client/domain/query/filters/OrFilterTest.java b/sdk/src/test/java/io/dapr/client/domain/query/filters/OrFilterTest.java
index 202d33336..1541292ee 100644
--- a/sdk/src/test/java/io/dapr/client/domain/query/filters/OrFilterTest.java
+++ b/sdk/src/test/java/io/dapr/client/domain/query/filters/OrFilterTest.java
@@ -2,8 +2,8 @@ package io.dapr.client.domain.query.filters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class OrFilterTest {
private final static ObjectMapper MAPPER = new ObjectMapper();
@@ -17,7 +17,7 @@ public class OrFilterTest {
filter.addClause(new EqFilter<>("key", "value"));
filter.addClause(new InFilter<>("key2", "v1", "v2"));
- Assert.assertEquals(json, MAPPER.writeValueAsString((Filter) filter));
+ Assertions.assertEquals(json, MAPPER.writeValueAsString((Filter) filter));
}
@Test
@@ -25,33 +25,33 @@ public class OrFilterTest {
Filter> res = MAPPER.readValue(json, Filter.class);
// Check for AndFilter
- Assert.assertEquals("OR", res.getName());
- Assert.assertSame(OrFilter.class, res.getClass());
+ Assertions.assertEquals("OR", res.getName());
+ Assertions.assertSame(OrFilter.class, res.getClass());
OrFilter filter = (OrFilter) res;
// Check 2 clauses
- Assert.assertEquals(2, filter.getClauses().length);
+ Assertions.assertEquals(2, filter.getClauses().length);
// First EQ
- Assert.assertSame(EqFilter.class, filter.getClauses()[0].getClass());
+ Assertions.assertSame(EqFilter.class, filter.getClauses()[0].getClass());
EqFilter> eq = (EqFilter>) filter.getClauses()[0];
- Assert.assertEquals("key", eq.getKey());
- Assert.assertEquals("value", eq.getValue());
+ Assertions.assertEquals("key", eq.getKey());
+ Assertions.assertEquals("value", eq.getValue());
// Second IN
- Assert.assertSame(InFilter.class, filter.getClauses()[1].getClass());
+ Assertions.assertSame(InFilter.class, filter.getClauses()[1].getClass());
InFilter> in = (InFilter>) filter.getClauses()[1];
- Assert.assertEquals("key2", in.getKey());
- Assert.assertArrayEquals(new String[]{ "v1", "v2" }, in.getValues().toArray());
+ Assertions.assertEquals("key2", in.getKey());
+ Assertions.assertArrayEquals(new String[]{ "v1", "v2" }, in.getValues().toArray());
}
@Test
public void testValidation() {
OrFilter filter = new OrFilter();
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter.addClause(new EqFilter<>("key1", "v2"));
- Assert.assertFalse(filter.isValid());
+ Assertions.assertFalse(filter.isValid());
filter.addClause(new EqFilter<>("key2", "v3"));
- Assert.assertTrue(filter.isValid());
+ Assertions.assertTrue(filter.isValid());
}
}
diff --git a/sdk/src/test/java/io/dapr/resiliency/RetryPolicyTest.java b/sdk/src/test/java/io/dapr/resiliency/RetryPolicyTest.java
index d495832c2..076ca2e01 100644
--- a/sdk/src/test/java/io/dapr/resiliency/RetryPolicyTest.java
+++ b/sdk/src/test/java/io/dapr/resiliency/RetryPolicyTest.java
@@ -16,13 +16,17 @@ package io.dapr.resiliency;
import io.dapr.internal.resiliency.RetryPolicy;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import reactor.core.Exceptions;
import reactor.core.publisher.Mono;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.*;
+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.junit.jupiter.api.Assertions.fail;
public class RetryPolicyTest {
diff --git a/sdk/src/test/java/io/dapr/runtime/DaprRuntimeTest.java b/sdk/src/test/java/io/dapr/runtime/DaprRuntimeTest.java
index 538067a64..8ae30b412 100644
--- a/sdk/src/test/java/io/dapr/runtime/DaprRuntimeTest.java
+++ b/sdk/src/test/java/io/dapr/runtime/DaprRuntimeTest.java
@@ -1,354 +1,356 @@
-/*
- * Copyright 2021 The Dapr Authors
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package io.dapr.runtime;
-
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.core.JsonGenerator;
-import io.dapr.client.DaprClient;
-import io.dapr.client.DaprClientTestBuilder;
-import io.dapr.client.DaprHttp;
-import io.dapr.client.DaprHttpStub;
-import io.dapr.client.domain.CloudEvent;
-import io.dapr.client.domain.HttpExtension;
-import io.dapr.serializer.DaprObjectSerializer;
-import io.dapr.serializer.DefaultObjectSerializer;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import reactor.core.publisher.Mono;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.util.Collections;
-import java.util.Map;
-import java.util.UUID;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class DaprRuntimeTest {
-
- protected static final JsonFactory JSON_FACTORY = new JsonFactory();
-
- private static final String TYPE_PLAIN_TEXT = "plain/text";
-
- private static final String PUBSUB_NAME = "mypubsubname";
-
- private static final String TOPIC_NAME = "mytopic";
-
- private static final String APP_ID = "myappid";
-
- private static final String METHOD_NAME = "mymethod";
-
- private static final String INVOKE_PATH = DaprHttp.API_VERSION + "/invoke";
-
- private static final String PUBLISH_PATH = DaprHttp.API_VERSION + "/publish";
-
- private final DaprRuntime daprRuntime = Dapr.getInstance();
-
- @Before
- public void setup() throws Exception {
- // Only for unit tests to simulate a new start of the app.
- Field field = this.daprRuntime.getClass().getDeclaredField("instance");
- field.setAccessible(true);
- field.set(null, null);
- }
-
- @Test
- public void pubSubHappyCase() throws Exception {
- Assert.assertNotNull(this.daprRuntime.getSubscribedTopics());
- Assert.assertTrue(this.daprRuntime.getSubscribedTopics().isEmpty());
-
- TopicListener listener = mock(TopicListener.class);
- when(listener.process(any(), any())).thenReturn(Mono.empty());
-
- this.daprRuntime.subscribeToTopic(TOPIC_NAME, listener);
-
- verify(listener, never()).process(any(), any());
-
- Message[] messages = new Message[]{
- new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- generatePayload(),
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- "",
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- null,
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- generatePayload(),
- null),
- new Message(
- "",
- TYPE_PLAIN_TEXT,
- generatePayload(),
- generateSingleMetadata()),
- new Message(
- null,
- TYPE_PLAIN_TEXT,
- generatePayload(),
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- "",
- generatePayload(),
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- null,
- generatePayload(),
- generateSingleMetadata())
- };
-
- DaprHttpStub daprHttp = mock(DaprHttpStub.class);
- DaprClient client = DaprClientTestBuilder.buildHttpClient(daprHttp);
- DaprObjectSerializer serializer = new DefaultObjectSerializer();
-
- for (Message message : messages) {
- when(daprHttp.invokeApi(
- eq("POST"),
- eq((PUBLISH_PATH + "/" + PUBSUB_NAME + "/" + TOPIC_NAME).split("/")),
- any(),
- eq(serializer.serialize(message.data)),
- any(),
- any()))
- .thenAnswer(invocationOnMock -> this.daprRuntime.handleInvocation(
- TOPIC_NAME,
- this.serialize(message),
- message.metadata).then());
-
- client.publishEvent(PUBSUB_NAME, TOPIC_NAME, message.data).block();
-
- CloudEvent envelope = new CloudEvent(
- message.id,
- null,
- null,
- null,
- message.datacontenttype,
- message.data
- );
- verify(listener, times(1)).process(eq(envelope), eq(message.metadata));
- }
-
- verify(listener, times(messages.length)).process(any(), any());
- }
-
- @Test
- public void invokeHappyCase() throws Exception {
- MethodListener listener = mock(MethodListener.class);
-
- this.daprRuntime.registerServiceMethod(METHOD_NAME, listener);
-
- verify(listener, never()).process(any(), any());
-
- Message[] messages = new Message[]{
- new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- generatePayload(),
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- "",
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- null,
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- generatePayload(),
- null),
- new Message(
- "",
- TYPE_PLAIN_TEXT,
- generatePayload(),
- generateSingleMetadata()),
- new Message(
- null,
- TYPE_PLAIN_TEXT,
- generatePayload(),
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- "",
- generatePayload(),
- generateSingleMetadata()),
- new Message(
- generateMessageId(),
- null,
- generatePayload(),
- generateSingleMetadata())
- };
-
- DaprHttpStub daprHttp = mock(DaprHttpStub.class);
- DaprClient client = DaprClientTestBuilder.buildHttpClient(daprHttp);
-
- DaprObjectSerializer serializer = new DefaultObjectSerializer();
- for (Message message : messages) {
- byte[] expectedResponse = serializer.serialize(message.id);
- when(listener.process(eq(serializer.serialize(message.data)), eq(message.metadata)))
- .then(x -> expectedResponse == null ? Mono.empty() : Mono.just(expectedResponse));
-
- when(daprHttp.invokeApi(
- eq("POST"),
- eq((INVOKE_PATH + "/" + APP_ID + "/method/" + METHOD_NAME).split("/")),
- any(),
- eq(serializer.serialize(message.data)),
- any(),
- any()))
- .thenAnswer(x ->
- this.daprRuntime.handleInvocation(
- METHOD_NAME,
- serializer.serialize(message.data),
- message.metadata)
- .map(r -> new DaprHttpStub.ResponseStub(r, null, 200)));
- Mono response = client.invokeMethod(APP_ID, METHOD_NAME, message.data, HttpExtension.POST,
- message.metadata, byte[].class);
- Assert.assertArrayEquals(expectedResponse, response.block());
-
- verify(listener, times(1))
- .process(eq(serializer.serialize(message.data)), eq(message.metadata));
- }
-
- verify(listener, times(messages.length)).process(any(), any());
- }
-
- @Test(expected = RuntimeException.class)
- public void subscribeCallbackException() throws Exception {
- Assert.assertNotNull(this.daprRuntime.getSubscribedTopics());
- Assert.assertTrue(this.daprRuntime.getSubscribedTopics().isEmpty());
-
- TopicListener listener = mock(TopicListener.class);
- when(listener.process(any(), any()))
- .thenReturn(Mono.error(new RuntimeException()));
-
- this.daprRuntime.subscribeToTopic(TOPIC_NAME, listener);
-
- Message message = new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- generatePayload(),
- generateSingleMetadata());
-
- Mono result = this.daprRuntime
- .handleInvocation(TOPIC_NAME, this.serialize(message), message.metadata);
-
- CloudEvent envelope = new CloudEvent(
- message.id,
- null,
- null,
- null,
- message.datacontenttype,
- message.data
- );
- verify(listener, times(1)).process(eq(envelope), eq(message.metadata));
- result.block();
- }
-
- @Test(expected = RuntimeException.class)
- public void subscribeUnknownTopic() throws Exception {
- Assert.assertNotNull(this.daprRuntime.getSubscribedTopics());
- Assert.assertTrue(this.daprRuntime.getSubscribedTopics().isEmpty());
-
- TopicListener listener = mock(TopicListener.class);
-
- this.daprRuntime.subscribeToTopic(TOPIC_NAME, listener);
-
- Message message = new Message(
- generateMessageId(),
- TYPE_PLAIN_TEXT,
- generatePayload(),
- generateSingleMetadata());
-
- Mono result = this.daprRuntime
- .handleInvocation("UNKNOWN", serialize(message), message.metadata);
-
- verify(listener, never()).process(any(), any());
-
- result.block();
- }
-
- private static String generateMessageId() {
- return UUID.randomUUID().toString();
- }
-
- private static String generatePayload() {
- return UUID.randomUUID().toString();
- }
-
- private static Map generateSingleMetadata() {
- return Collections.singletonMap(UUID.randomUUID().toString(), UUID.randomUUID().toString());
- }
-
- private static final class Message {
-
- private final String id;
-
- private final String datacontenttype;
-
- private final String data;
-
- private final Map metadata;
-
- private Message(String id, String datacontenttype, String data, Map metadata) {
- this.id = id;
- this.datacontenttype = datacontenttype;
- this.data = data;
- this.metadata = metadata;
- }
- }
-
- private byte[] serialize(Message message) throws IOException {
- if (message == null) {
- return null;
- }
-
- try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
- JsonGenerator generator = JSON_FACTORY.createGenerator(bos);
- generator.writeStartObject();
- if (message.id != null) {
- generator.writeStringField("id", message.id);
- }
- if (message.datacontenttype != null) {
- generator.writeStringField("datacontenttype", message.datacontenttype);
- }
- if (message.data != null) {
- generator.writeStringField("data", message.data);
- }
- generator.writeEndObject();
- generator.close();
- bos.flush();
- return bos.toByteArray();
- }
- }
-}
+/*
+ * Copyright 2021 The Dapr Authors
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package io.dapr.runtime;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
+import io.dapr.client.DaprClient;
+import io.dapr.client.DaprClientTestBuilder;
+import io.dapr.client.DaprHttp;
+import io.dapr.client.DaprHttpStub;
+import io.dapr.client.domain.CloudEvent;
+import io.dapr.client.domain.HttpExtension;
+import io.dapr.serializer.DaprObjectSerializer;
+import io.dapr.serializer.DefaultObjectSerializer;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Mono;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.Collections;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class DaprRuntimeTest {
+
+ protected static final JsonFactory JSON_FACTORY = new JsonFactory();
+
+ private static final String TYPE_PLAIN_TEXT = "plain/text";
+
+ private static final String PUBSUB_NAME = "mypubsubname";
+
+ private static final String TOPIC_NAME = "mytopic";
+
+ private static final String APP_ID = "myappid";
+
+ private static final String METHOD_NAME = "mymethod";
+
+ private static final String INVOKE_PATH = DaprHttp.API_VERSION + "/invoke";
+
+ private static final String PUBLISH_PATH = DaprHttp.API_VERSION + "/publish";
+
+ private final DaprRuntime daprRuntime = Dapr.getInstance();
+
+ @BeforeEach
+ public void setup() throws Exception {
+ // Only for unit tests to simulate a new start of the app.
+ Field field = this.daprRuntime.getClass().getDeclaredField("instance");
+ field.setAccessible(true);
+ field.set(null, null);
+ }
+
+ @Test
+ public void pubSubHappyCase() throws Exception {
+ Assertions.assertNotNull(this.daprRuntime.getSubscribedTopics());
+ Assertions.assertTrue(this.daprRuntime.getSubscribedTopics().isEmpty());
+
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.process(any(), any())).thenReturn(Mono.empty());
+
+ this.daprRuntime.subscribeToTopic(TOPIC_NAME, listener);
+
+ verify(listener, never()).process(any(), any());
+
+ Message[] messages = new Message[]{
+ new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ "",
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ null,
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ null),
+ new Message(
+ "",
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ generateSingleMetadata()),
+ new Message(
+ null,
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ "",
+ generatePayload(),
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ null,
+ generatePayload(),
+ generateSingleMetadata())
+ };
+
+ DaprHttpStub daprHttp = mock(DaprHttpStub.class);
+ DaprClient client = DaprClientTestBuilder.buildHttpClient(daprHttp);
+ DaprObjectSerializer serializer = new DefaultObjectSerializer();
+
+ for (Message message : messages) {
+ when(daprHttp.invokeApi(
+ eq("POST"),
+ eq((PUBLISH_PATH + "/" + PUBSUB_NAME + "/" + TOPIC_NAME).split("/")),
+ any(),
+ eq(serializer.serialize(message.data)),
+ any(),
+ any()))
+ .thenAnswer(invocationOnMock -> this.daprRuntime.handleInvocation(
+ TOPIC_NAME,
+ this.serialize(message),
+ message.metadata).then());
+
+ client.publishEvent(PUBSUB_NAME, TOPIC_NAME, message.data).block();
+
+ CloudEvent envelope = new CloudEvent(
+ message.id,
+ null,
+ null,
+ null,
+ message.datacontenttype,
+ message.data
+ );
+ verify(listener, times(1)).process(eq(envelope), eq(message.metadata));
+ }
+
+ verify(listener, times(messages.length)).process(any(), any());
+ }
+
+ @Test
+ public void invokeHappyCase() throws Exception {
+ MethodListener listener = mock(MethodListener.class);
+
+ this.daprRuntime.registerServiceMethod(METHOD_NAME, listener);
+
+ verify(listener, never()).process(any(), any());
+
+ Message[] messages = new Message[]{
+ new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ "",
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ null,
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ null),
+ new Message(
+ "",
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ generateSingleMetadata()),
+ new Message(
+ null,
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ "",
+ generatePayload(),
+ generateSingleMetadata()),
+ new Message(
+ generateMessageId(),
+ null,
+ generatePayload(),
+ generateSingleMetadata())
+ };
+
+ DaprHttpStub daprHttp = mock(DaprHttpStub.class);
+ DaprClient client = DaprClientTestBuilder.buildHttpClient(daprHttp);
+
+ DaprObjectSerializer serializer = new DefaultObjectSerializer();
+ for (Message message : messages) {
+ byte[] expectedResponse = serializer.serialize(message.id);
+ when(listener.process(eq(serializer.serialize(message.data)), eq(message.metadata)))
+ .then(x -> expectedResponse == null ? Mono.empty() : Mono.just(expectedResponse));
+
+ when(daprHttp.invokeApi(
+ eq("POST"),
+ eq((INVOKE_PATH + "/" + APP_ID + "/method/" + METHOD_NAME).split("/")),
+ any(),
+ eq(serializer.serialize(message.data)),
+ any(),
+ any()))
+ .thenAnswer(x ->
+ this.daprRuntime.handleInvocation(
+ METHOD_NAME,
+ serializer.serialize(message.data),
+ message.metadata)
+ .map(r -> new DaprHttpStub.ResponseStub(r, null, 200)));
+ Mono response = client.invokeMethod(APP_ID, METHOD_NAME, message.data, HttpExtension.POST,
+ message.metadata, byte[].class);
+ Assertions.assertArrayEquals(expectedResponse, response.block());
+
+ verify(listener, times(1))
+ .process(eq(serializer.serialize(message.data)), eq(message.metadata));
+ }
+
+ verify(listener, times(messages.length)).process(any(), any());
+ }
+
+ @Test
+ public void subscribeCallbackException() throws Exception {
+ Assertions.assertNotNull(this.daprRuntime.getSubscribedTopics());
+ Assertions.assertTrue(this.daprRuntime.getSubscribedTopics().isEmpty());
+
+ TopicListener listener = mock(TopicListener.class);
+ when(listener.process(any(), any()))
+ .thenReturn(Mono.error(new RuntimeException()));
+
+ this.daprRuntime.subscribeToTopic(TOPIC_NAME, listener);
+
+ Message message = new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ generateSingleMetadata());
+
+ Mono result = this.daprRuntime
+ .handleInvocation(TOPIC_NAME, this.serialize(message), message.metadata);
+
+ CloudEvent envelope = new CloudEvent(
+ message.id,
+ null,
+ null,
+ null,
+ message.datacontenttype,
+ message.data
+ );
+ verify(listener, times(1)).process(eq(envelope), eq(message.metadata));
+
+ assertThrows(RuntimeException.class, () -> result.block());
+ }
+
+ @Test
+ public void subscribeUnknownTopic() throws Exception {
+ Assertions.assertNotNull(this.daprRuntime.getSubscribedTopics());
+ Assertions.assertTrue(this.daprRuntime.getSubscribedTopics().isEmpty());
+
+ TopicListener listener = mock(TopicListener.class);
+
+ this.daprRuntime.subscribeToTopic(TOPIC_NAME, listener);
+
+ Message message = new Message(
+ generateMessageId(),
+ TYPE_PLAIN_TEXT,
+ generatePayload(),
+ generateSingleMetadata());
+
+ Mono result = this.daprRuntime
+ .handleInvocation("UNKNOWN", serialize(message), message.metadata);
+
+ verify(listener, never()).process(any(), any());
+
+ assertThrows(IllegalArgumentException.class, () -> result.block());
+ }
+
+ private static String generateMessageId() {
+ return UUID.randomUUID().toString();
+ }
+
+ private static String generatePayload() {
+ return UUID.randomUUID().toString();
+ }
+
+ private static Map generateSingleMetadata() {
+ return Collections.singletonMap(UUID.randomUUID().toString(), UUID.randomUUID().toString());
+ }
+
+ private static final class Message {
+
+ private final String id;
+
+ private final String datacontenttype;
+
+ private final String data;
+
+ private final Map metadata;
+
+ private Message(String id, String datacontenttype, String data, Map metadata) {
+ this.id = id;
+ this.datacontenttype = datacontenttype;
+ this.data = data;
+ this.metadata = metadata;
+ }
+ }
+
+ private byte[] serialize(Message message) throws IOException {
+ if (message == null) {
+ return null;
+ }
+
+ try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
+ JsonGenerator generator = JSON_FACTORY.createGenerator(bos);
+ generator.writeStartObject();
+ if (message.id != null) {
+ generator.writeStringField("id", message.id);
+ }
+ if (message.datacontenttype != null) {
+ generator.writeStringField("datacontenttype", message.datacontenttype);
+ }
+ if (message.data != null) {
+ generator.writeStringField("data", message.data);
+ }
+ generator.writeEndObject();
+ generator.close();
+ bos.flush();
+ return bos.toByteArray();
+ }
+ }
+}
diff --git a/sdk/src/test/java/io/dapr/serializer/DefaultObjectSerializerTest.java b/sdk/src/test/java/io/dapr/serializer/DefaultObjectSerializerTest.java
index 33e73f34e..d540fb8ae 100644
--- a/sdk/src/test/java/io/dapr/serializer/DefaultObjectSerializerTest.java
+++ b/sdk/src/test/java/io/dapr/serializer/DefaultObjectSerializerTest.java
@@ -22,7 +22,7 @@ import com.google.protobuf.Parser;
import io.dapr.client.domain.CloudEvent;
import io.dapr.utils.TypeRef;
import io.dapr.v1.CommonProtos;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.OutputStream;
@@ -34,13 +34,13 @@ import java.util.List;
import java.util.TreeMap;
import java.util.function.Function;
-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.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+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;
public class DefaultObjectSerializerTest {
@@ -222,7 +222,7 @@ public class DefaultObjectSerializerTest {
String serializedValue;
try {
serializedValue = new String(SERIALIZER.serialize(obj));
- assertEquals("FOUND:[[" + serializedValue + "]] \n but was EXPECTING: [[" + expectedResult + "]]", expectedResult, serializedValue);
+ assertEquals(expectedResult, serializedValue, "FOUND:[[" + serializedValue + "]] \n but was EXPECTING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -452,7 +452,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), TypeRef.get(MyObjectTestToSerialize.class));
- assertEquals("The expected value is different than the actual result", expectedResult, result);
+ assertEquals(expectedResult, result, "The expected value is different than the actual result");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -475,7 +475,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), new TypeRef>(){});
- assertEquals("The expected value is different than the actual result", expectedResult, result.get(0));
+ assertEquals(expectedResult, result.get(0), "The expected value is different than the actual result");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -485,7 +485,7 @@ public class DefaultObjectSerializerTest {
Type t = tr1.getType();
TypeRef> tr = TypeRef.get(t);
result = (List) SERIALIZER.deserialize(jsonToDeserialize.getBytes(), tr);
- assertEquals("The expected value is different than the actual result", expectedResult, result.get(0));
+ assertEquals(expectedResult, result.get(0), "The expected value is different than the actual result");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -550,7 +550,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -572,7 +572,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -594,7 +594,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -616,7 +616,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -638,7 +638,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -660,7 +660,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -682,7 +682,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -704,7 +704,7 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
@@ -726,44 +726,37 @@ public class DefaultObjectSerializerTest {
try {
result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- assertEquals("FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]", expectedResult, result);
+ assertEquals(expectedResult, result, "FOUND:[[" + result + "]] \n but was EXPECING: [[" + expectedResult + "]]");
} catch (IOException exception) {
fail(exception.getMessage());
}
}
- @Test(expected = IOException.class)
+ @Test
public void deserializeObjectIntExceedMaximunValueTest() throws Exception {
String jsonToDeserialize = "{\"stringValue\":\"A String\",\"intValue\":2147483648,\"boolValue\":true,\"charValue\":\"a\",\"byteValue\":65,\"shortValue\":32767,\"longValue\":9223372036854775807,\"floatValue\":1.0,\"doubleValue\":1000.0}";
-
- SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
+ assertThrows(IOException.class, () -> SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class));
}
- @Test(expected = IOException.class)
+ @Test
public void deserializeObjectNotACharTest() throws Exception {
String jsonToDeserialize = "{\"stringValue\":\"A String\",\"intValue\":2147483647,\"boolValue\":true,\"charValue\":\"Not A Char\",\"byteValue\":65,\"shortValue\":32767,\"longValue\":9223372036854775807,\"floatValue\":1.0,\"doubleValue\":1000.0}";
-
- try {
- SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
- } catch (IOException ioEx) {
- throw ioEx;
- } catch (Exception ex) {
- fail("Wrong exception thrown: [" + ex.getClass() + "] Message:[" + ex.getMessage() + "]");
- }
+
+ assertThrows(IOException.class, () -> SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class));
}
- @Test(expected = IOException.class)
+ @Test
public void deserializeObjectShortExceededMaximunValueTest() throws Exception {
String jsonToDeserialize = "{\"stringValue\":\"A String\",\"intValue\":2147483647,\"boolValue\":true,\"charValue\":\"a\",\"byteValue\":65,\"shortValue\":32768,\"longValue\":9223372036854775807,\"floatValue\":1.0,\"doubleValue\":1000.0}";
-
- SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
+
+ assertThrows(IOException.class, () -> SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class));
}
- @Test(expected = IOException.class)
+ @Test
public void deserializeObjectLongExceededMaximumValueTest() throws Exception {
String jsonToDeserialize = "{\"stringValue\":\"A String\",\"intValue\":2147483647,\"boolValue\":true,\"charValue\":\"a\",\"byteValue\":65,\"shortValue\":32767,\"longValue\":9223372036854775808,\"floatValue\":1.0,\"doubleValue\":1000.0}";
-
- MyObjectTestToSerialize result = SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class);
+
+ assertThrows(IOException.class, () -> SERIALIZER.deserialize(jsonToDeserialize.getBytes(), MyObjectTestToSerialize.class));
}
@Test
diff --git a/sdk/src/test/java/io/dapr/utils/DefaultContentTypeConverterTest.java b/sdk/src/test/java/io/dapr/utils/DefaultContentTypeConverterTest.java
index faac1f096..720aee472 100644
--- a/sdk/src/test/java/io/dapr/utils/DefaultContentTypeConverterTest.java
+++ b/sdk/src/test/java/io/dapr/utils/DefaultContentTypeConverterTest.java
@@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dapr.client.domain.CloudEvent;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -26,6 +26,8 @@ import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
public class DefaultContentTypeConverterTest {
// same as default serializer config
@@ -37,18 +39,18 @@ public class DefaultContentTypeConverterTest {
public void testToBytesHttpStringEventCorrectContentType() throws IOException {
String event = "string event";
byte[] res = DefaultContentTypeConverter.convertEventToBytesForHttp(event, "text/plain");
- Assert.assertNotNull("expected correct byte array response", res);
+ Assertions.assertNotNull(res, "expected correct byte array response");
byte[] expected = event.getBytes(StandardCharsets.UTF_8);
- Assert.assertArrayEquals("expected response to be matched with expectation", expected, res);
+ Assertions.assertArrayEquals(expected, res, "expected response to be matched with expectation");
}
@Test
public void testToBytesHttpNumberEventCorrectContentType() throws IOException {
Number event = 123;
byte[] res = DefaultContentTypeConverter.convertEventToBytesForHttp(event, "text/plain");
- Assert.assertNotNull("expected correct byte array response", res);
+ Assertions.assertNotNull( res, "expected correct byte array response");
byte[] expected = "123".getBytes(StandardCharsets.UTF_8);
- Assert.assertArrayEquals("expected response to be matched with expectation", expected, res);
+ Assertions.assertArrayEquals( expected, res, "expected response to be matched with expectation");
}
@Test
@@ -56,15 +58,16 @@ public class DefaultContentTypeConverterTest {
String event = "string event";
byte[] data = event.getBytes(StandardCharsets.UTF_8);
byte[] res = DefaultContentTypeConverter.convertEventToBytesForHttp(data, "application/octet-stream");
- Assert.assertNotNull("expected correct byte array response", res);
+ Assertions.assertNotNull(res, "expected correct byte array response");
byte[] expected = Base64.getEncoder().encode(data);
- Assert.assertArrayEquals("expected response to be matched with expectation", expected, res);
+ Assertions.assertArrayEquals(expected, res, "expected response to be matched with expectation");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testToBytesHttpBinEventInCorrectContentType() throws IOException {
String event = "string event";
- DefaultContentTypeConverter.convertEventToBytesForHttp(event, "application/octet-stream");
+ assertThrows(IllegalArgumentException.class, () ->
+ DefaultContentTypeConverter.convertEventToBytesForHttp(event, "application/octet-stream"));
}
@Test
@@ -74,18 +77,19 @@ public class DefaultContentTypeConverterTest {
put("test2", "val2");
}};
byte[] res = DefaultContentTypeConverter.convertEventToBytesForHttp(event, "application/json");
- Assert.assertNotNull("expected correct byte array response", res);
+ Assertions.assertNotNull(res, "expected correct byte array response");
byte[] expected = MAPPER.writeValueAsBytes(event);
- Assert.assertArrayEquals("expected response to be matched with expectation", expected, res);
+ Assertions.assertArrayEquals(expected, res, "expected response to be matched with expectation");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testToBytesHttpJsonEventInCorrectContentType() throws IOException {
Map event = new HashMap() {{
put("test1", "val1");
put("test2", "val2");
}};
- DefaultContentTypeConverter.convertEventToBytesForHttp(event, "application/xml");
+
+ assertThrows(IllegalArgumentException.class, () -> DefaultContentTypeConverter.convertEventToBytesForHttp(event, "application/xml"));
}
@Test
@@ -99,12 +103,12 @@ public class DefaultContentTypeConverterTest {
event.setDatacontenttype("text/plain");
event.setSource("dapr test");
byte[] res = DefaultContentTypeConverter.convertEventToBytesForHttp(event, "application/cloudevents+json");
- Assert.assertNotNull("expected correct byte array response", res);
+ Assertions.assertNotNull(res, "expected correct byte array response");
byte[] expected = MAPPER.writeValueAsBytes(event);
- Assert.assertArrayEquals("expected response to be matched with expectation", expected, res);
+ Assertions.assertArrayEquals(expected, res, "expected response to be matched with expectation");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testToBytesHttpCloudEventInCorrectContentType() throws IOException {
// Make sure that the MAPPER is configured same as the DefaultObjectSerializer config
CloudEvent event = new CloudEvent<>();
@@ -114,30 +118,30 @@ public class DefaultContentTypeConverterTest {
event.setData("test data");
event.setDatacontenttype("text/plain");
event.setSource("dapr test");
- DefaultContentTypeConverter.convertEventToBytesForHttp(event, "image/png");
+ assertThrows(IllegalArgumentException.class, () -> DefaultContentTypeConverter.convertEventToBytesForHttp(event, "image/png"));
}
@Test
public void testToBytesGrpcBinEventCorrectContentType() throws IOException {
byte[] event = "test event".getBytes(StandardCharsets.UTF_8);
byte[] res = DefaultContentTypeConverter.convertEventToBytesForGrpc(event, "application/octet-stream");
- Assert.assertNotNull("expected correct byte array response", res);
- Assert.assertArrayEquals("expected response to be matched with expectation", event, res);
+ Assertions.assertNotNull(res, "expected correct byte array response");
+ Assertions.assertArrayEquals( event, res, "expected response to be matched with expectation");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testToBytesGrpcBinEventInCorrectContentType() throws IOException {
byte[] event = "test event".getBytes(StandardCharsets.UTF_8);
- DefaultContentTypeConverter.convertEventToBytesForGrpc(event, "application/xml");
+ assertThrows(IllegalArgumentException.class, () -> DefaultContentTypeConverter.convertEventToBytesForGrpc(event, "application/xml"));
}
@Test
public void testToBytesGrpcStringEventCorrectContentType() throws IOException {
String event = "string event";
byte[] res = DefaultContentTypeConverter.convertEventToBytesForGrpc(event, "text/plain");
- Assert.assertNotNull("expected correct byte array response", res);
+ Assertions.assertNotNull(res, "expected correct byte array response");
byte[] expected = event.getBytes(StandardCharsets.UTF_8);
- Assert.assertArrayEquals("expected response to be matched with expectation", expected, res);
+ Assertions.assertArrayEquals(expected, res, "expected response to be matched with expectation");
}
@Test
@@ -145,8 +149,8 @@ public class DefaultContentTypeConverterTest {
byte[] event = "string event".getBytes(StandardCharsets.UTF_8);
String res = DefaultContentTypeConverter.convertBytesToEventFromHttp(event,
"text/plain", TypeRef.STRING);
- Assert.assertNotNull("expected not null response", res);
- Assert.assertEquals("expected res to match expectation", "string event", res);
+ Assertions.assertNotNull( res, "expected not null response");
+ Assertions.assertEquals("string event", res, "expected res to match expectation");
}
@Test
@@ -155,8 +159,8 @@ public class DefaultContentTypeConverterTest {
byte[] event = Base64.getEncoder().encode(expected);
byte[] res = DefaultContentTypeConverter.convertBytesToEventFromHttp(event,
"application/octet-stream", TypeRef.BYTE_ARRAY);
- Assert.assertNotNull("expected not null response", res);
- Assert.assertArrayEquals("expected res to match expectation", expected, res);
+ Assertions.assertNotNull(res, "expected not null response");
+ Assertions.assertArrayEquals(expected, res, "expected res to match expectation");
}
@Test
@@ -164,15 +168,15 @@ public class DefaultContentTypeConverterTest {
byte[] expected = "string event".getBytes(StandardCharsets.UTF_8);
byte[] res = DefaultContentTypeConverter.convertBytesToEventFromGrpc(expected,
"application/octet-stream", TypeRef.BYTE_ARRAY);
- Assert.assertNotNull("expected not null response", res);
- Assert.assertArrayEquals("expected res to match expectation", expected, res);
+ Assertions.assertNotNull(res, "expected not null response");
+ Assertions.assertArrayEquals(expected, res, "expected res to match expectation");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testToBytesGrpcBinDataInCorrectContentType() throws IOException {
String event = "string event";
- DefaultContentTypeConverter.convertEventToBytesForGrpc(event,
- "application/octet-stream");
+ assertThrows(IllegalArgumentException.class, () -> DefaultContentTypeConverter.convertEventToBytesForGrpc(event,
+ "application/octet-stream"));
}
@Test
@@ -180,8 +184,8 @@ public class DefaultContentTypeConverterTest {
byte[] expected = "string event".getBytes(StandardCharsets.UTF_8);
String res = DefaultContentTypeConverter.convertBytesToEventFromGrpc(expected,
"text/plain", TypeRef.STRING);
- Assert.assertNotNull("expected not null response", res);
- Assert.assertEquals("expected res to match expectation", "string event", res);
+ Assertions.assertNotNull( res, "expected not null response");
+ Assertions.assertEquals("string event", res, "expected res to match expectation");
}
@@ -191,8 +195,8 @@ public class DefaultContentTypeConverterTest {
byte[] data = DefaultContentTypeConverter.convertEventToBytesForHttp(expected, "text/plain");
Integer res = DefaultContentTypeConverter.convertBytesToEventFromHttp(data,
"text/plain", TypeRef.INT);
- Assert.assertNotNull("expected not null response", res);
- Assert.assertEquals("expected res to match expectation", expected, res);
+ Assertions.assertNotNull(res, "expected not null response");
+ Assertions.assertEquals(expected, res, "expected res to match expectation");
}
@Test
@@ -208,31 +212,31 @@ public class DefaultContentTypeConverterTest {
CloudEvent res = DefaultContentTypeConverter.convertBytesToEventFromHttp(data,
"application/cloudevents+json", new TypeRef>() {
});
- Assert.assertNotNull("expected not null response", res);
- Assert.assertEquals("expected res to match expectation", event, res);
+ Assertions.assertNotNull(res,"expected not null response");
+ Assertions.assertEquals(event, res, "expected res to match expectation");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testToEventHttpBinDataInCorrectContentType() throws IOException {
byte[] data = "string event".getBytes(StandardCharsets.UTF_8);
byte[] event = Base64.getEncoder().encode(data);
- DefaultContentTypeConverter.convertBytesToEventFromHttp(event,
- "text/plain", TypeRef.BYTE_ARRAY);
+ assertThrows(IllegalArgumentException.class, () -> DefaultContentTypeConverter.convertBytesToEventFromHttp(event,
+ "text/plain", TypeRef.BYTE_ARRAY));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testToEventHttpBinDataNullCorrectContentType() throws IOException {
byte[] data = "string event".getBytes(StandardCharsets.UTF_8);
byte[] event = Base64.getEncoder().encode(data);
- DefaultContentTypeConverter.convertBytesToEventFromHttp(event,
- null, TypeRef.BYTE_ARRAY);
+ assertThrows(IllegalArgumentException.class, () -> DefaultContentTypeConverter.convertBytesToEventFromHttp(event,
+ null, TypeRef.BYTE_ARRAY));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testToEventHttpBinDataCharsetInCorrectContentType() throws IOException {
byte[] data = "string event".getBytes(StandardCharsets.UTF_8);
byte[] event = Base64.getEncoder().encode(data);
- DefaultContentTypeConverter.convertBytesToEventFromHttp(event,
- "text/plain;charset=utf-8", TypeRef.BYTE_ARRAY);
+ assertThrows(IllegalArgumentException.class, () -> DefaultContentTypeConverter.convertBytesToEventFromHttp(event,
+ "text/plain;charset=utf-8", TypeRef.BYTE_ARRAY));
}
}
diff --git a/sdk/src/test/java/io/dapr/utils/DurationUtilsTest.java b/sdk/src/test/java/io/dapr/utils/DurationUtilsTest.java
index 5c807d0f5..dd75781f7 100644
--- a/sdk/src/test/java/io/dapr/utils/DurationUtilsTest.java
+++ b/sdk/src/test/java/io/dapr/utils/DurationUtilsTest.java
@@ -13,11 +13,15 @@ limitations under the License.
package io.dapr.utils;
-import org.junit.Assert;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
public class DurationUtilsTest {
@Test
@@ -26,7 +30,7 @@ public class DurationUtilsTest {
Duration d1 = DurationUtils.convertDurationFromDaprFormat(s);
String t = DurationUtils.convertDurationToDaprFormat(d1);
- Assert.assertEquals(s, t);
+ assertEquals(s, t);
}
@Test
@@ -36,7 +40,7 @@ public class DurationUtilsTest {
Duration d1 = DurationUtils.convertDurationFromDaprFormat(partial);
String t = DurationUtils.convertDurationToDaprFormat(d1);
- Assert.assertEquals(s, t);
+ assertEquals(s, t);
}
@Test
@@ -46,7 +50,7 @@ public class DurationUtilsTest {
Duration d1 = DurationUtils.convertDurationFromDaprFormat(partial);
String t = DurationUtils.convertDurationToDaprFormat(d1);
- Assert.assertEquals(s, t);
+ assertEquals(s, t);
}
@Test
@@ -56,7 +60,7 @@ public class DurationUtilsTest {
Duration d1 = DurationUtils.convertDurationFromDaprFormat(partial);
String t = DurationUtils.convertDurationToDaprFormat(d1);
- Assert.assertEquals(s, t);
+ assertEquals(s, t);
}
@Test
@@ -66,7 +70,7 @@ public class DurationUtilsTest {
Duration d1 = DurationUtils.convertDurationFromDaprFormat(partial);
String t = DurationUtils.convertDurationToDaprFormat(d1);
- Assert.assertEquals(s, t);
+ assertEquals(s, t);
}
@Test
@@ -76,19 +80,19 @@ public class DurationUtilsTest {
Duration d1 = DurationUtils.convertDurationFromDaprFormat(partial);
String t = DurationUtils.convertDurationToDaprFormat(d1);
- Assert.assertEquals(s, t);
+ assertEquals(s, t);
}
@Test
public void testZeroDuration(){
String s = "0h0m0s0ms";
String t = DurationUtils.convertDurationToDaprFormat(Duration.ZERO);
- Assert.assertEquals(s, t);
+ assertEquals(s, t);
}
@Test
public void testNullString() {
- Assert.assertThrows(IllegalArgumentException.class, () ->{
+ assertThrows(IllegalArgumentException.class, () ->{
DurationUtils.convertDurationFromDaprFormat(null);
});
}
@@ -96,7 +100,7 @@ public class DurationUtilsTest {
@Test
public void testEmptyString() {
Duration d = DurationUtils.convertDurationFromDaprFormat("");
- Assert.assertEquals(Duration.ZERO, d);
+ assertEquals(Duration.ZERO, d);
}
@Test
@@ -106,79 +110,79 @@ public class DurationUtilsTest {
Duration d1 = DurationUtils.convertDurationFromDaprFormat(s);
String t = DurationUtils.convertDurationToDaprFormat(d1);
- Assert.assertEquals(s, t);
+ assertEquals(s, t);
}
@Test
public void negativeDuration() {
Duration d = Duration.ofSeconds(-99);
String t = DurationUtils.convertDurationToDaprFormat(d);
- Assert.assertEquals("", t);
+ assertEquals("", t);
}
@Test
public void testGetHoursPart() {
Duration d1 = Duration.ZERO.plusHours(26);
- Assert.assertEquals(2, DurationUtils.getHoursPart(d1));
+ assertEquals(2, DurationUtils.getHoursPart(d1));
Duration d2 = Duration.ZERO.plusHours(23);
- Assert.assertEquals(23, DurationUtils.getHoursPart(d2));
+ assertEquals(23, DurationUtils.getHoursPart(d2));
Duration d3 = Duration.ZERO.plusHours(24);
- Assert.assertEquals(0, DurationUtils.getHoursPart(d3));
+ assertEquals(0, DurationUtils.getHoursPart(d3));
}
@Test
public void testGetMinutesPart() {
Duration d1 = Duration.ZERO.plusMinutes(61);
- Assert.assertEquals(1, DurationUtils.getMinutesPart(d1));
+ assertEquals(1, DurationUtils.getMinutesPart(d1));
Duration d2 = Duration.ZERO.plusMinutes(60);
- Assert.assertEquals(0, DurationUtils.getMinutesPart(d2));
+ assertEquals(0, DurationUtils.getMinutesPart(d2));
Duration d3 = Duration.ZERO.plusMinutes(59);
- Assert.assertEquals(59, DurationUtils.getMinutesPart(d3));
+ assertEquals(59, DurationUtils.getMinutesPart(d3));
Duration d4 = Duration.ZERO.plusMinutes(3600);
- Assert.assertEquals(0, DurationUtils.getMinutesPart(d4));
+ assertEquals(0, DurationUtils.getMinutesPart(d4));
}
@Test
public void testGetSecondsPart() {
Duration d1 = Duration.ZERO.plusSeconds(61);
- Assert.assertEquals(1, DurationUtils.getSecondsPart(d1));
+ assertEquals(1, DurationUtils.getSecondsPart(d1));
Duration d2 = Duration.ZERO.plusSeconds(60);
- Assert.assertEquals(0, DurationUtils.getSecondsPart(d2));
+ assertEquals(0, DurationUtils.getSecondsPart(d2));
Duration d3 = Duration.ZERO.plusSeconds(59);
- Assert.assertEquals(59, DurationUtils.getSecondsPart(d3));
+ assertEquals(59, DurationUtils.getSecondsPart(d3));
Duration d4 = Duration.ZERO.plusSeconds(3600);
- Assert.assertEquals(0, DurationUtils.getSecondsPart(d4));
+ assertEquals(0, DurationUtils.getSecondsPart(d4));
}
@Test
public void testGetMillisecondsPart() {
Duration d1 = Duration.ZERO.plusMillis(61);
- Assert.assertEquals(61, DurationUtils.getMilliSecondsPart(d1));
+ assertEquals(61, DurationUtils.getMilliSecondsPart(d1));
Duration d2 = Duration.ZERO.plusMillis(60);
- Assert.assertEquals(60, DurationUtils.getMilliSecondsPart(d2));
+ assertEquals(60, DurationUtils.getMilliSecondsPart(d2));
Duration d3 = Duration.ZERO.plusMillis(59);
- Assert.assertEquals(59, DurationUtils.getMilliSecondsPart(d3));
+ assertEquals(59, DurationUtils.getMilliSecondsPart(d3));
Duration d4 = Duration.ZERO.plusMillis(999);
- Assert.assertEquals(999, DurationUtils.getMilliSecondsPart(d4));
+ assertEquals(999, DurationUtils.getMilliSecondsPart(d4));
Duration d5 = Duration.ZERO.plusMillis(1001);
- Assert.assertEquals(1, DurationUtils.getMilliSecondsPart(d5));
+ assertEquals(1, DurationUtils.getMilliSecondsPart(d5));
Duration d6 = Duration.ZERO.plusMillis(1000);
- Assert.assertEquals(0, DurationUtils.getMilliSecondsPart(d6));
+ assertEquals(0, DurationUtils.getMilliSecondsPart(d6));
Duration d7 = Duration.ZERO.plusMillis(10000);
- Assert.assertEquals(0, DurationUtils.getMilliSecondsPart(d7));
+ assertEquals(0, DurationUtils.getMilliSecondsPart(d7));
}
}
diff --git a/sdk/src/test/java/io/dapr/utils/NetworkUtilsTest.java b/sdk/src/test/java/io/dapr/utils/NetworkUtilsTest.java
index 0c1417cea..93945b947 100644
--- a/sdk/src/test/java/io/dapr/utils/NetworkUtilsTest.java
+++ b/sdk/src/test/java/io/dapr/utils/NetworkUtilsTest.java
@@ -2,14 +2,14 @@ package io.dapr.utils;
import io.dapr.config.Properties;
import io.grpc.ManagedChannel;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class NetworkUtilsTest {
private final int defaultGrpcPort = 4000;
private final String defaultSidecarIP = "127.0.0.1";
- @Before
+ @BeforeEach
public void setUp() {
System.setProperty(Properties.GRPC_PORT.getName(), Integer.toString(defaultGrpcPort));
System.setProperty(Properties.SIDECAR_IP.getName(), defaultSidecarIP);
@@ -21,7 +21,7 @@ public class NetworkUtilsTest {
ManagedChannel channel = NetworkUtils.buildGrpcManagedChannel();
String expectedAuthority = String.format("%s:%s", defaultSidecarIP, defaultGrpcPort);
- Assert.assertEquals(expectedAuthority, channel.authority());
+ Assertions.assertEquals(expectedAuthority, channel.authority());
}
@Test
@@ -30,7 +30,7 @@ public class NetworkUtilsTest {
ManagedChannel channel = NetworkUtils.buildGrpcManagedChannel();
String expectedAuthority = "example.com:80";
- Assert.assertEquals(expectedAuthority, channel.authority());
+ Assertions.assertEquals(expectedAuthority, channel.authority());
}
@Test
@@ -39,7 +39,7 @@ public class NetworkUtilsTest {
ManagedChannel channel = NetworkUtils.buildGrpcManagedChannel();
String expectedAuthority = "example.com:3000";
- Assert.assertEquals(expectedAuthority, channel.authority());
+ Assertions.assertEquals(expectedAuthority, channel.authority());
}
@Test
@@ -48,7 +48,7 @@ public class NetworkUtilsTest {
ManagedChannel channel = NetworkUtils.buildGrpcManagedChannel();
String expectedAuthority = "example.com:443";
- Assert.assertEquals(expectedAuthority, channel.authority());
+ Assertions.assertEquals(expectedAuthority, channel.authority());
}
@Test
@@ -57,6 +57,6 @@ public class NetworkUtilsTest {
ManagedChannel channel = NetworkUtils.buildGrpcManagedChannel();
String expectedAuthority = "example.com:3000";
- Assert.assertEquals(expectedAuthority, channel.authority());
+ Assertions.assertEquals(expectedAuthority, channel.authority());
}
}
diff --git a/sdk/src/test/java/io/dapr/utils/TypeRefTest.java b/sdk/src/test/java/io/dapr/utils/TypeRefTest.java
index acd142546..d77536c49 100644
--- a/sdk/src/test/java/io/dapr/utils/TypeRefTest.java
+++ b/sdk/src/test/java/io/dapr/utils/TypeRefTest.java
@@ -1,21 +1,21 @@
package io.dapr.utils;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class TypeRefTest {
@Test
public void testTypeRefIsPrimitive() {
- Assert.assertTrue("expected this to be true as boolean is primitive", TypeRef.isPrimitive(TypeRef.BOOLEAN));
- Assert.assertTrue("expected this to be true as short is primitive", TypeRef.isPrimitive(TypeRef.SHORT));
- Assert.assertTrue("expected this to be true as float is primitive", TypeRef.isPrimitive(TypeRef.FLOAT));
- Assert.assertTrue("expected this to be true as double is primitive", TypeRef.isPrimitive(TypeRef.DOUBLE));
- Assert.assertTrue("expected this to be true as integer is primitive", TypeRef.isPrimitive(TypeRef.INT));
+ Assertions.assertTrue(TypeRef.isPrimitive(TypeRef.BOOLEAN), "expected this to be true as boolean is primitive");
+ Assertions.assertTrue(TypeRef.isPrimitive(TypeRef.SHORT), "expected this to be true as short is primitive");
+ Assertions.assertTrue(TypeRef.isPrimitive(TypeRef.FLOAT), "expected this to be true as float is primitive");
+ Assertions.assertTrue(TypeRef.isPrimitive(TypeRef.DOUBLE), "expected this to be true as double is primitive");
+ Assertions.assertTrue(TypeRef.isPrimitive(TypeRef.INT), "expected this to be true as integer is primitive");
- Assert.assertFalse("expected this to be false as string is not primitive",
- TypeRef.isPrimitive(TypeRef.STRING));
- Assert.assertFalse("expected this to be false as string array is not primitive",
- TypeRef.isPrimitive(TypeRef.STRING_ARRAY));
+ Assertions.assertFalse(TypeRef.isPrimitive(TypeRef.STRING),
+ "expected this to be false as string is not primitive");
+ Assertions.assertFalse(TypeRef.isPrimitive(TypeRef.STRING_ARRAY),
+ "expected this to be false as string array is not primitive");
}
}