0
我創建了我的第一批閱讀器,並打算用mockito測試我的課程。我不知道如何完全做到這一點。下面你會發現我的課程「Trailreader」和我開始開發的測試課「Trailreadertest」。我事先感謝您的幫助。如何使用mockito編寫批量閱讀器的單元測試
Trailreader類:
public class Trailreader implements ItemReader<TrailreaderInfo> {
private static final Logger LOG = LoggerFactory.getLogger(Trailreader.class);
private static final int LIMIT = 10;
@Value("#{configurationBatch.limit}")
public String limitString;
public String tableName;
public int nbLimit;
public List<Long> listToDelete;
@Inject
@Named("trailDao")
public transient ITrailDao trailDao;
public Trailreader() {
super();
}
/**
* Initialize
*/
@PostConstruct
public void initialize() {
try {
nbLimit = Integer.parseInt(limitString);
} catch (NumberFormatException e) {
nbLimit = LIMIT;
}
}
@DoNotLog
@Transactional
@Override
public TrailreaderInfo read() throws Exception, UnexpectedInputException, NonTransientResourceException {
try {
List<String> tableList = trailDao.getTablesList();
for (String tableName : tableList) {
List<Long> list_id = trailDao.getlist_idByDate(tableName);
List<Long> listToDelete = new ArrayList<Long>();
if (list_id.size() > nbLimit) {
int list_id_size = list_id.size();
int j = 0;
while (list_id_size > nbLimit) {
listToDelete.add(list_id.get(j));
list_id_size--;
j++;
}
}
}
return new TrailreaderInfo(tableName, nbLimit, listToDelete);
} catch (Exception e) {
LOG.error(e.getClass().getName(), e.getMessage());
throw new ParseException(e.getMessage());
}
}
}
測試類:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-applicationContext.xml" })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class TrailreaderTest {
private static final Logger LOG = LoggerFactory.getLogger(TrailreaderTest.class);
@InjectMocks
protected transient Trailreader reader;
@Inject
@Named("trailDao")
protected transient ITrailDao trailDao;
@Before
public void setUp() throws Exception {
LOG.info(TrailreaderTest.class.getSimpleName());
}
/**
* Initialization method
*/
@Transactional(value = Transactions.TX_MANAGER_READ_WRITE, readOnly = false)
protected void initialization() {
reader.trailDao = trailDao;
reader.limitString = "10";
reader.nbLimit = 10;
reader.initialize();
}
@Test
public void HistoryBackOfficeInfo() {
initialization();
}
}
歡迎來到SO!你已經發布了一切我們需要幫助你的東西,但有一件事:你的問題是什麼。你卡在哪裏?或...爲什麼測試不起作用? –
我的問題是我不知道如何測試我的課程。什麼變量被初始化?如何測試讀取方法?比較結果和預期的結果?謝謝你的幫助 – user3612284
如果你正在使用mockito,你應該模擬'Trailreader'依賴項('ITrailDao')並存根'ITrailDao :: getTablesList'和'ITrailDao :: getlist_idByDate'方法。 – gontard