模拟自动通用接口

时间:2017-04-24 15:01:59

标签: java spring junit mocking mockito

我正在尝试使用itemRepository模拟自动连接的接口@MockBean,但是当测试执行NullPointerExcepption方法itemRepository.findAll()时,我有一个ResourceController.listAll() 1}}。在调用resourceControler.listAll()之前的测试中,我的模拟itemRepository被正确创建,但在listAll()内,模拟未被引用。

您是否知道如何模拟这种自动通用的通用接口?

测试listAll()的方法:

    public abstract class ResourceController<T extends RESTResource<T>> extends MainController {

        @Autowired
        protected RESTRepository<T> itemRepository;

        public Page<T> listAll(T search, Pageable pageable) {
            return itemRepository.findAll(search, pageable);
        }
    }

通用界面:

    @NoRepositoryBean
    public interface RESTRepository<T> extends PagingAndSortingRepository<T, 
    String>, JpaSpecificationExecutor<T> {

    }

FindAll()方法是Spring SimpleJpaRepository实现的公共方法。我无法删除注释@NoRepositoryBean,但即使删除,模拟仍为null。

测试:

    @RunWith(SpringRunner.class)
    @ContextConfiguration
    public class ResourceControllerTest {



        @MockBean(classes = ResourceController.class, answer = CALLS_REAL_METHODS)
        private  ResourceController ressourceControler;

        @MockBean(classes = RESTResource.class)
        private  RESTResource search;

        @MockBean
        protected RESTRepository itemRepository;

        @MockBean
        private Pageable pageable;

        @Before
        public void initMocks(){
            MockitoAnnotations.initMocks(this);
        }


        @Test
        public void testListAll() throws Exception {

            // Given
            Page page = new PageImpl(new ArrayList());

            when(itemRepository.findAll(search, pageable)).thenReturn(page);

            // When
            Object obj = ressourceControler.listAll(search, pageable);

            //Then
                    ...
        }

0 个答案:

没有答案