【问题标题】:how to stub a method in a class which is called from another class如何存根从另一个类调用的类中的方法
【发布时间】:2021-10-05 02:05:39
【问题描述】:
public class A {
    .
    .
    .
    public static String methodA() {
        String x = new B().methodX();
        return x + "how are ya?";
    }
}
public class B {
    .
    .
    public String methodX() {
        return "Hello!";
    }
}

@Test
public void testGreeting() {
    final B b = Mockito.spy(new B());
    Mockito.when(b.methodX()).thenReturn("Hi!");

    String greetings = A.methodA();
    // greetings -> "Hello" but i want it to be "Hi!".
}

我无法让我的方法返回所需的值。 上面的实现显示了我是如何编写测试的,但它不起作用。

我在这里做错了什么?

【问题讨论】:

  • 要么在 A 的实例中注入 b(手动或使用注入框架),要么可以监视整个类而不是实例,如 Mockito.spy(B.class);。选项 1 可能更干净。

标签: java testing junit mockito stub


【解决方案1】:

尚未澄清给出的答案:您的错误是您实际上并未在任何地方使用该间谍/模拟。

在您的 A 类中,您有一个静态方法,其中始终实例化新的 B 而不是使用您的间谍:

String x = new B().methodX();

Spy 不会以某种方式在全局范围内创建类spied,而是只创建一个被监视且可以模拟的实例。再说一遍:这个new B() 既不是间谍也不是模仿者。

一个可能可行的解决方案是稍微改变你的设计(正如已经建议的那样),让 Mockito 在 A 的实例中注入这个间谍 B:

@RunWith(MockitoJUnitRunner.class)
public class TestClass {

    public static class AlternativeA {
        // this B can be injected and replaced with a spy or mock
        private B b = new B();
        // get rid of static to use spied B
        public String methodA() {
            String x = b.methodX();
            return x + "how are ya?";
        }
    }

    // Using annotations to create and inject mocks
    @Spy
    private B b;
    @InjectMocks
    private AlternativeA a;
    
    @Test
    public void testGreeting() {
        Mockito.when(b.methodX()).thenReturn("Hi!");
        String greetings = a.methodA();
    }
}

【讨论】:

    【解决方案2】:

    要完成 wakio 编写的答案,您可以编写:

    public class A {
        private B b;
    
        public String methodA() {
            String x = b.methodX();
            return x + "how are ya?";
        }
    
        public void setB(B b) {
            this.b = b;
        }
    }
    
    public class B {
        public String methodX() {
            return "Hello!";
        }
    }
    
    @Test
    public void testGreeting() {
        B b = Mockito.mock(B.class);
        Mockito.when(b.methodX()).thenReturn("Hi!");
    
        A a = new A();
        a.setB(b);
    
        String greetings = a.methodA();
        // The result will be "Hi!"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多