I have a test with Mockito from my RecyclerView clicks, but an error is thrown.
This is my code:
#Test
public void getUserClick() {
RecyclerView rcv = Mockito.mock(RecyclerView.class);
List<User> usersList = new ArrayList<>();
User commonUser = Mockito.mock(User.class);
commonUser.setId("1");
commonUser.setName("User");
commonUser.setEmail("admin#admin.com");
usersList.add(commonUser);
UserAdapterTest adapter = Mockito.mock(UserAdapterTest.class);
adapter.addData(usersList);
rcv.setAdapter(adapter);
// Test Click
rcv.getChildAt(0).performClick();
//Verify Click Item
Mockito.verify(adapter).testClickItem(commonUser);
}
And the error launch here:
java.lang.NullPointerException in rcv.getChildAt(0).performClick();
But the IDE doesn't tell me anything else.
java.lang.NullPointerException
at com.project.test.TestRecycler.getUserClick(TestRecycler.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.mockito.internal.junit.JUnitRule$1.evaluateSafely(JUnitRule.java:63)
at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:43)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
And my adapter already has the click event implemented.
When you do:
RecyclerView rcv = Mockito.mock(RecyclerView.class);
rcv becomes a mock (an object that returns null (or 0, or false) by default, on any method call). So rcv.getChildAt(0) by default is returning null, and when you try to call performClick() on it, the NullPointerException occurs.
When you create a mock and want some method to return a specific value, you must tell it using Mockito.when(). So in your case, you should do something like this:
// configure "when" behaviour **before** calling the getChildAt() method
Mockito.when(rcv.getChildAt(0)).thenReturn(objectYouWantToBeReturned);
Obviously you need to create objectYouWantToBeReturned before using when.
The code above will make rcv.getChildAt(0) returns the object you want, but only if you call it with parameter 0.
If you want to return the same object for any value (not only 0), you can do:
Mockito.when(rcv.getChildAt(Mockito.anyInt())).thenReturn(objectYouWantToBeReturned);
This will return objectYouWantToBeReturned for all calls of getChildAt, no matter what's the parameter value.
Related
Am having a challenge, where my test passes when I run it alone but fails when I run all the tests, it shows me this error message :
java.lang.RuntimeException: Method getMainLooper in android.os.Looper
not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.os.Looper.getMainLooper(Looper.java) at
retrofit2.Platform$Android$MainThreadExecutor.(Platform.java:172)
at
retrofit2.Platform$Android.defaultCallbackExecutor(Platform.java:145)
at retrofit2.Retrofit$Builder.build(Retrofit.java:585) at
com.andela.mrm.notifications.SlackService.getApi(SlackService.kt:26)
at
com.andela.mrm.notifications.SlackServiceTest.getAPI(SlackServiceTest.kt:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.junit.runners.Suite.runChild(Suite.java:128) at
org.junit.runners.Suite.runChild(Suite.java:27) at
org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at
com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at
com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Below is the Retrofit instance I want to test :
class SlackService {
private var retrofit: Retrofit? = null
/**
* This method creates a new instance of the API interface.
*
* #return The API interface
*/
val api: SlackApi
get() {
val baseURL = "https://hooks.slack.com/"
val client = ApiService.getOkHttpClient()
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(baseURL)
.client(client)
.build()
}
return retrofit!!.create(SlackApi::class.java)
}
}
And then, this is a test for the Retrofit Instance :
class SlackServiceTest {
#Test
fun getAPI() {
val slackService = SlackService()
assertNotNull(slackService.api)
}
}
I managed to see some similar issues via here but they are related with RxJava , and am not using it, how can I be helped ?
Thanks
Adding this fixed the issue for me.
android {
// ...
testOptions {
unitTests.returnDefaultValues = true
}
}
I found the solution by Liz here and it worked for me. It was a silly mistake. Glad to find a solution after a long trials. https://stackoverflow.com/a/69109928
Pasting the solution for easy reference
In case none of the solutions worked alike in my case, if you are using a later version of Gradle and you are using androix, make sure you import from androix in your build gradle.
implementation 'androidx.arch.core:core-testing:$version'
instead of
implementation 'android.arch.core:core-testing:$version'
Actually, I finally got the answer, it's in the link below:
Answer
I am trying to mock a service using Mockito, but it is saying i have not used argument Mather correctly.
import com.spmsoftware.appframework.validation.ValidationContext;
import com.spmsoftware.appframework.validation.ValidationContextSupport;
import com.spmsoftware.filters.api.model.Filter;
import com.spmsoftware.filters.api.validation.FilterValidationService;
import com.spmsoftware.tablereference.api.service.TableReferenceService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.when;
public class TestInputTabValidator {
#Mock
private Filter filter;
#Mock
private TableReferenceService tableReferenceService;
#Mock
private FilterValidationService filterValidationService;
#InjectMocks private InputTabValidator inputTabValidator;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
preCondition();
}
private void preCondition() {
when(tableReferenceService.getTable(anyLong())).thenReturn(anyObject());
when(tableReferenceService.tableExists(1L)).thenReturn(true);
}
#Test
public void validateInputTabSaveWithFilter() {
ValidationContext validationContext = new ValidationContextSupport();
inputTabValidator.validate(new Object[]{anyLong(), filter}, validationContext);
Assert.assertTrue("no validation errors recorded", !validationContext.hasErrors());
}
public void validateInputTabSaveWithoutFilter() {
ValidationContext validationContext = new ValidationContextSupport();
inputTabValidator.validate(new Object[]{anyLong()}, validationContext);
Assert.assertTrue("no validation errors recorded", !validationContext.hasErrors());
}
}
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
1 matchers expected, 2 recorded:
-> at com.spmsoftware.genericWebservices.validator.TestInputTabValidator.preCondition(TestInputTabValidator.java:55)
-> at com.spmsoftware.genericWebservices.validator.TestInputTabValidator.preCondition(TestInputTabValidator.java:56)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
at com.spmsoftware.genericWebservices.validator.TestInputTabValidator.preCondition(TestInputTabValidator.java:56)
at com.spmsoftware.genericWebservices.validator.TestInputTabValidator.setUp(TestInputTabValidator.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Cause is due to Mockito.any(MessageCreator.class) , but isn't there a way to test my send method is getting executed without creating an actual object in the MessageCreator?
The problem is in the following line:
when(tableReferenceService.getTable(anyLong())).thenReturn(anyObject());
You can't use a matcher as the expected return value. What you want is probably something like:
when(tableReferenceService.getTable(anyLong())).thenReturn(new Table());
or
Table table = mock(Table.class);
when(tableReferenceService.getTable(anyLong())).thenReturn(table);
depending on whether the object returned by tableReferenceService.getTable() requires mocking or not.
I'm having an issue with a JUnit test I made. The method I'm testing takes an InputStream should throw an exception if the passed InputStream doesn't support mark/reset.
The problem I am running into is that my test to ensure an exception gets thrown when an InputStream that doesn't support mark/reset gets passed (posted below) keeps throwing an AccessDeniedException.
public class IOTest{
#Rule
public TemporaryFolder tempFolder = TemporaryFolder()
#Before
public void createFolder() throws IOException {
Files.createDirectories(tempFolder.getRoot().toPath().resolve("testFile"));
}
#Test(expected = IllegalArgumentException.class)
public void testDetectCharsetOnlyAcceptsMarkResetSupportedInputStreams() throws IOException {
final Path testPath = tempFolder.getRoot().toPath().resolve("testFile");
final InputStream testStream = Files.newInputStream(testPath);
IO.detectCharset(testStream);
}
}
I think the problem I'm running into has to do with accessing the temporary folder, but I don't know how to circumvent this.
Here is the stack trace that gets printed when I run this test:
java.lang.Exception: Unexpected exception, expected<java.lang.IllegalArgumentException> but was<java.nio.file.AccessDeniedException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.nio.file.AccessDeniedException: C:\Users\antho\AppData\Local\Temp\junit4390480127201295432\testFile
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
at java.nio.file.Files.newInputStream(Files.java:152)
at com.bunnell.anthony.booker.IOTest.testDetectCharsetOnlyAcceptsMarkResetSupportedInputStreams(IOTest.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
... 24 more
I'm guessing it has something to do with permissions and the OS, but I'm just not sure how to get around this problem. If it helps, I'm using Windows 10.
You're trying to read from testFile, which is not a file but a directory; you're creating with
Files.createDirectories(tempFolder.getRoot().toPath().resolve("testFile"));
whose documentation says:
Creates a directory by creating all nonexistent parent directories first.
(emphasis mine)
In order to keep your JUnit tests portable and simple, I would suggest removing the external file dependency entirely.
You can do this in two ways:
Create an InputStream from something internal, like a String or byte array. Here is how with strings
Use a mocking framework, such as Mockito, to create a dummy InputStream that has just enough functionality to confirm that the method works. This would be my preferred strategy, as mocking produces much cleaner tests.
I am trying to set exclusive start key to my request so that I can have my LastEvaluatedKey afterwards.
The follow exception occurs when I iterate over my query result. Can anyone help me in this regard?
"The provided starting key does not match the range key predicate"
QuerySpec queryExpression = ...
queryExpression = queryExpression.withExclusiveStartKey(OFFSET_PRIMARY_KEY, offsetParts[OFFSET_PRIMARY_KEY_INDEX], OFFSET_SORT_KEY, Long.valueOf( offsetParts[OFFSET_SORT_KEY_INDEX]));
ItemCollection<QueryOutcome> items = table.query(queryExpression);
Iterator<Item> iterator = items.iterator();
iterator.forEachRemaining(m -> { //exception occurs here
...
});
Stack Trace:
com.amazonaws.AmazonServiceException: The provided starting key does not match the range key predicate (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 6EA9NOO079F7VUVV1JP92P05MRVV4KQNSO5AEMVJF66Q9ASUAAJG)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1389)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:902)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:607)
at com.amazonaws.http.AmazonHttpClient.doExecute(AmazonHttpClient.java:376)
at com.amazonaws.http.AmazonHttpClient.executeWithTimer(AmazonHttpClient.java:338)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:287)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:1985)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.query(AmazonDynamoDBClient.java:1620)
at com.amazonaws.services.dynamodbv2.document.internal.QueryCollection.firstPage(QueryCollection.java:53)
at com.amazonaws.services.dynamodbv2.document.internal.PageIterator.next(PageIterator.java:45)
at com.amazonaws.services.dynamodbv2.document.internal.PageIterator.next(PageIterator.java:25)
at java.lang.Iterable.forEach(Iterable.java:74)
at com.my.com.services.database.DynamoDatabaseRepository.fetchMessageList(DynamoDatabaseRepository.java:675)
at service.DatabaseServiceTest.accc(DatabaseServiceTest.java:106)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:130)
The “The provided starting key does not match the range key predicate” means that DynamoDB cannot hit the Item that ExclusiveStartKey represents by your query condition.So when you use queryPage api, you'd better not change the query condition until you find the last item; and you'd better not update the item that may be included in your pagination result.
Hope this answer can help someone.
This can happen if the row represented by the ExclusiveStartKey that you are passing no longer appears in the dynamodb query result.
Consider the case below:
Your Primary partition key is named "message_id"
Your Primary sort key is named "message_timestamp"
Your ExclusiveStartKey value is: '{"message_id":"3483b80a358cf60decfccc329bd5e72e","message_timestamp":1481114525}'
You are using KeyConditionExpression as: Key("message_id").eq("3483b80a358cf60decfccc329bd5e72e") & Key("message_timestamp").gt(1481202107)
Since the message_timestamp in KeyConditionExpression is greater than the corresponding value in ExclusiveStartKey, dynamodb will throw the error that you mentioned.
I am working on a Java RMI project and I am trying to begin to test the code I've written and when I run the following code, I get an AssertionError on a line that doesn't even have an assertion statement. I am confused as to how to fix this.
public void basicTest() throws UnknownHostException, RemoteException, AlreadyBoundException, NotBoundException, InterruptedException {
int numBooks = 20;
int copiesPerBook = 5;
int booksPerMember = 4;
// Simulate the server
LibraryServerImpl library = new LibraryServerImpl(numBooks, copiesPerBook, booksPerMember);
LibraryServer stub = (LibraryServer) java.rmi.server.UnicastRemoteObject.exportObject(library, 0);
Registry registry = LocateRegistry.createRegistry(port);
registry.bind(libraryName, stub);
// Simulate the client
Member member = new MemberImpl();
assertNotNull(member.getName()); // Will fail until you implement MemberImpl
Thread t = new Thread(new BasicClient(member));
t.start();
t.join();
}
This is the copied trace:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertNotNull(Assert.java:712)
at org.junit.Assert.assertNotNull(Assert.java:722)
at PublicTests.basicTest(PublicTests.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Line 56 corresponds to registry.bind(libraryName, stub);
Clearly, this does not make sense, so one of the facts is false.
Fact: you got the above stack trace. --no reason to doubt the truthfulness of this fact.
Fact: PublicTests.java is written by you. --no reason to doubt the truthfulness of this fact.
Fact: line 56 of PublicTests.java corresponds to registry.bind(libraryName, stub). Well, this cannot be true, since according to the stack trace, the failure is detected by a call to org.junit.Assert.assertNotNull(), but the line registry.bind(libraryName, stub) is not an invocation of org.junit.Assert.assertNotNull().
However, further down in your code you do have an invocation of assertNotNull(member.getName()), which means that this must be what is being reported as line 56.
So, what you are looking at is a mismatch in the line number being reported in the stack trace. As user indivisible suggested, please refresh your project, clean your output folder, rebuild all projects, and try again.