junit错误:cannotstubvoidmethodwithreturnvalue-test在一起运行时失败,但单独通过

jmo0nnb3  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(479)

我试着为我的测试用例模仿entitymanager。当单独运行时,测试通过,但作为一个批处理,当我执行整个测试类时,它失败。
以下是测试设置:

@RunWith(MockitoJUnitRunner.class)
public class CSImplTest {

    @InjectMocks
    final static CSImpl cs;
    final static CR cr;
    final static BS bs;

    static {
        cr= mock(CR.class);
        bs= mock(BS.class);

        cs= new CSImpl(cr,br);
        cs.entityManager=mock(EntityManager.class);
    }

@Mock
private EntityManager entityManager;

以及引起问题的线路:

doNothing().when(entityManager).detach(any());

并在堆栈跟踪下方添加:

org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue: 
'detach' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
    doThrow(exception).when(mock).someVoidMethod();
If you need to set the void method to do nothing you can use:
    doNothing().when(mock).someVoidMethod();
For more information, check out the javadocs for Mockito.doNothing().

***

If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. The method you are trying to stub is *overloaded*. Make sure you are calling the right overloaded version.
2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not verify/stub final methods.
3. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
4. Mocking methods declared on non-public parent classes is not supported.

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题