1

I am new to unit testing in spring boot. I am trying to test a service and have used Mockito for it. When I do mvc.perform() I get a null value. I have used when() to specify what to return. But not sure why it fails. Please provide some valuable inputs. Here are fe snippets:

@Test
public void testAll() throws Exception {

    /*Mockito.when(sensorDao.findAll()).thenReturn((Iterable<Sensor>) s2);
    assertEquals(200,expect().statusCode(200));*/

    Collection<Sensor>list =  getEntityListStubData();
    when(sensorserviceimpl.findAll()).thenReturn(list);
    when(sensorService.findAll()).thenReturn(list);
    when(sensorDao.findAll()).thenReturn(list);
    String uri="/sensor";
    //System.out.print("gfnjhkjjhhg");
    System.out.println("Helllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllloooooooooooooooooooooooooooooooooooooooooooo");
    System.out.println(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON));
    MvcResult result = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)).andReturn();
    String content = result.getResponse().getContentAsString();
    int status = result.getResponse().getStatus();
 }

Here is the output:

2017-08-18 19:11:45.030  INFO 21424 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@35083305 testClass = SensorServiceStandaloneApplicationTests, testInstance = com.bny.sr.sensorservicestandalone.SensorServiceStandaloneApplicationTests@482cd91f, testMethod = testAll@SensorServiceStandaloneApplicationTests, testException = java.lang.NullPointerException, mergedContextConfiguration = [WebMergedContextConfiguration@8e0379d testClass = SensorServiceStandaloneApplicationTests, locations = '{}', classes = '{class com.bny.sr.sensorservicestandalone.SensorServiceStandaloneApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{eureka.client.enabled:false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@167fdd33, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@53f65459, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@74650e52, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@80503], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].

java.lang.NullPointerException
    at com.bny.sr.sensorservicestandalone.SensorServiceStandaloneApplicationTests.testAll(SensorServiceStandaloneApplicationTests.java:163)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

2017-08-18 19:11:45.046  INFO 21424 --- [       Thread-5] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5386659f: startup date [Fri Aug 18 19:11:34 IST 2017]; root of context hierarchy
2017-08-18 19:11:45.054  INFO 21424 --- [       Thread-5] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

Process finished with exit code -1

Here is the debug result:

Debug results

2 Answers 2

5

Since spring-boot 1.4.0 you can use @WebMvcTest which will auto-configure MockMvc. Also, use @MockBean to mock any dependency in your controller.

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private SensorDao sensorDao;

}
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer gave a proper direction for me. @AutoConfigureMockMvc worked for me finally. The MockMvc requires to be auto configured. Thank You very much. :-)
this is true for me also.
1

@AutoConfigureMockMvc, will also do the trick

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.