【发布时间】:2018-05-11 06:15:05
【问题描述】:
我们目前正在使用 JUnit 和 Mockito 来测试我们的代码。
我们有一个类似下面的服务接口。
public interface ServiceA {
void doSomething();
}
它的实现类如下。
@Service
@Transactional
public class ServiceAImpl implements ServiceA {
@Inject
private RepositoryA repA;
@Inject
private ShareServiceA sharedServA;
public void doSomething(){
}
}
现在,我只想模拟 ServiceAImpl 类的 repA 依赖项。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
@DirtiesContext(classMode= DirtiesContext.ClassMode.AFTER_CLASS)
public class ServiceAImplTest {
@Mock
RepositoryA repA;
@InjectMocks
ServiceA servA = new ServiceAImpl();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
........
}
}
调用initMocks后,只启动了ServiceImpl的repA依赖,sharedServA保持为null,当被测类调用sharedServA的方法时,导致null异常。
根据我在互联网和书籍上阅读的一些参考资料,只有在被测试的类具有声明了参数的构造函数时才会发生这种情况。但是,对于我上面的示例,我没有声明任何构造函数。这是正确的行为还是我错过了什么?
【问题讨论】:
-
您可以通过清理 API 以使用构造函数注入来完全避免这种情况,这样做的好处是根本不需要使用 Spring 进行测试。
标签: java spring junit mocking mockito