Testing a Spring Boot application?

2019-09-05 16:56发布

问题:

I want to create a Spring Boot test for a Controller-class.

The method I want to test is:

private String statusQueryToken;

@RequestMapping("/onCompletion")
public String whenSigningComplete(@RequestParam("status_query_token") String token){
    this.statusQueryToken = token;

I am unsure about how to test things in Spring Boot.

If I wanted to test that the field statusQueryToken has been initialized with the @RequestParam("status_query_token"), how would I go about doing this?

Thank you!

回答1:

You can use Spring MockMvc

So try something like this:

MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
mockMvc.perform(get("/onCompletion").param("status_query_token", "yourToken"))
                .andExpect(status().isOk());


回答2:

There are several way you can approach this. My preferred way to test with the real tomcat instance.

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebIntegrationTest("server.port:0")
    @SpringApplicationConfiguration(YourMainApplication.class)
    public class TestClass() {
        @Value("${local.server.port}")
        private int port;
    @Autowired
    private RestTemplate restTemplate;

   public <T> T get(String path, Class<T> responseType, Object... pathVariables) {
        return restTemplate.getForEntity(path, responseType, pathVariables).getBody();
    }

    }


回答3:

There are different ways to test

1. Using Maven

$ mvn clean install

This will generate the jar file with spring boot embedded with tomcat by default

$ mvn spring-boot:run

This will run you spring app

Now Spring is up and running

2. Creating an executable jar (in absence on maven)

$ java -jar target/myproject.0.0.1.SNAPSHOT.jar

"Same effect as above"

Now open the browser or soap ui or fiddler or postmaster to send request to the controller

ex: GET method http://localhost:8080/myproject/onCompletion/hello

http://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html



回答4:

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = ApplicationConfiguration.class)
public class ItemFeedTest {

@InjectMocks
private PersonRepository personRepository;


@Autowired
@Mock
private PersonService personService;


@Before
    public void setup() throws IOException {
        MockitoAnnotations.initMocks(this);
    }

@Test
    public void onSuccessTest() {
        //Write the Junit Test and mock the required Class
}

}