简体   繁体   中英

How to inject a mocked object inside mock of another mocked object in Java?

I have below classes. DataServices object is used in both ProductImpl and Mapper. But its mock is available in ProductImpl but not in Mapper class. I do not what needs to be done so that mocked of DataServices is Available in Mapper class too.

class ProductImpl{
    @Inject private DataServices ds;
    @Inject private Mapper mapper;

    public void call(){
      ds.get(); //ds is not null here
      mapper.map();
     // some code
    }
   }



abstact class Mapper{

        @Inject private DataServices ds;

        public void map(){
            ds.get()// ds is null here
            //some code
        }
    }

I have test class below

class Test{

    @Mock private DataServices ds;
    @Mock private Mapper mapper;
    @InjectMocks private ProductImpl impl;

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

    @Test
    public void test(){
       impl.call();
    }
}

如果我理解正确,您不需要在 Mapper 中进行另一个模拟,因为您已经模拟了映射器类,并且 map 方法也是无效的,尽管如果一个方法返回了一些东西,您可以轻松地使用when提供您在测试中需要的行为。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM