我有一个需要进行单元测试的服务类。该服务具有上载方法,该方法又调用其他服务(自动装配的Bean)来更新数据库。我需要模拟其中一些服务,并按原样执行。
@Service
public class UploadServiceImpl implements UploadService{
@Autowired
private ServiceA serviceA;
@Autowired
private ServiceB serviceB;
public void upload(){
serviceA.execute();
serviceB.execute():
//code...
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我需要模拟ServiceA,但我希望ServiceB照常运行并执行其功能。我的Junit测试看起来像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=Swagger2SpringBoot.class)
public class UploadServiceTest {
@Mock
private ServiceA serviceA;
@InjectMocks
private UploadServiceImpl uploadService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testUpload(){
uploadService.upload();
}
Run Code Online (Sandbox Code Playgroud)
当我执行此我得到NPE在serviceB.execute();在UploadServiceImpl。
可能是什么问题呢?
注意:我没有指定模拟对象的行为,因为我并不在乎,模拟对象的默认行为也不执行任何操作。
谢谢!