如何使用mockit编写批处理阅读器的单元测试



我创建了我的第一个批处理阅读器,我打算用mockit测试我的类。我不知道该怎么做。下面你会发现我的类"Trailreader"和我开始开发的测试类"Trailreadertest"。我提前感谢你的帮助。

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();   
    }   
}

如果你想测试你的ItemReader,那么你需要模拟它的依赖关系,而不是对象本身。

所以您需要模拟DAO。这样你就可以在DAO返回空值或空列表或某些特定值的情况下测试阅读器。

相关内容

  • 没有找到相关文章

最新更新