![](/img/trans.png)
[英]How to mock an ObservableTransformer in unit tests using Mockito
[英]Unit Tests How to Mock Repository Using Mockito
我在存根我的存储库时遇到问题。 有人建议我创建另一个 application.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) 时它会抛出异常。 这就是我试图模拟的内容,但是存储库给了我问题。
@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 开始。 但只有你的存储库调用被模拟。
通过这种方式,您可以控制和测试类的所有其他部分(服务和数据服务)并仅模拟存储库调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.