Skip to content

Instantly share code, notes, and snippets.

@mooingcat
Last active March 16, 2017 15:35
Show Gist options
  • Save mooingcat/f04bb0012b9ec9252e42ae9a5d1dc371 to your computer and use it in GitHub Desktop.
Save mooingcat/f04bb0012b9ec9252e42ae9a5d1dc371 to your computer and use it in GitHub Desktop.
Snippets of useful Spring things

Testing

Best bits of https://spring.io/guides/gs/testing-web/:

Dependency

testCompile("org.springframework.boot:spring-boot-starter-test")

MockMvc

@AutoConfigureMockMvc on your test class, injects a MockMvc instance when you Autowired one. (You'll probably need @RunWith(SpringRunner.class) and @SpringBootTest too.)

Running tests on another port

Annotate test class with: @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) Inject port with @LocalServerPort

Running tests using TestRestTemplate

Spring will inject this for you. Nice.

@Autowired
private TestRestTemplate restTemplate;

Running only the web layer

Using @WebMvcTest instead of @SpringBootTest runs just the web layer (or even just for one controller using @WebMvcTest(OnlyOneController.class)), not the whole context. This means you could write a test for just one controller without having to worry about all the beans for other controllers you've not finished fixing yet. It also includes @AutoConfigureMockMvc for you.

Mocking controller constructor dependencies

Just adding a dependency to the controller constructor will mean you need to inject that dependency into all test classes using @MockBean which makes a mockito version of that bean.

JPA

Best bits of https://spring.io/guides/gs/accessing-data-jpa/

Dependencies

compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2")

Adding a repository

Extending the interface CrudRepository<T, ID> where T is an entity, Spring makes an implementation of that interface for you which includes save(), findOne(), findAll() etc as well as autogenerated methods based on the names of methods you add to that interface e.g. findByLastName().

T should have the @Entity annotation, and a protected empty constructor. Its id field should probably have the annotations @Id @GeneratedValue()

Validating form input

See https://spring.io/guides/gs/validating-form-input/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment