I am currently testing a method in which I execute a runnable into a ThreadPool.
Here is the code for the method.
@Override
public void queueLogin(Connection connection, LoginPacket packet) {
if(isRunning)
loginPool.execute(() -> loginService.tryLogin(connection, packet));
}
Now I need to verify whether the execute method was invoked or not with the correct parameters.
Here is my test case
@Test
public void theQueueLoginShouldCallExecuteOnThreadPoolIfManagerIsRunning() {
//Arrange
loginManager.start();
//Act
loginManager.queueLogin(moqConnection, moqLoginPacket);
//Assert
verify(moqLoginPool).execute(() -> moqLoginService.tryLogin(moqConnection, moqLoginPacket));
}
But the test is failing saying
Argument(s) are different! Wanted:
executorService.execute(
com.battletanks.game.server.unittests.manager.login.LoginManagerTests$$Lambda$2/1668016508@3d51f06e
);
-> at com.battletanks.game.server.unittests.manager.login.LoginManagerTests.theQueueLoginShouldCallExecuteOnThreadPoolIfManagerIsNotRunning(LoginManagerTests.java:84)
Actual invocation has different arguments:
executorService.execute(
com.battletanks.game.server.manager.login.DefaultLoginManager$$Lambda$1/77269878@7ed7259e
);
I understand what is wrong here but I am not sure how to fix this.
The way you have it, you're relying on these two lambdas to be equal to one another. Because they don't have an overridden equals
method, and are not the same instance, you won't be able to verify that way.
Instead, capture the argument , run it, and see that it does what you want it to do.
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.for(Runnable.class);
verify(moqLoginPool).execute(runnableCaptor.capture());
verify(moqLoginService, never()).tryLogin(any(), any());
runnableCaptor.getValue().run();
verify(moqLoginService).tryLogin(any(), any());
如何验证是否使用任何参数调用了moqLoginPool).execute(),然后确保执行完成后使用moqConnection,moqLoginPacket调用moqLoginService.tryLogin()?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.