JMockit:在模拟界面时“在这里检测到错误的参数匹配器”

时间:2012-11-25 15:12:08

标签: java unit-testing mockito jmockit

以下是测试代码:

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().

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我的不好......

好像我混淆了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();

    }