【发布时间】:2017-09-19 06:02:05
【问题描述】:
我有以下服务:
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
protected ContractService contractService;
private void saveInCache(MultipartFile multipartFile) {
this.contractService.saveInCache(multipartFile);
}
}
和另一个服务
@Service
public class ClientServiceImpl implements ClientService {
@Autowired
protected ContractService contractService;
private void getInfoOfFile(String multipartFileId) {
DocumentInfo document = this.contractService.getInfo(multipartFileId);
///
}
}
我有我的 Junit
public class ClientControllerTest extends ApiWebTest {
@Mock
protected ContractService contractService;
@Autowired
@InjectMocks
protected ClientService clientService = new ClientServiceImpl();
@Before
private void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
private void testGetInfo() {
// Code
DocumentInfo multipartFile = new DocumentInfo();
multipartFile.setMultipartFileId(1234);
when(this.contractService.getInfo(multipartFile.getMultipartFileId())).thenReturn(multipartFile);
// Test the Client service 'getInfoOfFile' method.
}
}
当我在调试模式下运行此测试时,我看到 this.contractService.getInfo(multipartFileId); 正在返回“null”。
我在嘲笑中哪里出错了。
我刚刚在我的 JUnit 中模拟了 ContractService。我还需要模拟 AccountServiceImpl 吗?
编辑:添加 saveInCache 和 getInfo 方法
private DocumentInfo getInfo(String documentId) {
if (StringUtils.isEmpty(documentId)) {
return null;
}
WriteLock lock = this.readWriteLock.writeLock();
try {
lock.lock();
DocumentInfo cachedDocument = this.documentCache.get(documentId);
return cachedDocument;
} finally {
if (lock != null) {
lock.unlock();
}
}
}
private DocumentInfo saveInCache(StreamingStorage document) {
if (document == null) {
throw new InvalidParameterException("Creative document is required to put into cache.");
}
WriteLock lock = this.readWriteLock.writeLock();
try {
lock.lock();
DocumentInfo newCachedDocument = this.documentCache.put(document.getDocumentId(), document);
return newCachedDocument;
} finally {
if (lock != null) {
lock.unlock();
}
}
}
【问题讨论】:
-
对于受保护的 ClientService 客户端服务,您不需要 @Autowired;也代替受保护的ClientService clientService;尝试使用 - private ClientServiceImpl clientService
-
ContractService 的 getInfo 也不可见。你能添加那个方法吗?
-
@asg 添加了方法
-
整个过程会简单很多,如果你在你的服务中使用构造器注入,你可以完全消除Spring。
-
当您告诉 Mockito 期望
DocumentInfo对象用于getInfo()方法时,您的 Test 类中是否存在编译问题,但实际上它接受String?在这行代码when(this.contractService.getInfo(multipartFile)).thenReturn(multipartFile)