gpt4 book ai didi

java - Easymock 调用 Autowiring 的对象方法

转载 作者:行者123 更新时间:2023-11-28 21:24:27 25 4
gpt4 key购买 nike

假设我有以下类(class):

public class A {
@Autowired B b;
public void doSomething(){
b.doSomeThingElse();
}


@Component
@Autowired C c;
public class B {
public void doSomethingElse(){
c.doIt();
}

当你知道我想模拟 c.doIt() 但想用 EasyMock 调用 b.doSomethingElse(); 时,我如何测试 A?

提前致谢

最佳答案

@Autowired 很好,但往往会让我们忘记如何测试。只需为 bc 添加一个 setter。

C c = mock(C.class);
c.doIt();

replay(c);

B b = new B();
b.setC(c);
A a = new A();
a.setB(b);

a.doSomething();

verify(c);

或者使用构造函数注入(inject)。

C c = mock(C.class);
c.doIt();

replay(c);

B b = new B(c);
A a = new A(b);

a.doSomething();

verify(c);

在这种情况下,您的类变为:

public class A {
private B b;
public A(B b) { // Spring will autowired by magic when calling the constructor
this.b = b;
}
public void doSomething() {
b.doSomeThingElse();
}
}

@Component
public class B {
private C c;
public B(C c) {
this.c = c;
}
public void doSomethingElse(){
c.doIt();
}
}

关于java - Easymock 调用 Autowiring 的对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44041189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com