使用 Mockito 和 Junit 时如何 AutoWire spring beans?

jav*_*999 6 java junit spring mockito autowired

我正在尝试将我的课程设置为在Junit.

但是,当我尝试执行以下操作时,出现错误。

当前测试类:

public class PersonServiceTest {

    @Autowired
    @InjectMocks
    PersonService personService;

    @Before
    public void setUp() throws Exception
    {
        MockitoAnnotations.initMocks(this);
        assertThat(PersonService, notNullValue());

    }

    //tests
Run Code Online (Sandbox Code Playgroud)

错误:

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

小智 5

您没有嘲笑代码​​中的任何内容。@InjectMocks 设置一个将注入模拟的类。

你的代码应该是这样的

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");
      }
Run Code Online (Sandbox Code Playgroud)