简体   繁体   中英

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

<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?

Do you need DI on your unit tests?

I prefer the setter injection because then you don't need to initialize 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:

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(){...}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM