简体   繁体   English

您如何使用 Mockito 从扩展 class 测试方法?

[英]How do you test method from extended class using Mockito?

I have a class A that extends from B. B has method called doB().我有一个从 B 延伸的 class A。B 具有称为 doB() 的方法。

In my test, I want to return A when doB() is called.在我的测试中,我想在调用 doB() 时返回 A。

Class B: Class B:

public String doB() {
    return "B";
}

Class A: Class A:

public class A extends B {
    
    public String doA() {
        String A = doB();
        return A;
    }
}

In my unit test, I want to do something like:在我的单元测试中,我想做类似的事情:

@Mock
private A a;

@Test
public void test() {
    when(a.doB()).thenReturn("PASS");
    a.doB();
    //check if it is "PASS"
}

However, it doesn't intercept when it calls doB() .但是,它在调用doB()时不会拦截。 Is this possible?这可能吗? If not, what is the best way to test this?如果不是,那么最好的测试方法是什么?

Perhaps favour composition over inheritance.也许更喜欢 inheritance 的组合。 In other words, instead of A extending B, A should use B. So B becomes A's collaborator.换句话说,A应该使用B而不是A扩展B。所以B成为A的合作者。

For example:例如:

public class B {
    public String doB() {
        return "B";
    }
}
public class A {
    private B b;

    public A(B b) {
        this.b = b;
    }

    public String doA() {
        String a = b.doB();
        return a;
    }
}

So your unit test would look something like:所以你的单元测试看起来像:

public class MyTest {
    @Mock
    private B b;

    @InjectMocks
    private A a;

    @Test
    public void test() {
        when(b.doB()).thenReturn("PASS");
        a.doA();
        //check if it is "PASS"
    }
}

This is an example of how TDD can contribute to good design.这是 TDD 如何有助于良好设计的一个示例。

Since you are mocking class A, the method will not really be executed, which means there is no call to doB inside youre mock execution.由于您是 mocking class A,因此该方法不会真正执行,这意味着您的模拟执行内部没有对 doB 的调用。 you should either setup your mock to call the real method你应该设置你的模拟来调用真正的方法

when(a.doA()).thenCallRealMethod();
verify(a,times(1)).doB();

or use a Spy instead of a Mock.或使用 Spy 而不是 Mock。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM