我有这样的 Spring Bean

@Component
public class Service extends AbstractService {
        @Autowired
        private OtherService otherService;
}

为了测试,我使用Service嘲笑创建了一个测试上下文
<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>

模拟仍然需要我模拟所有自动装配的依赖项。有没有一种方法可以只创建“哑”模拟而无需为所有依赖项创建bean?

最佳答案

您的单元测试中是否需要DI?

我更喜欢使用setter注入,因为这样就不需要初始化Spring Framework了。例如:

@Component
public class Service extends AbstractService {
    private OtherService otherService;

    @Autowired
    public void setOtherService(OtherService otherService){...}
}

然后在您的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(){...}
}

09-26 02:50