Skip to content

Instantly share code, notes, and snippets.

@rasheedamir
Last active June 4, 2017 07:39
Show Gist options
  • Save rasheedamir/4f6001aa4617264c4c706aa1795a6ed1 to your computer and use it in GitHub Desktop.
Save rasheedamir/4f6001aa4617264c4c706aa1795a6ed1 to your computer and use it in GitHub Desktop.
Java Tests
@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);
}
}
@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");
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
// Your spring configuration class containing the @EnableAutoConfiguration
// annotation
@SpringApplicationConfiguration(classes = Application.class)
// Makes sure the application starts at a random free port, caches it throughout
// all unit tests, and closes it again at the end.
@IntegrationTest("server.port:0")
@WebAppConfiguration
public abstract class AbstractIntegrationTest {
// Will contain the random free port number
@Value("${local.server.port}")
private int port;
/**
* Returns the base url for your rest interface
*
* @return
*/
private String getBaseUrl() {
return "http://localhost:" + port;
}
// Some convenience methods to help you interact with your rest interface
/**
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceReturnTypeClass
* should be the the return type of the service
* @param parametersInOrderOfAppearance
* should be the parameters of the requestMappingUrl ({}) in
* order of appearance
* @return the result of the service, or null on error
*/
protected <T> T getEntity(final String requestMappingUrl, final Class<T> serviceReturnTypeClass, final Object... parametersInOrderOfAppearance) {
// Make a rest template do do the service call
final TestRestTemplate restTemplate = new TestRestTemplate();
// Add correct headers, none for this example
final HttpEntity<String> requestEntity = new HttpEntity<String>(new HttpHeaders());
try {
// Do a call the the url
final ResponseEntity<T> entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, serviceReturnTypeClass,
parametersInOrderOfAppearance);
// Return result
return entity.getBody();
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
/**
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceListReturnTypeClass
* should be the the generic type of the list the service
* returns, eg: List<serviceListReturnTypeClass>
* @param parametersInOrderOfAppearance
* should be the parameters of the requestMappingUrl ({}) in
* order of appearance
* @return the result of the service, or null on error
*/
protected <T> List<T> getList(final String requestMappingUrl, final Class<T> serviceListReturnTypeClass, final Object... parametersInOrderOfAppearance) {
final ObjectMapper mapper = new ObjectMapper();
final TestRestTemplate restTemplate = new TestRestTemplate();
final HttpEntity<String> requestEntity = new HttpEntity<String>(new HttpHeaders());
try {
// Retrieve list
final ResponseEntity<List> entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, List.class, parametersInOrderOfAppearance);
final List<Map<String, String>> entries = entity.getBody();
final List<T> returnList = new ArrayList<T>();
for (final Map<String, String> entry : entries) {
// Fill return list with converted objects
returnList.add(mapper.convertValue(entry, serviceListReturnTypeClass));
}
return returnList;
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
/**
*
* @param requestMappingUrl
* should be exactly the same as defined in your RequestMapping
* value attribute (including the parameters in {})
* RequestMapping(value = yourRestUrl)
* @param serviceReturnTypeClass
* should be the the return type of the service
* @param objectToPost
* Object that will be posted to the url
* @return
*/
protected <T> T postEntity(final String requestMappingUrl, final Class<T> serviceReturnTypeClass, final Object objectToPost) {
final TestRestTemplate restTemplate = new TestRestTemplate();
final ObjectMapper mapper = new ObjectMapper();
try {
final HttpEntity<String> requestEntity = new HttpEntity<String>(mapper.writeValueAsString(objectToPost));
final ResponseEntity<T> entity = restTemplate.postForEntity(getBaseUrl() + requestMappingUrl, requestEntity, serviceReturnTypeClass);
return entity.getBody();
} catch (final Exception ex) {
// Handle exceptions
}
return null;
}
}
Also note that @TestPropertySource can accept a properties argument to overwrite some property inline, such as @TestPropertySource(properties = "myConf.myProp=valueInTest"), it's useful in case that you don't want a totally brand new property file.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public class ExampleApplicationTests {
}
You can use @TestPropertySource to override values in application.properties. From its javadoc:
test property sources can be used to selectively override properties defined in system and application property sources
You can also use meta-annotations to externalize the configuration. For example:
@RunWith(SpringJUnit4ClassRunner.class)
@DefaultTestAnnotations
public class ExampleApplicationTests {
...
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public @interface DefaultTestAnnotations { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment