"mvn test"没有执行@Mock注解的方法
"mvn test" did not execute @Mock annotated method
我有一个测试 class 看起来像这样:
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class SomeTest {
@Mock
Object someObj;
@Before
public void before() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testNullPointer() {
Mockito.when(someObj.toString()).thenReturn("1");
}
}
当我在这个项目的根目录下运行mvn clean test
时,说testcase触发了NullPointerException
,stack tree显示someObj
为null。
我正在使用 org.mockito::mockito-core::4.0.0
和 junit::junit::4.13.0
.
似乎没有执行 before() 方法。任何想法为什么?提前谢谢。
您的 class 上缺少注释:
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
...
}
当 运行 这个测试时,你会在堆栈跟踪上方得到这个错误:
testNullPointer(org.example.SomeTest) Time elapsed: 0.368 sec <<< ERROR!
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
这里有趣的部分是第一个项目符号 - 您不能对 hashCode
方法进行存根。如果你用一些可以存根的方法替换它,测试就会通过。例如:
Mockito.when(someObj.toString()).thenReturn("yay!");
我有一个测试 class 看起来像这样:
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class SomeTest {
@Mock
Object someObj;
@Before
public void before() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testNullPointer() {
Mockito.when(someObj.toString()).thenReturn("1");
}
}
当我在这个项目的根目录下运行mvn clean test
时,说testcase触发了NullPointerException
,stack tree显示someObj
为null。
我正在使用 org.mockito::mockito-core::4.0.0
和 junit::junit::4.13.0
.
似乎没有执行 before() 方法。任何想法为什么?提前谢谢。
您的 class 上缺少注释:
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
...
}
当 运行 这个测试时,你会在堆栈跟踪上方得到这个错误:
testNullPointer(org.example.SomeTest) Time elapsed: 0.368 sec <<< ERROR!
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
这里有趣的部分是第一个项目符号 - 您不能对 hashCode
方法进行存根。如果你用一些可以存根的方法替换它,测试就会通过。例如:
Mockito.when(someObj.toString()).thenReturn("yay!");