Java 轻松模拟:在@PostConstruct内设置期望值
我有一个类,它使用@PostConstruct缓存一些对象Java 轻松模拟:在@PostConstruct内设置期望值,java,spring,unit-testing,easymock,Java,Spring,Unit Testing,Easymock,我有一个类,它使用@PostConstruct缓存一些对象 @Component public class A { @Autowired private B b; private X x; @PostConstruct public void init(){ x = b.doSomething() } } public class C { @Autowired private A; } public class T
@Component
public class A {
@Autowired
private B b;
private X x;
@PostConstruct
public void init(){
x = b.doSomething()
}
}
public class C {
@Autowired
private A;
}
public class TestClass {
@Autowired
private A;
@Before
public init() {
expect(b.dosomething()).andReturns(x);
}
@Test
public test1() {
//test
}
}
我已经模拟了B,因为它通过HTTP调用来获取x。但在通过单元测试运行此测试时,我得到以下错误:
Missing behaviour definition for the preceding method call:
B.dosomething().andXXX()
如果我在类A的某个普通方法中执行相同的操作,那么一切都会正常工作。我使用spring进行依赖项注入
我认为这种行为的原因是,因为我在我的单元测试中对类B的mock设置了期望值,该类在调用init方法之后被调用。如何测试这个?< p>如果你想测试类A的@后构造注释“init”方法中的代码,你可以考虑在测试中不使用Spring来测试它。您将需要手动注入依赖项 一种方法是:
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
public class TestA {
private A a = new A();
private B b = EasyMock.createMock(B.class);
@Before
public void init() {
Whitebox.setInternalState(a, "b", b);
}
@Test
public void testInit() {
EasyMock.reset(b);
//define mock behavior here
EasyMock.replay(b);
a.init();
//assert and verify
EasyMock.verify(b);
}
}
给我们看看你的代码。我们无法解释为什么代码在没有看到代码的情况下无法工作。我想我可以感觉到问题将是什么,但您是否可以提供您的测试类和测试上下文,以便我们可以看到出现问题的代码?看到测试上下文也会很有帮助,但最终的问题是,您没有将B的实例注入到测试类中。如果没有对注入到a对象中的B的实际实例的引用,您将无法对其设置期望值。(请记住,Spring上下文中的对象是单例的。)一旦您在测试类中有了引用,您可能会遇到您正在思考的问题。我建议使用静态方法创建mock B实例,该方法设置期望值并将mock置于重播模式。