SampleDao { public Sample findSampleById(final Long sampleId, boolean lockRow) { return dbp.get().toSelect("select sample_name, update_sequence, update_time from sample where sample_id=?" + (lockRow ? " for update" : "")) .argLong(sampleId).queryOneOrNull(r -> { Sample result = new Sample(); result.setSampleId(sampleId); result.setName(r.getStringOrNull()); result.setUpdateSequence(r.getIntegerOrNull()); result.setUpdateTime(r.getDateOrNull()); return result; }); } SampleDao(Supplier<Database> dbp); void createSample(final Sample sample, Long userIdMakingChange); Sample findSampleById(final Long sampleId, boolean lockRow); void updateSample(Sample sample, Long userIdMakingChange); void deleteSample(Sample sample, Long userIdMakingChange);  }
@Test public void testFind() throws Exception { when(db.query(anyString(), anyString())).thenReturn(new RowStub() .withColumnNames("sample_name", "update_sequence", "update_time") .addRow("Foo", 3, now)); Sample sample = sampleDao.findSampleById(15L, false); assertEquals(new Long(15L), sample.getSampleId()); assertEquals("Foo", sample.getName()); assertEquals(new Integer(3), sample.getUpdateSequence()); assertEquals(now, sample.getUpdateTime()); verify(db).query(anyString(), eq("select sample_name, update_sequence, update_time from sample where sample_id=15")); verifyNoMoreInteractions(db); }
@Test public void testFindAndLock() throws Exception { when(db.query(anyString(), anyString())).thenReturn(new RowStub() .withColumnNames("sample_name", "update_sequence", "update_time") .addRow("Foo", 3, now)); Sample sample = sampleDao.findSampleById(15L, true); assertEquals(new Long(15L), sample.getSampleId()); assertEquals("Foo", sample.getName()); assertEquals(new Integer(3), sample.getUpdateSequence()); assertEquals(now, sample.getUpdateTime()); verify(db).query(anyString(), eq("select sample_name, update_sequence, update_time from sample where sample_id=15 for update")); verifyNoMoreInteractions(db); }