我是Mockito库的新手,卡在某个地方。
问题是当我模拟Spring jpaRepository的save方法时,总是得到null。我在我的项目中使用了这样的代码,但是为了测试,我编写了一个虚拟代码。这是我的代码:
// This is the class for which I am making test case
@Service("deviceManagementService")
@Scope(BRASSConstants.SCOPE_SESSION)
@Transactional
public class DeviceManagementServiceImpl implements DeviceManagementService {
public String show(){
Device device = new Device() ;
device.setContactName("abc");
Device deviceEntity = deviceDao.save(device);
System.out.println(deviceEntity); // i get this null always Why ???
return "demo";
}
}
我正在编写的测试用例是:
@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
@InjectMocks
private DeviceManagementServiceImpl deviceManagementServiceImpl;
@Mock
private DeviceDao deviceDao;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void show(){
Device device = new Device() ;
Device deviceEntity = new Device() ;
deviceEntity.setDeviceId(12L);
Mockito.when(deviceDao.save(device)).thenReturn(deviceEntity);
Mockito.when(deviceManagementServiceImpl.show()).thenReturn(null) ;
}
}
如果我使用类似这样的东西
Mockito.when(deviceDao.findByDeviceSerialNo("234er")).thenReturn(deviceEntity);
然后它运行并为我提供了Device的非空对象。
这是什么原因?