我已经编写了这段代码:
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)
)
);
还有编写这种代码的更优雅的方式吗?
答案 0 :(得分:1)
您可以使用模仿注释为您完成此操作:
@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
实现执行测试,在这种情况下为模拟运行器,它初始化所有带注释的字段@Mock
表示您要模拟所说的对象,就像Mockito.mock(SomeClass.class)
@InjectMocks
表示您希望将所有声明的@Mock
注入到带注释的字段中,因此它仅使用给定的参数调用构造函数。我还认为您不需要spy
来测试您的服务。如果您仍然需要它,则可以在@Spy
注释后的之后使用@InjectMocks
注释