How to make Junit test in spring boot

Fadi

I want to test the behaviour of my rest controller methods, using Mockito.test.

I have the following controller class

    @RestController
    @RequestMapping("/project/image")
    public class ImageController {
        @Autowired
        ImgService imageService;    
    
    
        @GetMapping("/getImage/{id}")
    public ResponseEntity<Image> getImageById(@PathVariable Integer id) {
        Optional<Image> img = imageService.getImageById(id);
        return new ResponseEntity<Image>(HttpStatus.OK);    
}   ....

and I am trying to do some basic unit test on the getImageById method and it does not pass the test:


@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ImageControllerTest {
    @MockBean
    private ImgService service;
    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("GET /Image/1 - Found")
    void testGetImageIdFound() throws Exception {
        Image mockImage = new Image(1, "mockPath", "Normal");
        doReturn(Optional.of(mockImage)).when(service).getImageById(1);        mockMvc.perform(get("/getImage/{id}",1).accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$.id", is(1)))
    }

the error I am getting is "content type is not set"

This is the full trace:

java.lang.AssertionError: Content type not set
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:37)
    at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:70)
    at org.springframework.test.util.AssertionErrors.assertNotNull(AssertionErrors.java:106)
    at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$contentType$0(ContentResultMatchers.java:83)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at com.bachelor.ImageControllerTest.testGetImageIdFound(ImageControllerTest.java:61)
    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:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

What am I missing?

gtiwari333

As I mentioned in my comments, I fixed the following problems and now your test passes:

  • mockMvc.perform(get("/getImage/ doesn't match the full URL to the getImageById
  • You are not returning img object from the method.
  • make sure Image class has getters so that JSON will be properly serialized

Working code:

package sotestapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@SpringBootApplication
public class TestApp {
    public static void main(String[] args) {
        SpringApplication.run(TestApp.class, args);
    }
}

@RestController
@RequestMapping("/project/image")
class ImageController {
    @Autowired
    ImgService imageService;

    @GetMapping("/getImage/{id}")
    public ResponseEntity<Image> getImageById(@PathVariable Integer id) {
        Optional<Image> img = imageService.getImageById(id);
        return ResponseEntity.of(img);
    }
}

@Service
class ImgService {
    public Optional<Image> getImageById(Integer id) {
        return Optional.of(new Image(1, "test", "test"));
    }
}

class Image {
    int id;
    String path;
    String normal;

    public Image(int id, String path, String normal) {
        this.id = id;
        this.path = path;
        this.normal = normal;
    }

    public int getId() {
        return id;
    }

    public String getPath() {
        return path;
    }

    public String getNormal() {
        return normal;
    }
}

Test:

package sotestapp;

import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import java.util.Optional;

import static org.mockito.Mockito.doReturn;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

@SpringBootTest
@AutoConfigureMockMvc
public class ImageControllerTest {
    @MockBean
    private ImgService service;
    @Autowired
    private MockMvc mockMvc;

    @Test
    void testGetImageIdFound() throws Exception {
        Image mockImage = new Image(1, "mockPath", "Normal");
        doReturn(Optional.of(mockImage)).when(service).getImageById(1);
        mockMvc.perform(get("/project/image/getImage/{id}", 1)
                .accept(MediaType.APPLICATION_JSON_VALUE))
                .andExpect(jsonPath("$.id", Matchers.is(1)));
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

From Java

spring-boot-starter-test with JUnit 5

From Dev

How to write JUnit test with Spring Autowire?

From Dev

How to make Ant junit task show detail only if a test fails?

From Dev

Make Spring Boot Recreate Test Databases

From Dev

How to run Spring Shell scripts in a JUnit test

From Dev

How to test ConfigurationProperties in Spring with JUnit?

From Dev

Exception when building the ApplicationContext for a JUnit test in Activiti with Spring Boot

From Dev

How to hide spring boot banner.txt in junit test with SpringJUnit4TestRunner?

From Dev

How to make a Junit test case fail if there is any exception in the code?

From Dev

How to test Maven module project with Spring Boot

From Dev

Spring Boot profile. How to test?

From Dev

Spring Boot 1.4 - how to test a controller with the validation

From Dev

spring-boot-starter-test with JUnit 5

From Dev

How to catch Hibernate ConstraintViolationException (or Spring DataIntegrityViolationException?) in Spring Boot with JUnit 5

From Dev

How to run parallel test jUnit5 in spring boot - cucumber version 5 and more

From Dev

No vanilla JUnit dependency in spring-boot-starter-test?

From Dev

How to JUnit Test Spring-Boot's Application.java

From Dev

How to test Maven module project with Spring Boot

From Dev

Can't Autowire JpaRepository in Junit test - Spring boot application

From Dev

Spring boot unit test by Junit 5 why mock return null

From Dev

How to make a test case as fail in Junit?

From Dev

Spring Boot - How to test an image is correctly served

From Dev

Spring junit test not working

From Dev

ClassNotFoundException on Spring JavaMailSenderImpl in JUnit test with Spring Boot

From Dev

Cannot overrid Spring-Boot application properties in Junit Test

From Dev

How to make Java ServiceActivator visible in JUnit Test?

From Dev

JUnit spring boot application

From Dev

How to make JUnit test for void method with Scanner and while loop

Related Related

  1. 1

    How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

  2. 2

    spring-boot-starter-test with JUnit 5

  3. 3

    How to write JUnit test with Spring Autowire?

  4. 4

    How to make Ant junit task show detail only if a test fails?

  5. 5

    Make Spring Boot Recreate Test Databases

  6. 6

    How to run Spring Shell scripts in a JUnit test

  7. 7

    How to test ConfigurationProperties in Spring with JUnit?

  8. 8

    Exception when building the ApplicationContext for a JUnit test in Activiti with Spring Boot

  9. 9

    How to hide spring boot banner.txt in junit test with SpringJUnit4TestRunner?

  10. 10

    How to make a Junit test case fail if there is any exception in the code?

  11. 11

    How to test Maven module project with Spring Boot

  12. 12

    Spring Boot profile. How to test?

  13. 13

    Spring Boot 1.4 - how to test a controller with the validation

  14. 14

    spring-boot-starter-test with JUnit 5

  15. 15

    How to catch Hibernate ConstraintViolationException (or Spring DataIntegrityViolationException?) in Spring Boot with JUnit 5

  16. 16

    How to run parallel test jUnit5 in spring boot - cucumber version 5 and more

  17. 17

    No vanilla JUnit dependency in spring-boot-starter-test?

  18. 18

    How to JUnit Test Spring-Boot's Application.java

  19. 19

    How to test Maven module project with Spring Boot

  20. 20

    Can't Autowire JpaRepository in Junit test - Spring boot application

  21. 21

    Spring boot unit test by Junit 5 why mock return null

  22. 22

    How to make a test case as fail in Junit?

  23. 23

    Spring Boot - How to test an image is correctly served

  24. 24

    Spring junit test not working

  25. 25

    ClassNotFoundException on Spring JavaMailSenderImpl in JUnit test with Spring Boot

  26. 26

    Cannot overrid Spring-Boot application properties in Junit Test

  27. 27

    How to make Java ServiceActivator visible in JUnit Test?

  28. 28

    JUnit spring boot application

  29. 29

    How to make JUnit test for void method with Scanner and while loop

HotTag

Archive