[英]How to create “deep” mock of a spring bean?
I have a spring beans like this 我有这样的春豆
@Component
public class Service extends AbstractService {
@Autowired
private OtherService otherService;
}
For test I created a test context with Service mock 为了测试,我使用Service mock创建了一个测试上下文
<bean id="serviceMock" class="org.easymock.EasyMock" factory-method="createMock" primary="true">
<constructor-arg index="0" type="java.lang.Class" value="com.pkg.my.Service"/>
</bean>
The mock still requires me to mock all the autowired dependencies. 模拟仍然需要我模拟所有自动连接的依赖项。 Is there a way to create just "dumb" mock without the need to create beans for all the dependencies?
有没有办法创建只是“哑”模拟而不需要为所有依赖项创建bean?
Do you need DI on your unit tests? 你的单元测试需要DI吗?
I prefer the setter injection because then you don't need to initialize Spring Framework. 我更喜欢setter注入,因为那时你不需要初始化Spring Framework。 For example:
例如:
@Component
public class Service extends AbstractService {
private OtherService otherService;
@Autowired
public void setOtherService(OtherService otherService){...}
}
And then on your Test class: 然后在你的Test类上:
public class ServiceTest {
private Service service;
private OtherService otherServiceMock;
@Before
public void setUp() {
otherServiceMock= mock(OtherService.class);
service = new Service();
service.setOtherService(otherServiceMock);
}
@Test
public void testSomeMethodBlaBla(){...}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.