【问题标题】:SpringMVC Mockito Mocking values of class within classSpringMVC Mockito 在类中模拟类的值
【发布时间】:2016-12-13 14:33:59
【问题描述】:

当我从 testclass 运行 class1 中的方法 try() 时,我正在尝试使用 mockito 来模拟 class3 中 method3() 的返回值。我有不能对我拥有的代码进行任何版本的限制。所以,我不能根据我在互联网上看到的一些解决方案添加构造函数来制作模拟。我将 MockMVC 与 WebApplicationContextSetup 一起使用。请指导我是否可以仅使用 mockito 模拟 method3() 的值,如果不可能,我可以用来模拟该值的其他解决方案是什么?

class1
{
     Class2 c2 = new Class2();
     public String try()
     {
        Something temp1 = c2.method1();
     }
}

class2
{
   Class3 c3 = new Class3();
   public String method1()
   {
      return c3.method3();
   }
}
class3
{
  //Will like to mock the return value of this method
  public String method3()
  {
     return "asd";
  }
}
testclass
{
     class1 c1 = new class1();
     c1.try();
}

非常感谢:D

【问题讨论】:

    标签: spring unit-testing spring-mvc mockito mockmvc


    【解决方案1】:

    关于你的代码,看起来你需要模拟一个静态方法:

    return Class3.method3();
    

    没有

    public String method3()
    

    请准确,因为根据您是否需要模拟静态方法,答案会有所不同。

    【讨论】:

      【解决方案2】:

      为此,您需要监视您的 class2。

      import org.junit.Before;
      import org.junit.Test;
      import org.mockito.*;
      import static org.junit.Assert.assertEquals;
      
      public class TestClass {
      
      @InjectMocks
      private Class1 class1 = new Class1();
      
      @InjectMocks @Spy
      private Class2 class2 = new Class2();
      
      @Mock
      private Class3 class3;
      
      @Before
      public void init() {
          MockitoAnnotations.initMocks(this);
      }
      
      @Test
      public void testWithMock() {
          Mockito.when(class3.method3()).thenReturn("mocked");
          assertEquals("mocked", class1.doTry());
      }
      
      }
      

      【讨论】:

      • 因此,如果在到达 class3 的调用之间有更多类。我必须监视所有那些中间类?
      • 确实如此。通常,当您必须在测试中做如此复杂的事情时,要么您正在测试遗留代码,要么您处于特定情况(它发生),要么您做错了什么。通常,你会模拟被测系统的依赖关系,但更罕见的是,模拟被测系统的依赖关系的依赖关系。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多