@Transactional(propagation = Propagation.REQUIRED)
public void exe() {
try {
Reserve reserveInfo = newTransactionTemplate.execute(new TransactionCallback<Reserve>() {
@Override
public Reserve doInTransaction(TransactionStatus status) {
return reserveService.callReserve(reserveDetails);
}
});
if(reserveInfo != null && reserveInfo.getStatus()=="DONE") {
someOtherService.doSomething();
}
} finally {
if(reserveInfo!= null && reserveInfo.getStatus().equals("DONE")){
final String id = reserveInfo.getId();
Release releaseInfo = newTransactionTemplate.execute(new TransactionCallback<Release>() {
@Override
public Release doInTransaction(TransactionStatus status) {
return reserveService.callRelease(id);
}
});
if (releaseInfo.getStatus() != "RELEASED") {
throw new RuntimeException("Problem in releaseing");
}
}
}
}
这是我想要测试的示例代码。在网络上找不到关于测试匿名类的太多信息。
我想测试exe()方法,通过newTransactionTemplate.execute方法并模拟调用reserveService.callReserve(reserveDetails)。
请问有人可以建议如何测试这种情况吗?
以下是我正在尝试测试的示例: private SomeService someService = null;
@Mock
private ReserveService mockReserveService;
@Mock
private ReleaseService mockReleaseService;
@Mock
private TransactionTemplate mockTransactionTemplate;
@Mock
private SomeOtherService mockSomeOtherService;
@BeforeMethod
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
someService = new SomeService();
someService.setReserveService(mockReserveService);
someService.setReleaseService(mockReleaseService);
someService.setSomeOtherService(mockSomeOtherService);
someService.setNewTransactionTemplate(mockTransactionTemplate);
}
@Test(enabled=true)
public void exeHappyPath() {
Reserve reserveInfo = new Reserve();
reserveInfo.setId("123");
reserveInfo.setStatus("DONE");
Release releaseInfo = new Release();
releaseInfo.setStatus("RELEASED");
when(mockReserveService.callReserve(Mockito.any(ReserveDetails.class))).thenReturn(reserveInfo);
when(mockReserveService.callRelease(reserveInfo.getId())).thenReturn(releaseInfo);
when(mockTransactionTemplate.execute(Mockito.<TransactionCallback<Reserve>>any())).thenReturn(reserveInfo);
when(mockTransactionTemplate.execute(Mockito.<TransactionCallback<ReleaseInfo>>any())).thenReturn(releaseInfo);
//Call the exe method
someService.exe();
verify(mockReserveService, times(1)).callReserve(Mockito.any(ReserveDetails.class));
verify(mockReserveService, times(1)).callRelease(reserveInfo.getId()));
verify(mockSomeOtherService, times(1)).doSomthing());
}
第二次调用 when(mockTransactionTemplate.execute...) 返回对象 releaseInfo 时抛出了 java.lang.ClassCastException 异常。
when(transactionTemplate.execute(Mockito.<TransactionCallback>any())).thenAnswer((Answer) invocation -> { final TransactionCallback txCallback = (TransactionCallback) invocation.getArguments()[0]; return txCallback.doInTransaction(new SimpleTransactionStatus()); });
- Vijay Nandwana