正在为mockito调用主类中的java方法

rbpvctlc  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(446)

我正在为我班上的一个方法写一个测试类。我在班上没什么变化。下面是我的代码的简单版本。

  1. Class AInternal extend A {
  2. public List getList(listArg1, listArg2) {
  3. boolean flag = isCorrectFlag();
  4. if (flag) {
  5. return getListForNext(nextArg1, nextArg2);
  6. }
  7. }
  8. public boolean isCorrectFlag(){
  9. //logic and return value
  10. }
  11. protected List getListForNext(nextArg1, nextArg2) {
  12. AIteror arit = new AIterator();
  13. String s = fetchValue();
  14. arit.getObject();
  15. }
  16. protected class AIterator {
  17. public Iterator getObject() {
  18. //logic and return iterator
  19. }
  20. }
  21. }
  22. Class A {
  23. public String fetchValue() {
  24. //logic and return value
  25. }
  26. }

下面是我的测试方法

  1. @Test
  2. public void getList() throws Exception {
  3. try {
  4. AInternal AInternalSpy = spy(new AInternal());
  5. AIterator AIteratorSpy = spy(AInternal.new AIterator());
  6. Iterator<Object> iterator1 = ep.iterator();
  7. doReturn(Boolean.TRUE).when(AInternalSpy).isCorrectFlag();
  8. doReturn("value").when(AInternalSpy).fetchValue();
  9. doReturn(iterator1).when(AIterator).getObject();
  10. AInternalSpy.getIteratorPartitions(arg1, arg2);
  11. }
  12. catch (IllegalArgumentException e) {
  13. throw new Exception(e);
  14. }
  15. }

前两个doreturn返回正确的值,但是getobject()方法从类中调用该方法,并且不返回存根值。我尝试使用powermockito.whennew返回模拟示例,但没有成功。任何提示都会有帮助。

xam8gpfp

xam8gpfp1#

您可以将创建的新示例移动到一个新函数中,如下所示:

  1. protected AIterator getIteratorInstance() {
  2. return new AIterator();
  3. }

现在,可以将getlistfornext(…)函数修改为:

  1. protected List getListForNext(nextArg1, nextArg2) {
  2. AIteror arit = getIteratorInstance();
  3. String s = fetchValue();
  4. arit.getObject();
  5. }

现在为新创建的getiteratorinstance()函数返回一个模拟或间谍的aiterator:

  1. doReturn(AIteratorSpy).when(AInternalSpy).getIteratorInstance()

你的测试现在应该执行了。

展开查看全部

相关问题