【发布时间】:2015-10-29 23:36:36
【问题描述】:
我有Thread,它在程序运行时运行并轮询队列并检查它是否有对象,如果有,则调用对象上的方法
代码如下:
while(isRunning){
synchronized (loginQueue) {
if(loginQueue.peek() != null) {
Object[] loginObjectWithConnection = loginQueue.poll();
tryLogin(loginObjectWithConnection);
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
这里是 tryLogin 方法
private void tryLogin(Object[] loginObjectWithConnection) {
LoginPacket packet = (LoginPacket)loginObjectWithConnection[0];
Connection connection = (Connection)loginObjectWithConnection[1];
try {
if(playerDataService.arevalidCredentials(packet.getUserName(), packet.getPassword())) {
if(!playerDataService.isPlayerBanned(packet.getUserName())){ //Player exists in the system
communicationService.sendTCP(connection, packetFactory.makeLoginFailurePacket(StringConstants.PLAYER_BANNED));
} else{ //Player is not banned
}
} else { // Player does not exist
communicationService.sendTCP(connection, packetFactory.makeLoginFailurePacket(StringConstants.INVALID_USER));
}
} catch (SQLException e) {
communicationService.sendTCP(connection, packetFactory.makeLoginFailurePacket(StringConstants.SERVER_ERROR));
e.printStackTrace();
}
}
现在我的问题是我想测试这些服务方法的调用,但是当我运行单元测试时,它们将无法工作,因为到达 tryLogin 点需要时间,直到那时 JUnit 失败。我尝试使用Thread.sleep(),但我知道这不是正确的方法,因为它有时会失败,有时会通过。
这是我的单元测试中的内容
@Test
public void theExpectedMessageShouldBeSentIfUserIsBanned() throws InterruptedException, SQLException {
//Arrange
when(moqLoginQueue.peek()).thenReturn(object);
when(moqLoginQueue.poll()).thenReturn(object);
LoginFailurePacket packet = new LoginFailurePacket(StringConstants.PLAYER_BANNED);
when(moqPacketFactory.makeLoginFailurePacket(StringConstants.PLAYER_BANNED)).thenReturn(packet);
when(moqPlayerDataService.arevalidCredentials(anyString(), anyString())).thenReturn(true);
when(moqPlayerDataService.isPlayerBanned(anyString())).thenReturn(true);
//Act
loginManager.start();
Thread.sleep(10); //Dirty hack -.-
//Assert
verify(moqCommunicationService).sendTCP(any(Connection.class), eq(packet));
}
【问题讨论】:
标签: java multithreading unit-testing junit mockito