Testing Controller Layer Lecture Notes
Testing Controller Layer Lecture Notes
Mockito @WebMvcTest
Hamcrest Librar
Hamcrest is the well-known framework used for unit testing in the Java ecosystem.
It's bundled in JUnit and simply put, it uses existing predicates – called matcher
classes – for making assertions.
Hamcrest is commonly used with JUnit and other testing frameworks for making
assertions. Speci cally, instead of using JUnit’s numerous assert methods, we only
use the API's single assertThat statement with appropriate matchers.
Hamcrest is() method: If we want to verify that the expected value (or object) is
equal to the actual value (or object), we have to create our Hamcrest matcher by
invoking the is() method of the Matchers class.
Syntax:
assertThat(ACTUAL, is(EXPECTED))
fi
y
JsonPath Librar
A Java DSL for reading JSON documents
JsonPath expressions always refer to a JSON structure in the same way as XPath
expression are used in combination with an XML document. The "root member
object" in JsonPath is always referred to as $ regardless if it is an object or array.
fi
fi
.
"
Syntax
@Test
public void given_when_then() {
// given - precondition or setup
@WebMvcTest Annotatio
SpringBoot provides @WebMvcTest annotation to test Spring MVC Controllers.
Also, @WebMvcTest based tests runs faster as it will load only the speci ed controller
and its dependencies only without loading the entire application
Spring Boot instantiates only the web layer rather than the whole application context. In
an application with multiple controllers, you can even ask for only one to be
instantiated by using, for example, @WebMvcTest(HomeController.class).
@WebMvcTest
HomeController
Controller Service Repository
EmployeeController DB
UserController
Layer Layer Layer
fi
@WebMvcTest vs @SpringBootTes
Spring Boot provides @WebMvcTest annotation to test Spring MVC controllers. This
annotation creates an application context that contains all the beans necessary for testing
a Spring web controller.
HomeController
Controller Service Repository
EmployeeController DB
UserController
Layer Layer Layer