我写了这段代码:
BackOfficeProperties backOfficeProperties = Mockito.mock(BackOfficeProperties.class);
Mockito
.when(backOfficeProperties.getUrlFrontOffice())
.thenReturn("http://some.valid.url");
this.auditService = Mockito.spy(
new AuditService(
backOfficeProperties,
Mockito.mock(AuditFactory.class),
Mockito.mock(AuditDao.class),
Mockito.mock(RedisDao.class),
Mockito.mock(ObjectMapper.class),
Mockito.mock(I18nResourceBundleMessageSource.class)
)
);
有没有更优雅的方法来编写这段代码?
您可以使用 mockito 注释为您执行此操作:
@RunWith(MockitoJunitRunner.class)
public class AuditServiceTest {
@Mock
private BackOfficeProperties backOfficeProperties;
@Mock
private AuditFactory auditFactory;
@Mock
private AuditDao auditDao;
@Mock
private RedisDao redisDao;
@Mock
private ObjectMapper objectMapper;
@Mock
private I18nResourceBundleMessageSource i18nResourceBundleMessageSource;
@InjectMocks
private AuditService auditService;
@Before
public void setup(){
Mockito
.when(backOfficeProperties.getUrlFrontOffice())
.thenReturn("http://some.valid.url");
}
// your tests
}
一些解释:
-
@RunWith(MockitoJunitRunner.class)
使用给定的Runner
实现执行测试,在本例中为 mockito 运行器,它初始化所有带注释的字段 -
@Mock
表示你想模拟所述对象,就像Mockito.mock(SomeClass.class)
-
@InjectMocks
表示您希望将声明的所有@Mock
注入到带注释的字段中,因此它只是使用给定参数调用构造函数。
我还认为您不需要spy
要测试的服务。如果您仍然需要它,您可以在@InjectMocks
注释之后使用 @Spy
注释