Add a new spring-boot-sample-test application

Add a sample application that demonstrates recently added testing
features.

See gh-4901
This commit is contained in:
Phillip Webb
2016-03-22 10:22:25 -07:00
parent 81d5635571
commit 247bdf9c84
30 changed files with 1582 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import sample.test.domain.VehicleIdentificationNumber;
import sample.test.service.VehicleDetails;
import sample.test.service.VehicleDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.web.WebIntegrationTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import static org.mockito.BDDMockito.given;
/**
* {@code @WebIntegrationTest} for {@link SampleTestApplication}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@WebIntegrationTest(randomPort = true)
@AutoConfigureTestDatabase
public class SampleTestApplicationWebIntegrationTests {
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber(
"01234567890123456");
@Autowired
private TestRestTemplate restTemplate;
@MockBean
private VehicleDetailsService vehicleDetailsService;
@Before
public void setup() {
given(this.vehicleDetailsService.getVehicleDetails(VIN))
.willReturn(new VehicleDetails("Honda", "Civic"));
}
@Test
public void test() {
this.restTemplate.getForEntity("/{username}/vehicle", String.class, "sframework");
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.domain;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Data JPA tests for {@link User}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserEntityTests {
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber(
"00000000000000000");
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired
private TestEntityManager entityManager;
@Test
public void createWhenUserIdIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Username must not be empty");
new User(null, VIN);
}
@Test
public void createWhenUserIdIsEmptyShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Username must not be empty");
new User("", VIN);
}
@Test
public void createWhenVinIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("VIN must not be null");
new User("sboot", null);
}
@Test
public void saveShouldPersistData() throws Exception {
User user = this.entityManager.persistFlushFind(new User("sboot", VIN));
assertThat(user.getUsername()).isEqualTo("sboot");
assertThat(user.getVin()).isEqualTo(VIN);
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.domain;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link UserRepository}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTests {
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber(
"00000000000000000");
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository repository;
@Test
public void findByUsernameShouldReturnUser() throws Exception {
this.entityManager.persist(new User("sboot", VIN));
User user = this.repository.findByUsername("sboot");
assertThat(user.getUsername()).isEqualTo("sboot");
assertThat(user.getVin()).isEqualTo(VIN);
}
@Test
public void findByUsernameWhenNoUserShouldReturnNull() throws Exception {
this.entityManager.persist(new User("sboot", VIN));
User user = this.repository.findByUsername("mmouse");
assertThat(user).isNull();
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.domain;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link VehicleIdentificationNumber}.
*
* @author Phillip Webb
* @see <a href="http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html">
* Naming standards for unit tests</a>
* @see <a href="http://joel-costigliola.github.io/assertj/">AssertJ</a>
*/
public class VehicleIdentificationNumberTests {
private static final String SAMPLE_VIN = "41549485710496749";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void createWhenVinIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("VIN must not be null");
new VehicleIdentificationNumber(null);
}
@Test
public void createWhenVinIsMoreThan17CharsShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("VIN must be exactly 17 characters");
new VehicleIdentificationNumber("012345678901234567");
}
@Test
public void createWhenVinIsLessThan17CharsShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("VIN must be exactly 17 characters");
new VehicleIdentificationNumber("0123456789012345");
}
@Test
public void toStringShouldReturnVin() throws Exception {
VehicleIdentificationNumber vin = new VehicleIdentificationNumber(SAMPLE_VIN);
assertThat(vin.toString()).isEqualTo(SAMPLE_VIN);
}
@Test
public void equalsAndHashShouldBeBasedOnVin() throws Exception {
VehicleIdentificationNumber vin1 = new VehicleIdentificationNumber(SAMPLE_VIN);
VehicleIdentificationNumber vin2 = new VehicleIdentificationNumber(SAMPLE_VIN);
VehicleIdentificationNumber vin3 = new VehicleIdentificationNumber(
"00000000000000000");
assertThat(vin1.hashCode()).isEqualTo(vin2.hashCode());
assertThat(vin1).isEqualTo(vin1).isEqualTo(vin2).isNotEqualTo(vin3);
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.service;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import sample.test.domain.VehicleIdentificationNumber;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.HttpServerErrorException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
/**
* Tests for {@link RemoteVehicleDetailsService}.
*
* @author Phillip Webb
*/
public class RemoteVehicleDetailsServiceTests {
private static final String VIN = "00000000000000000";
@Rule
public ExpectedException thrown = ExpectedException.none();
private RemoteVehicleDetailsService service;
private MockRestServiceServer server;
@Before
public void setup() {
ServiceProperties properties = new ServiceProperties();
properties.setVehicleServiceRootUrl("http://example.com/");
this.service = new RemoteVehicleDetailsService(properties);
this.server = MockRestServiceServer.createServer(this.service.getRestTemplate());
}
@Test
public void getVehicleDetailsWhenVinIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("VIN must not be null");
this.service.getVehicleDetails(null);
}
@Test
public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails()
throws Exception {
this.server.expect(requestTo("http://example.com/vehicle/" + VIN + "/details"))
.andRespond(withSuccess(getClassPathResource("vehicledetails.json"),
MediaType.APPLICATION_JSON));
VehicleDetails details = this.service
.getVehicleDetails(new VehicleIdentificationNumber(VIN));
assertThat(details.getMake()).isEqualTo("Honda");
assertThat(details.getModel()).isEqualTo("Civic");
}
@Test
public void getVehicleDetailsWhenResultIsNotFoundShouldThrowException()
throws Exception {
this.server.expect(requestTo("http://example.com/vehicle/" + VIN + "/details"))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
this.thrown.expect(VehicleIdentificationNumberNotFoundException.class);
this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN));
}
@Test
public void getVehicleDetailsWhenResultIServerErrorShouldThrowException()
throws Exception {
this.server.expect(requestTo("http://example.com/vehicle/" + VIN + "/details"))
.andRespond(withServerError());
this.thrown.expect(HttpServerErrorException.class);
this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN));
}
private ClassPathResource getClassPathResource(String path) {
return new ClassPathResource(path, getClass());
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* JSON Tests for {@link VehicleDetails}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@JsonTest
public class VehicleDetailsJsonTests {
private JacksonTester<VehicleDetails> json;
@Test
public void serializeJson() throws Exception {
VehicleDetails details = new VehicleDetails("Honda", "Civic");
assertThat(this.json.write(details)).isEqualTo("vehicledetails.json");
assertThat(this.json.write(details)).isEqualToJson("vehicledetails.json");
assertThat(this.json.write(details)).hasJsonPathStringValue("@.make");
assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make")
.isEqualTo("Honda");
}
@Test
public void deserializeJson() throws Exception {
String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
assertThat(this.json.parse(content))
.isEqualTo(new VehicleDetails("Ford", "Focus"));
assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford");
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import sample.test.WelcomeCommandLineRunner;
import sample.test.service.VehicleDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringApplicationTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* {@code @SpringApplicationTest} based tests for {@link UserVehicleController}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@SpringApplicationTest
@AutoConfigureMockMvc
@AutoConfigureTestDatabase
public class UserVehicleControllerApplicationTests {
@Autowired
private MockMvc mvc;
@Autowired
private ApplicationContext applicationContext;
@MockBean
private UserVehicleService userVehicleService;
@Test
public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(new VehicleDetails("Honda", "Civic"));
this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
}
@Test
public void welcomeCommandLineRunnerShouldBeAvailble() throws Exception {
// Since we're a @SpringApplicationTest all beans should be available
assertThat(this.applicationContext.getBean(WelcomeCommandLineRunner.class))
.isNotNull();
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.web;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.junit.Test;
import org.junit.runner.RunWith;
import sample.test.service.VehicleDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* HtmlUnit based tests for {@link UserVehicleController}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public class UserVehicleControllerHtmlUnitTests {
@Autowired
private WebClient webClient;
@MockBean
private UserVehicleService userVehicleService;
@Test
public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(new VehicleDetails("Honda", "Civic"));
HtmlPage page = this.webClient.getPage("/sboot/vehicle.html");
assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic");
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import sample.test.service.VehicleDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Selenium based tests for {@link UserVehicleController}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public class UserVehicleControllerSeleniumTests {
@Autowired
private WebDriver webDriver;
@MockBean
private UserVehicleService userVehicleService;
@Test
public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(new VehicleDetails("Honda", "Civic"));
this.webDriver.get("/sboot/vehicle.html");
WebElement element = this.webDriver.findElement(By.tagName("h1"));
assertThat(element.getText()).isEqualTo("Honda Civic");
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import sample.test.WelcomeCommandLineRunner;
import sample.test.domain.VehicleIdentificationNumber;
import sample.test.service.VehicleDetails;
import sample.test.service.VehicleIdentificationNumberNotFoundException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* {@code @WebMvcTest} based tests for {@link UserVehicleController}.
*
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public class UserVehicleControllerTests {
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber(
"00000000000000000");
@Autowired
private MockMvc mvc;
@Autowired
private ApplicationContext applicationContext;
@MockBean
private UserVehicleService userVehicleService;
@Test
public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(new VehicleDetails("Honda", "Civic"));
this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
}
@Test
public void getVehicleWhenRequestingJsonShouldReturnMakeAndModel() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(new VehicleDetails("Honda", "Civic"));
this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json("{'make':'Honda','model':'Civic'}"));
}
@Test
public void getVehicleWhenRequestingHtmlShouldReturnMakeAndModel() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(new VehicleDetails("Honda", "Civic"));
this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk())
.andExpect(content().string(containsString("<h1>Honda Civic</h1>")));
}
@Test
public void getVehicleWhenUserNotFoundShouldReturnNotFound() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willThrow(new UserNameNotFoundException("sboot"));
this.mvc.perform(get("/sboot/vehicle")).andExpect(status().isNotFound());
}
@Test
public void getVehicleWhenVinNotFoundShouldReturnNotFound() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willThrow(new VehicleIdentificationNumberNotFoundException(VIN));
this.mvc.perform(get("/sboot/vehicle")).andExpect(status().isNotFound());
}
@Test(expected = NoSuchBeanDefinitionException.class)
public void welcomeCommandLineRunnerShouldBeAvailble() throws Exception {
// Since we're a @WebMvcTest WelcomeCommandLineRunner should not be available
assertThat(this.applicationContext.getBean(WelcomeCommandLineRunner.class));
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.test.web;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import sample.test.domain.User;
import sample.test.domain.UserRepository;
import sample.test.domain.VehicleIdentificationNumber;
import sample.test.service.VehicleDetails;
import sample.test.service.VehicleDetailsService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
/**
* Tests for {@link UserVehicleService}.
*
* @author Phillip Webb
*/
public class UserVehicleServiceTests {
private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber(
"00000000000000000");
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
private VehicleDetailsService vehicleDetailsService;
@Mock
private UserRepository userRepository;
private UserVehicleService service;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.service = new UserVehicleService(this.userRepository,
this.vehicleDetailsService);
}
@Test
public void getVehicleDetailsWhenUsernameIsNullShouldThrowException()
throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Username must not be null");
this.service.getVehicleDetails(null);
}
@Test
public void getVehicleDetailsWhenUserNameNotFoundShouldThrowException()
throws Exception {
given(this.userRepository.findByUsername(anyString())).willReturn(null);
this.thrown.expect(UserNameNotFoundException.class);
this.service.getVehicleDetails("sboot");
}
@Test
public void getVehicleDetailsShouldReturnMakeAndModel() throws Exception {
given(this.userRepository.findByUsername(anyString()))
.willReturn(new User("sboot", VIN));
VehicleDetails details = new VehicleDetails("Honda", "Civic");
given(this.vehicleDetailsService.getVehicleDetails(VIN)).willReturn(details);
VehicleDetails actual = this.service.getVehicleDetails("sboot");
assertThat(actual).isEqualTo(details);
}
}