Mockito注入嵌套豆

Raf*_*fał 2 java junit spring dependency-injection mockito

我对Mockito并不陌生,但是这次我在工作中发现了一个有趣的案例。希望您能帮助我。

我需要注入模拟以更改测试过程中的某些方法行为。问题是,bean结构是嵌套的,并且此bean位于其他bean内部,无法通过测试方法访问。我的代码如下所示:

@Component
class TestedService { 
  @Autowired
  NestedService nestedService;
}

@Component
class NestedService {
  @Autowired
  MoreNestedService moreNestedService;
}

@Component
class MoreNestedService {
  @Autowired
  NestedDao nestedDao;
}

@Component
class NestedDao {
  public int method(){
    //typical dao method, details omitted
  };
}
Run Code Online (Sandbox Code Playgroud)

因此,在我的测试中,我希望调用NestedDao.method返回模拟的答案。

class Test { 
  @Mock
  NestedDao nestedDao;

  @InjectMocks
  TestedService testedSevice;

  @Test
  void test() {
    Mockito.when(nestedDao.method()).thenReturn(1);
    //data preparation omitted
    testedSevice.callNestedServiceThatCallsNestedDaoMethod();
    //assertions omitted
  }
}
Run Code Online (Sandbox Code Playgroud)

我试图做一个initMocks:

@BeforeMethod
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}
Run Code Online (Sandbox Code Playgroud)

还要在我的测试类上添加注释:

@RunWith(MockitoJUnitRunner.class)
Run Code Online (Sandbox Code Playgroud)

总是从方法获取空指针或错误答案(未模拟)。

我想这是嵌套调用错误,因此无法模拟此Dao。我也读过@InjectMocks只适用于setter或构造函数注入,这是我想念的(在私有字段上只是@Autowire),但是当我尝试时它没有起作用。

你猜我在想什么吗?;)

小智 5

您可以使用@MockBean代替@Mock和@InjectionMock。

@RunWith(SpringRunner.class)
@SpringBootTest
class Test { 
  @MockBean
  NestedDao nestedDao;

  @Autowired
  TestedService testedSevice;

  @Test
  void test() {
    Mockito.when(nestedDao.method()).thenReturn(1);
    //data preparation omitted
    testedSevice.callNestedServiceThatCallsNestedDaoMethod();
    //assertions omitted
  }
}
Run Code Online (Sandbox Code Playgroud)