模拟和注入继承字段

use*_*542 2 java inheritance junit unit-testing mockito

我在继承和编写单元测试方面遇到问题。当我想测试的类继承该字段时,我不知道如何将模拟注入为字段。请注意,我无法存根任何内容,因为测试类是额外的测试包。我只想让myService.getSomething()-call 正常工作。

    public class A{
    @Autowired
    private Service myService;

    protected void doSomething(){
        //
        someValue = myService.getSomething();
    }
Run Code Online (Sandbox Code Playgroud)

还有B类,它继承了以下方法:

    public class B extends A{
        public void someMethod(){
            doSomething();
        }
    }
Run Code Online (Sandbox Code Playgroud)

这将是我的测试类:

public class TestB{
        @Mock
        private Service myService;

        @InjectMocks
        private B classUnderTest = new B();

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

        @Test
        public void testSomeMethod(){
            SomeValue someValue = new SomeValue();
            doReturn(someValue).when(myService).getSomething();

            classUnderTest.doSomething();
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。

小智 6

一种可能的方法是使用 java 反射在运行时设置/更改字段:

    Field parentService = classUnderTest.getClass().getSuperclass().getDeclaredField("myService");
    parentService.setAccessible(true);
    parentService.set(classUnderTest, myService_mock);
Run Code Online (Sandbox Code Playgroud)

也在寻找解决方案,这对我有用。

参考:/sf/answers/2228274401/