【发布时间】:2015-06-24 13:45:47
【问题描述】:
我是 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);
然后它可以工作并给我设备的非空对象。
这是什么原因?
【问题讨论】:
-
然后它可以工作并给我设备的非空对象。还有什么问题?不是空对象?