Mockito测试 - 注入自动服务



我正在尝试对Sprint启动服务(服务A)进行单位,该启动服务(服务A)已将另一个服务(服务b)自动为

@Autowired
ServiceB serviceB;

单位测试的声明看起来如下:

@Mock
private UserRepository userRepository;
@Mock
private ServiceA serviceA;
@InjectMocks
@Autowired
private ServiceB serviceB;
private User user;

这将失败

Mockito.when(userRepository.save(any(User.class))).thenReturn(user);
User result = serviceA.upsertUser(user);

servicea upsertUser()方法看起来像

user = serviceB.doUpsertUser(user);

测试工作正常,然后我从

中切换用户声明servicea new
user = new ServiceB(userRepository).doUpsertUser(user);

@Autowired

user = SeviceB.doUpsertUser(user);

我不确定我是否弄乱了创建模拟并以适当的方式注入模拟,因为我在servicea升入Servicea时没有声明ServiceB。

我已经解决了我的问题以下步骤,从https://tedvinke.wordpress.com/2014/02/13/mockito-why-why-why-why-you-should-not-should-not-should-not-should-not-iase-injectmocks-angectmocks-annotation-to-autowire-field/用于更改ServiceAServiceB,但没有@InjectMocks

就无法离开

我的调整后的摩根托测试看起来像:

@Mock
private UserRepository userRepository;
@InjectMocks
private ServiceB serviceB;
private User user;
private ServiceA serviceA;
@Before
public void setUp() {
    this.serviceA = new ServiceA(userRepository, serviceB);
}
@Test
....

相关内容

  • 没有找到相关文章

最新更新