本文介绍了单元测试如何使用Mockito模拟存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在清除存储库时遇到问题。有人建议我只创建另一个Applation.Properties(我还没有这样做),并使用像h2这样的内存数据库。不过,我想知道是否可以只将调用存根,这样在调用myDataService.findById(Id)时,而不是试图从数据库中获取时,只会返回一个模拟对象?
我刚开始为我的单元测试和Spring Boot编写模拟代码,所以我可能遗漏了一些东西。下面的代码(试图简化名称并使其成为通用名称以便在此处发布)。
我的测试类
public class MyServiceImplTest
{
private MyDataService myDataService;
private NyService myService;
private MyRepository myRepository;
@Before
public void setUp() {
myDataService = Mockito.mock(MyDataServiceImpl.class);
myService = new MyServiceImpl(myDataService);
}
@Test
public void getById_ValidId() {
doReturn(MyMockData.getMyObject()).when(myDataService).findById("1");
when(myService.getById("1")).thenReturn(MyMockData.getMyObject());
MyObject myObject = myService.getById("1");
//Whatever asserts need to be done on the object myObject
}
}
用于对数据层进行服务调用的类
@Service
public class MyServiceImpl implements MyService {
MyDataService myDataService;
@Autowired
public MyServiceImpl(MyDataService myDataService) {
this.myDataService = myDataService;
}
@Override
public MyObject getById(String id) {
if(id == null || id == "") {
throw new InvalidRequestException("Invalid Identifier");
}
MyObject myObj;
try {
myObj = myDataService.findById(id);
}catch(Exception ex) {
throw new SystemException("Internal Server Error");
}
return myObj;
}
}
这就是我在测试中遇到问题的地方。当调用findById()方法时,变量存储库为空,因此当尝试执行repository.findOne(Id)时,它抛出异常n。这就是我尝试模拟的内容,但存储库给我带来了问题。
@Repository
@Qualifier("MyRepo")
public class MyDataServiceImpl {
@PersistenceContext
private EntityManager em;
private MyRepository repository;
@Autowired
public MyDataServiceImpl(MyRepository repository) {
super(repository);
this.repository = repository;
}
public MyObject findById(String id) {
P persitentObject = repository.findOne(id);
//Calls to map what persitentObject holds to MyObject and returns a MyObject
}
}
此处MyRepository的代码只是为了显示它是一个扩展CrudRepository的空接口
public interface MyRepository extends CrudRepository<MyObjectPO, String>, JpaSpecificationExecutor<MyObjectPO> {
}
推荐答案
首先我要说的是,通过使用构造函数注入而不是字段注入(这使得使用模拟编写测试要简单得多),您走上了正确的道路。
public class MyServiceImplTest
{
private MyDataService myDataService;
private NyService myService;
@Mock
private MyRepository myRepository;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this); // this is needed for inititalizytion of mocks, if you use @Mock
myDataService = new MyDataServiceImpl(myRepository);
myService = new MyServiceImpl(myDataService);
}
@Test
public void getById_ValidId() {
doReturn(someMockData).when(myRepository).findOne("1");
MyObject myObject = myService.getById("1");
//Whatever asserts need to be done on the object myObject
}
}
从您的服务–>dataService–>开始调用。但只模拟您的存储库调用。
通过这种方式,您可以控制和测试类的所有其他部分(包括服务和数据服务),并且只模拟存储库调用。
这篇关于单元测试如何使用Mockito模拟存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。