我想测试的方法有一个for循环,其中包含bList中每个元素的逻辑:
class A {
void someMethod(){
for(B b: bList){
//some logic for b
}
}
}
Run Code Online (Sandbox Code Playgroud)
执行以下测试时出现异常:
@RunWith(MockitoJUnitRunner.class)
class ATest {
@Mock
private B b;
@Mock
private Map<Int, List<B>> bMap;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private List<B> bList;
@Spy
@InjectMocks
private C c;
....
@Test
public void test(){
//this line executes fine
when(bList.size()).thenReturn(1);
//strangely this works fine
when(bMap.get(any())).thenReturn(bList);
//ClassCastException
when(bList.get(0)).thenReturn(b); // or when(bList.get(anyInt())).thenReturn(b);
c.methodIWantToTest();
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的例外是:
java.lang.ClassCastException:
org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$ cannot be cast to xyz.BRun Code Online (Sandbox Code Playgroud)
有没有人遇到过这个并提出解决方法?
我搜索了一个解决方案并遇到了一些链接:http://code.google.com/p/mockito/issues/detail?id = 251 …
我有一个如下代码块:
@Service
ExecutorService {
@Autowired
IAccountService accountService;
@Retryable(maxAttempts = 3, value = {DataIntegrityViolationException.class}, backoff = @Backoff(delay = 1000, multiplier = 2))
public void execute(RequestDto reqDto)
{
Account acc = accountService.getAccount(reqDto.getAccountId);
...
}
}
Run Code Online (Sandbox Code Playgroud)
在 Mockito 测试中,我只想按预期看到调用方法 3 次。
@RunWith(SpringRunner.class)
public class CampaignExecuterServiceTest
{
private static final Long ACCOUNT_ID = 1L;
@InjectMocks
private ExecutorService executorService;
@Mock
private IAccountService accountService;
@Test
public void execute_success()
{
Account account = new Account(ACCOUNT_ID, null, null, null, null);
RequestDto reqDto = new RequestDto();
when(accountService.getAccount(any())).thenThrow(DataIntegrityViolationException.class);
executorService.execute(reqDto);
verify(executorService, …Run Code Online (Sandbox Code Playgroud)