Testing a Spring Boot application?

2019-09-05 16:12发布

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!

4条回答
啃猪蹄的小仙女
2楼-- · 2019-09-05 16:47

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());
查看更多
淡お忘
3楼-- · 2019-09-05 16:55
@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
}

}
查看更多
欢心
4楼-- · 2019-09-05 16:58

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();
    }

    }
查看更多
何必那么认真
5楼-- · 2019-09-05 17:04

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

查看更多
登录 后发表回答