私はJavaでプログラミングするのはかなり初めてですが、ユニットテストから直接始めようとしたため、JMockも使用しました。動作するいくつかのテストケース (JMock を使用) を既に実装していますが、これは実行できません。
私がしたこと: モック オブジェクトを作成するテスト クラスを作成し、(oneOf を使用して) 呼び出しを期待しています。単体テストを実行すると、失敗したと表示されます (ただし、will(returnValue(x))
.
次の面白い/奇妙なことは、oneOf を「never」に変更すると、単体テストは成功しますが、例外がスローされます。
Exception in thread "Thread-2" java.lang.AssertionError: unexpected invocation: blockingQueue.take()
期待: 期待されていない、決して呼び出されていない:blockingQueue.take(); これより前に何が起こったかを返します: 何もありません!
ここにコード:
@RunWith(JMock.class)
public class ExecuteGameRunnableTest {
private Mockery context = new JUnit4Mockery();
private Thread testObject;
private BlockingQueue<Game> queueMock;
private Executor executorMock;
@SuppressWarnings("unchecked")
@Before
public void setUp() {
queueMock = context.mock(BlockingQueue.class);
executorMock = context.mock(Executor.class);
testObject = new Thread(new ExecuteGameRunnable(queueMock, executorMock, true));
}
@After
public void tearDown() {
queueMock = null;
executorMock = null;
testObject = null;
}
@Test
public void testQueueTake() throws InterruptedException {
final Game game = new Game();
game.setId(1);
game.setProcessing(false);
context.checking(new Expectations() {{
never(queueMock).take(); will(returnValue(game));
}});
testObject.start();
context.assertIsSatisfied();
}
}
そして、私がテストしている実行可能ファイル:
public class ExecuteGameRunnable implements Runnable {
private BlockingQueue<Game> queue;
private Executor executor;
private Boolean unitTesting = false;
static Logger logger = Logger.getLogger(ExecuteGameRunnable.class);
public ExecuteGameRunnable(BlockingQueue<Game> queue, Executor executor) {
this.queue = queue;
this.executor = executor;
}
public ExecuteGameRunnable (BlockingQueue<Game> queue, Executor executor, Boolean unitTesting) {
this(queue,executor);
this.unitTesting = unitTesting;
}
public void run() {
try {
do {
if (Thread.interrupted()) throw new InterruptedException();
Game game = queue.take();
logger.info("Game "+game.getId()+" taken. Checking if it is processing"); // THIS ONE PRINTS OUT THE GAME ID THAT I RETURN WITH JMOCK-FRAMEWORK
if (game.isProcessing()) {
continue;
}
game.updateProcessing(true);
executor.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
});
} while (!unitTesting);
} catch (InterruptedException ex) {
logger.info("Game-Execution-Executor interrupted.");
return;
} catch (DataSourceException ex) {
logger.fatal("Unable to connect to DB whilst executing game: "+id_game,ex);
return;
}
}
}