我有一个类使用@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 TestClass {
@Autowired
private A;
@Before
public init() {
expect(b.dosomething()).andReturns(x);
}
@Test
public test1() {
//test
}
}
我 mock B 因为它进行 HTTP 调用以获取 x。但是在通过单元测试运行它时,出现以下错误:
Missing behaviour definition for the preceding method call:
B.dosomething().andXXX()
如果我在 A 类的一些普通方法中做同样的事情,一切都很好。我正在使用 spring 进行依赖注入(inject)。
我认为这种行为的原因是,因为我在我的单元测试中设置了对类 B 的模拟的期望,它在调用此 init 方法“之后”被调用。我该如何测试它?
最佳答案
如果您希望测试类 A 的 @PostConstruct 注释“init”方法中的代码,您可以考虑在测试中不使用 Spring 来测试它。您将需要手动注入(inject)依赖项。
一种方法是:
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);
}
}
关于java - 简单模拟 : Setting expectation inside @PostConstruct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25230927/