java - 使用 Mockito 和 Junit 时如何自动连接 spring bean?

标签 java spring junit mockito autowired

我正在尝试设置要在 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/

相关文章:

java - 如何确定碰撞发生在哪一侧?

java - 如何识别没有 style 属性的 <li> 标签?

spring - 混合 html 和 json 模板时如何在 thymeleaf 中正确设置内容类型

java - 当 TrustManagerFactory 不是 TrustManagerFactory (Java)

java - 如何在 Java 中使用 jmockit 模拟静态链式方法

java - 使用自签名证书时 Tomcat 服务器未发生 SSL/TLS 通信

java - UTFDataFormatException : malformed input UTF Format

spring - @Cacheable 无法更新

java - JAX-WS Web 服务内部的 EJB 对象空指针异常

java - JUnit 测试中的假设与断言