【问题标题】:the stubbed value is not being return when I mock on a class当我模拟一个类时,没有返回存根值
【发布时间】:2020-05-04 21:43:09
【问题描述】:

我正在模拟一个类并存根其中一个方法以返回我想要的值,但由于我需要传递 .class 值,因此不会返回模拟数据。任何见解都值得赞赏。

public class Generator{

   public int getSomething(){
      return 1;
   }
 }

public class Utility{

 public void generate(java.lang.Class<?> class){

  }

 }

@RunWith(SpringRunner.class)
public class TestClass extends Utility{

 @Test
 public void test()

 Generator gen = Mockito.spy(Generator.class)
 Mockito.when(gen.getSomething()).thenReturn(4);

  Int x = generate(gen.getClass())
 // in here 1 is being returned instead of 4
}

}

【问题讨论】:

  • 您使用间谍而不是模拟的任何原因?
  • 哪个类有generate方法,它有什么作用?请注意,getClass() 不会在模拟或间谍上为您提供与在普通对象上相同的结果。
  • generate 是我用来调用生成器的实用程序类中的一个方法
  • 这可能就是问题所在。
  • 我认为问题可能是我正在使用 getClass() 方法。我从该方法获得的结果与我从间谍获得的对象有何不同?

标签: java spring-boot mocking mockito


【解决方案1】:

用于与模拟对象不同的间谍对象

试试

Mockito.doReturn(4).when(gen).getSomething();


下面的代码非常适合我

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
public class TestClass {
    @Test
     public void test() {

     Generator gen = Mockito.spy(Generator.class);

     Mockito.doReturn(4).when(gen).getSomething();
     assertEquals(4, gen.getSomething());
    }
}

class Generator{

       public int getSomething(){
          return 1;
       }
     } 

【讨论】:

  • 值得注意的是,这种方法适用于间谍和模拟。 Mockito.when 方法有点麻烦。
  • @DawoodibnKareem 如果你认为这是可能的解决方案,你介意支持答案:)
  • 这对我不起作用,我得到了相同的结果。我正在使用间谍,所以我只是部分地嘲笑那个类
猜你喜欢
  • 2019-01-15
  • 1970-01-01
  • 2019-08-18
  • 2017-08-05
  • 2022-07-25
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
  • 2019-04-12
相关资源
最近更新 更多