简体   繁体   中英

Mockito can't instantiate the class under test

I've got three classes A , B and C :

public class A {
  @Autowired
  private B someB;
  private C someC = someB.getSomeC();
}

@Service
public class B {
  C getSomeC() {
    return new C();
  }
}

public class C { }

Now if I write a unit test for A which looks like:

@RunWith(MockitoJUnitRunner.class)
public class ATest {

  @InjectMocks
  private A classUnderTest;

  @Mock
  private B someB;

  @Mock
  private C someC;

  @Test
  public void testSomething() {

  }
}

Mockito is not happy with this:

 org.mockito.exceptions.base.MockitoException: 
    Cannot instantiate @InjectMocks field named 'classUnderTest' of type 'class my.package.A'.
    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

If I remove the call in class A , such that class A looks like the following:

public class A {
  private B someB;
  private C someC;
}

, Mockito is able to instantiate the classUnderTest and the test runs through.

Why is this the case?

edit : Using Mockito 1.9.5

Well this is always going to fail:

public class A {
  private B someB;
  private C someC = someB.getSomeC();
}

You're trying to call getSomeC() on a value which will always be null... that will always thrown NullPointerException . You need to fix A to handle the dependencies better. (Personally I'd take them as constructor parameters, but there are other options of course...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM