The older version of the new edition simplifies a lot
Add directly on the test class
@RunWith (Springrunner. class = Own startup class, Webenvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
Colleague injects the Testresttemplate class and injects the current port number through @LocalServerPort annotations
The specific test code is as follows:
@RunWith (Springrunner.class) @SpringBootTest (Classes= Serverapplication.class, webenvironment =SpringBootTest.WebEnvironment.RANDOM_PORT) Public classTest {@LocalServerPortPrivate intPort; PrivateURL Base; PrivateGson Gson =NewGson (); @AutowiredPrivatetestresttemplate resttemplate; @Before Public voidSetUp ()throwsException { This. Base =NewURL ("http://localhost:" + port + "/"); } @Test Public voidTest () {responseentity<String> test = This. Resttemplate.getforentity ( This. base.tostring () + "/test", String.class, "Test"); System.out.println (Test.getbody ()); }}
Controller
@RestController @requestmapping ("/test") Public class Processinstancecontroller { = "", method = requestmethod.get) public String Test () { return "Greetings from Spring boot!" ; }}
Serverapplication:
@SpringBootApplication Public classServerapplicationextendsSpringbootservletinitializerImplementsCommandlinerunner {@OverrideprotectedSpringapplicationbuilder Configure (Springapplicationbuilder application) {returnApplication.sources (serverapplication.class); } Public Static voidMain (string[] args)throwsIOException {springapplication.run (serverapplication.class, args); } @Override Public voidRun (String ... strings)throwsException {System.out.println ("Initialize ......" "); }}
Spring boot 1.4.2 Unit Test Configuration