【问题标题】:Mocking dependency inside abstract parent class在抽象父类中模拟依赖
【发布时间】:2022-01-28 09:58:47
【问题描述】:

我有以下一组类:

public abstract class ParentClass {

    @Autowired
    private SomeService service;

    protected Item getItem() {
        return service.foo();
    }

    protected abstract doSomething();

}

@Component
public ChildClass extends ParentClass {
    private final SomeOtherService someOtherService;

    @Override
    protected doSomething() {
        Item item = getItem(); //invoking parent class method
        .... do some stuff
    }
}

尝试测试 Child 类:

@RunWith(MockitoJUnitRunner.class)
public class ChildClassTest {

    @Mock
    private SomeOtherService somerOtherService;

    @Mock
    private SomerService someService; //dependency at parent class

    @InjectMocks
    private ChildClass childClass;

    public void testDoSomethingMethod() {
         Item item = new Item();
         when(someService.getItem()).thenReturn(item);
         childClass.doSomething();
    }
}

问题是我总是收到 NullPointerException,因为父依赖项 (SomeService) 始终为空。

也试过了:

Mockito.doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
        return new Item();
    }
}).when(someService).getItem();

并且使用 Spy,没有任何成功。

感谢您的提示。

【问题讨论】:

    标签: java unit-testing junit mockito


    【解决方案1】:

    一种选择是使用 ReflectionTestUtils 类来注入模拟。在下面的代码中,我使用 JUnit 4 执行了单元测试。

    @RunWith(MockitoJUnitRunner.class)
    public class ChildClassTest {
    
    @Mock
    private SomeService someService;
    
    @Test
    public void test_something() {
        ChildClass childClass = new ChildClass();       
        ReflectionTestUtils.setField(childClass, "service", someService);
        
        when(someService.foo()).thenReturn("Test Foo");
        
        assertEquals("Child Test Foo", childClass.doSomething());
    }
    

    }

    【讨论】:

    • 是的,只是使用了相同的方法,它可以工作。
    猜你喜欢
    • 2019-12-04
    • 1970-01-01
    • 2011-05-13
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    相关资源
    最近更新 更多