我有以下服务:
@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.
}
}
当我在 Debug模式下运行此测试时,我看到 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
@InjectMocks
protected ClientService clientService = new ClientServiceImpl();
这应该创建一个名为 clientService 的 Autowiring 的 ClientService 并注入(inject)模拟。但是 = new ClientServiceImpl()
将覆盖 Autowiring 并为您创建一个普通的 Autowiring (我认为!)。此外,也不需要同时使用 @Autowired
和 @InjectMocks
- 您想要创建一个注入(inject)模拟的服务 - 而不是 Autowiring 的对象。
你能尝试像这样改变你的测试吗:
@RunWith(MockitoJUnitRunner.class)
public class ClientControllerTest extends ApiWebTest {
@Mock
protected ContractService contractService;
@InjectMocks
protected ClientService clientService;
@Test
private void testGetInfo() {
DocumentInfo multipartFile = new DocumentInfo();
multipartFile.setMultipartFileId(1234);
when(this.contractService.getInfo(multipartFile)).thenReturn(multipartFile);
}
}
添加 @RunWith(MockitoJUnitRunner.class)
意味着所有对象的创建都在不需要您做任何进一步工作的情况下发生。
关于java - 在另一个服务 Junit 中模拟一个服务的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46292928/