簡體   English   中英

測試Spring Boot應用程序?

[英]Testing a Spring Boot application?

我想為控制器類創建一個Spring Boot測試。

我要測試的方法是:

private String statusQueryToken;

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

我不確定如何在Spring Boot中測試事物。

如果我想測試狀態statusQueryToken是否已使用@RequestParam("status_query_token")進行了初始化,我該怎么做?

謝謝!

您可以使用Spring MockMvc

所以嘗試這樣的事情:

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

有幾種方法可以解決此問題。 我首選的使用實際tomcat實例進行測試的方法。

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

    }

有不同的測試方法

1.使用Maven

$ mvn clean install

默認情況下,這將生成帶有嵌入tomcat的spring boot的jar文件

$ mvn spring-boot:run

這將運行您的春季應用程序

現在,Spring已啟動並運行

2.創建一個可執行jar(在Maven上不存在)

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

“與上述效果相同”

現在打開瀏覽器或soap ui或fiddler或postmaster將請求發送到控制器

例如:GET方法http:// localhost:8080 / myproject / onCompletion / hello

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

@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
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM