简体   繁体   English

抽象父 class 中的 Mocking 依赖项

[英]Mocking dependency inside abstract parent class

I have the following set of classes:我有以下一组课程:

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
    }
}

Trying to test the Child class:尝试测试子 class:

@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();
    }
}

The matter is that I'm always getting a NullPointerException because the parent dependency (SomeService) is always null.问题是我总是收到 NullPointerException,因为父依赖项(SomeService)总是 null。

Also tried:也试过:

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

And using Spy, without any success.并且使用 Spy,没有任何成功。

Thanks for your hints.感谢您的提示。

One option is using ReflectionTestUtils class to inject the mock.一种选择是使用 ReflectionTestUtils class 来注入模拟。 In the code bellow I've executed the unit tests with JUnit 4.在下面的代码中,我使用 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());
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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