Best bits of https://spring.io/guides/gs/testing-web/:
testCompile("org.springframework.boot:spring-boot-starter-test")
@AutoConfigureMockMvc
on your test class, injects a MockMvc
instance when you Autowired
one.
(You'll probably need @RunWith(SpringRunner.class)
and @SpringBootTest
too.)
Annotate test class with: @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Inject port with @LocalServerPort
Spring will inject this for you. Nice.
@Autowired
private TestRestTemplate restTemplate;
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.
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.
Best bits of https://spring.io/guides/gs/accessing-data-jpa/
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2")
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()