SpringCloud 所有測(cè)試的單一基類

2023-12-08 17:45 更新

在默認(rèn)的MockMvc中使用Spring Cloud Contract驗(yàn)證程序時(shí),您需要為所有生成的驗(yàn)收測(cè)試創(chuàng)建基本規(guī)范。在此類中,您需要指向一個(gè)端點(diǎn),該端點(diǎn)應(yīng)進(jìn)行驗(yàn)證。

package org.mycompany.tests

import org.mycompany.ExampleSpringController
import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
import spock.lang.Specification

class MvcSpec extends Specification {
  def setup() {
   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
  }
}

如果需要,您還可以設(shè)置整個(gè)上下文。

import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
public abstract class BaseTestClass {

	@Autowired
	WebApplicationContext context;

	@Before
	public void setup() {
		RestAssuredMockMvc.webAppContextSetup(this.context);
	}
}

如果使用EXPLICIT模式,則可以使用基類類似地初始化整個(gè)測(cè)試的應(yīng)用程序,就像在常規(guī)集成測(cè)試中可能會(huì)發(fā)現(xiàn)的那樣。

import io.restassured.RestAssured;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
public abstract class BaseTestClass {

	@LocalServerPort
	int port;

	@Before
	public void setup() {
		RestAssured.baseURI = "http://localhost:" + this.port;
	}
}

如果使用JAXRSCLIENT模式,則此基類還應(yīng)包含一個(gè)protected WebTarget webTarget字段。目前,測(cè)試JAX-RS API的唯一選項(xiàng)是啟動(dòng)web服務(wù)器。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)