无法使用 java 类实例化名为异常的 @InjectMocks 字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23086932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:36:23  来源:igfitidea点击:

Cannot instantiate @InjectMocks field named exception with java class

javamockitojunit4

提问by Patan

I have a class with user defined constructor.

我有一个带有用户定义构造函数的类。

public class Employee   
{
    @Inject
    private MyBean myBean;

    private String abcd;    

    protected Employee(Parameter1 param1, Parameter2 param2)
    { //some operations on method params
    //some operation on mybean
      this.abcd = "some value";
    }

    protected String getAbcd()
    {
        return nrOfAccesses;
    }

    protected void setAbcd(String abcd)
    {
        this.abcd = abcd;
    }

}

Test class

测试班

@RunWith(MockitoJUnitRunner.class)
public class TestEmployee
{


    @Mock
    private MyBean myBean;

    private Parameter1 param1;
    private Parameter2 param2;

    @InjectMocks
    private Employee employee;


    @Before
    public void prepare()
        throws Exception
    {
        //some intialization
        param1 = some value;
        param2 = some value;            
        when(myBean.get(eq("ID"))).thenReturn("1075");

    }

    @Test
    public void testEmployeeID()
    {
        employee = new Employee(param1, param2);
        assertThat(employee.getAbcd(), is("XYZC"));        
    }

I am getting exception as

我得到了例外

org.mockito.exceptions.base.MockitoException: 
Cannot instantiate @InjectMocks field named 'employee' of type 'class com.xyz.Employee'.
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

    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.withBefores(JUnit45AndHigherRunnerImpl.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:254)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access
@InjectMocks
ClassUnderTest cut;

@Mock
Dependency1 dep1;
@Mock
Dependency2 dep2;

@Before
public void setup() {
  initMocks(this);
}
0(ParentRunner.java:53) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: java.lang.NullPointerException

回答by Max Fichtelmann

if you do a employee = new Employee(param1, param2);you may as well skip @InjectMocks.

如果你做一个employee = new Employee(param1, param2);你也可以跳过@InjectMocks

It is supposed to do the following:

它应该执行以下操作:

ClassUnderTest cut;

@Mock
Dependency1 dep1;
@Mock
Dependency2 dep2;

@Before
public void setup() {
  initMocks(this);
  cut = new ClassUnderTest(dep1, dep2);
}

omitting @InjectMocksthe same behaviour can be achieved with the following code:

@InjectMocks可以使用以下代码实现省略相同的行为:

    @ExtendWith(SpringExtension.class)
    @SpringBootTest
    public class MyServiceTest {

        MyService myService;

        @Autowired
        DependentObject dependentObject;

        @BeforeEach
        void setup() {
            myService = new MyService(dependentObject);
        }

In your specific case, you should mock param1and param2. Never call the constructor manually when using @InjectMocks.

在您的特定情况下,您应该模拟param1param2. 使用时切勿手动调用构造函数@InjectMocks

回答by CCC

To test a service class with dependency objects, you can do the following:

要使用依赖对象测试服务类,您可以执行以下操作:

  • Put @ExtendWith(SpringExtension.class) annotation on your test class instead of @ExtendWith(MockitoExtension.class).
  • Put @SpringBootTest on your test class
  • Put @Autowired annotation on any dependent objects instead of @Mock.
  • 将 @ExtendWith(SpringExtension.class) 注释放在您的测试类上,而不是 @ExtendWith(MockitoExtension.class)。
  • 将 @SpringBootTest 放在您的测试类上
  • 将@Autowired 注释放在任何依赖对象而不是@Mock 上。

Test class:

测试类:

     @Service
     public class MyService {

            private DependentObject dependentObject;

            public MyService(DependentObject dependentObject) {}
    }

Service class:

服务等级:

##代码##