1

以下是测试代码:

package a.b.c.concurrent.locks;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.when;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

import mockit.Mocked;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestLockConcludesProperly {

    private static LockProxy lockProxy;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        Logger.getRootLogger().addAppender(new ConsoleAppender(new PatternLayout()));
    }

    @Test
    public void testAquireLockInFirstIteration(@Mocked Lock mockLock) throws Exception {

        when(mockLock.tryLock(anyLong(), any(TimeUnit.class))).thenReturn(true);

        lockProxy = new LockProxy(mockLock, 2, TimeUnit.MILLISECONDS);

        lockProxy.lock();

    }
}

我得到并且无法弄清楚的错误,虽然它可能是我的一些错误配置,是:

Tests in error: 
  testAquireLockInFirstIteration(a.b.c.concurrent.locks.TestLockConcludesProperly): 
Misplaced argument matcher detected here:

-> at a.b.c.concurrent.locks.TestLockConcludesProperly.testAquireLockInFirstIteration(TestLockConcludesProperly.java:34)
-> at a.b.c.concurrent.locks.TestLockConcludesProperly.testAquireLockInFirstIteration(TestLockConcludesProperly.java:34)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().

我究竟做错了什么?

4

1 回答 1

2

我的错...

好像我混淆了 JMockit API 和 Mockito 的 API。

为了模拟Lock界面,我需要做的就是:

    @Test
    public void testAquireLockInFirstIteration() throws Exception {

        Lock mockLock = Mockito.mock(Lock.class);
        when(mockLock.tryLock(anyLong(), any(TimeUnit.class))).thenReturn(true);

        lockProxy = new LockProxy(mockLock, 2, TimeUnit.MILLISECONDS);

        lockProxy.lock();

    }
于 2012-11-25T16:00:24.970 回答