我正在尝试设置要在 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
我该如何解决这个问题?
最佳答案
您没有在代码中模拟任何内容。 @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");
}
关于java - 使用 Mockito 和 Junit 时如何自动连接 spring bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37053048/