我正在尝试设置要在Junit
中使用的类。
但是,当我尝试执行以下操作时,出现错误。
当前测试类别:
public class PersonServiceTest {
@Autowired
@InjectMocks
PersonService personService;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
assertThat(PersonService, notNullValue());
}
//tests
错误:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'personService'
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null
我怎样才能解决这个问题?
最佳答案
您没有在代码中 mock 任何东西。 @InjectMocks设置一个将注入(inject)模拟的类。
您的代码应如下所示
public class PersonServiceTest {
@InjectMocks
PersonService personService;
@Mock
MockedClass myMock;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
Mockito.doReturn("Whatever you want returned").when(myMock).mockMethod;
}
@Test()
public void testPerson() {
assertThat(personService.method, "what you expect");
}