Spring JpaRepository save() 不使用 Mockito 模拟
我是Mockito图书馆的新手,被困在某个地方。
问题是,当我模拟Spring jpaRepository的保存方法时,我总是得到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);
然后它工作,并给我不空的设备对象。
这是什么原因?