First of all, I have the following endpoint method present within a class called RecipeController:
#RequestMapping(value = {"/", "/recipes"})
public String listRecipes(Model model, Principal principal){
List<Recipe> recipes;
User user = (User)((UsernamePasswordAuthenticationToken)principal).getPrincipal();
User actualUser = userService.findByUsername(user.getUsername());
if(!model.containsAttribute("recipes")){
recipes = recipeService.findAll();
model.addAttribute("nullAndNonNullUserFavoriteRecipeList",
UtilityMethods.nullAndNonNullUserFavoriteRecipeList(recipes, actualUser.getFavoritedRecipes()));
model.addAttribute("recipes", recipes);
}
if(!model.containsAttribute("recipe")){
model.addAttribute("recipe", new Recipe());
}
model.addAttribute("categories", Category.values());
model.addAttribute("username", user.getUsername());
return "recipe/index";
}
As you can see above, the method takes as a second parameter a Principal object. When running the application, the parameter points to a non-null object as expected. It contains information about the user that is currently logged in within the application.
I have created a test class for the RecipeController called RecipeControllerTest. This class contains a single method called testListRecipes.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
#WebAppConfiguration
public class RecipeControllerTest{
#Mock
private RecipeService recipeService;
#Mock
private IngredientService ingredientService;
#Mock
private StepService stepService;
#Mock
private UserService userService;
#Mock
private UsernamePasswordAuthenticationToken principal;
private RecipeController recipeController;
private MockMvc mockMvc;
#Before
public void setUp(){
MockitoAnnotations.initMocks(this);
recipeController = new RecipeController(recipeService,
ingredientService, stepService, userService);
mockMvc = MockMvcBuilders.standaloneSetup(recipeController).build();
}
#Test
public void testListRecipes() throws Exception {
User user = new User();
List<Recipe> recipes = new ArrayList<>();
Recipe recipe = new Recipe();
recipes.add(recipe);
when(principal.getPrincipal()).thenReturn(user);
when(userService.findByUsername(anyString()))
.thenReturn(user);
when(recipeService.findAll()).thenReturn(recipes);
mockMvc.perform(get("/recipes"))
.andExpect(status().isOk())
.andExpect(view().name("recipe/index"))
.andExpect(model().attributeExists("recipes"))
.andExpect(model().attributeExists("recipe"))
.andExpect(model().attributeExists("categories"))
.andExpect(model().attributeExists("username"));
verify(userService, times(1)).findByUsername(anyString());
verify(recipeService, times(1)).findAll();
}
}
As you can see in this second snippet, I tried to mock the Principal object within the test class, using the UsernamePasswordAuthenticationToken implementation.
When I run the test, I get a NullPointerException, and the stacktrace points me to the following line from the first snippet of code:
User user = (User)((UsernamePasswordAuthenticationToken)principal).getPrincipal();
The principal object passed as a parameter to the listRecipes method from is still null, even though I tried to provide a mock object.
Any suggestions ?
Create a class that implements Principal:
class PrincipalImpl implements Principal {
#Override
public String getName() {
return "XXXXXXX";
}
}
Sample test:
#Test
public void login() throws Exception {
Principal principal = new PrincipalImpl();
mockMvc.perform(get("/login").principal(principal)).andExpect(.........;
}
Spring MVC is very flexible with controller arguments, which lets you put most of the responsibility of looking up information onto the framework and focus on writing the business code. In this particular case, while you can use Principal as a method parameter, it's usually much better to use your actual principal class:
public String listRecipes(Model model, #AuthenticationPrincipal User user)
To actually set the user for a test, you need to work with Spring Security, which means adding .apply(springSecurity()) to your setup. (Complications like this, by the way, are the main reason I dislike using standaloneSetup, as it requires you to remember to duplicate your exact production setup. I recommend writing actual unit tests and/or full-stack tests.) Then annotate your test with #WithUserDetails and specify the username of the test user.
Finally, as a side note this controller pattern can be simplified significantly with Querydsl, as Spring is able to inject a Predicate that combines all of the filter attributes you're looking up by hand, and then you can pass that predicate to a Spring Data repository.
Did you try using...?
#Test
#WithMockUser(username = "my_principal")
public void testListRecipes() {
...
Related
I'm trying to test my service implementation with JUNIT5. I don't quite understand whats going wrong but my UserRepository doesn't seem to be returning a value.
I have tested to see if the UserRepository has been used with:
verify(repository, times(1)); And the response was "Wanted but not invoked...Actually, there were zero interactions with this mock"
Here is the Test Class:
#ExtendWith(MockitoExtension.class)
public class UserServiceTest {
#Mock
UserRepository repository;
#InjectMocks
UserServiceImpl userServiceImpl;
UserModel inputUserModel;
#BeforeEach
public void setUp() throws Exception {
inputUserModel = new UserModel();
inputUserModel.setEmail("testemail#gmail.com");
inputUserModel.setFirstName("john");
inputUserModel.setLastName("doe");
inputUserModel.setPassword("test");
inputUserModel.setMatchPassword("test");
User inputUser = User.builder()
.email(inputUserModel.getEmail())
.firstName(inputUserModel.getFirstName())
.lastName(inputUserModel.getLastName())
.password(inputUserModel.getPassword())
.timeCreated(Timestamp.valueOf(LocalDateTime.now(ZoneId.systemDefault()))).userID(1)
.build();
User outputUser = User.builder().
email(inputUserModel.getFirstName()).
password(inputUserModel.getLastName()).
lastName(inputUserModel.getFirstName())
.firstName(inputUserModel.getFirstName())
.timeCreated(Timestamp.valueOf(LocalDateTime.now(ZoneId.systemDefault()))).userID(1).build();
Mockito.when(repository.save(inputUser)).thenReturn(outputUser);
}
#Test
public void whenSaveUser_ThenUserHasID(){
Assertions.assertEquals(1, userServiceImpl.saveUser(inputUserModel).getUserID());
}
}
The error that I am getting:
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'save' method:
repository.save(
User(userID=0, email=testemail#gmail.com, timeCreated=2022-12-14 03:18:24.0435578, password=test, firstName=john, lastName=doe)
);
-> at com.jschwery.securitydemo.service.Implementations.UserServiceImpl.saveUser(UserServiceImpl.java:37)
- has following stubbing(s) with different arguments:
1. repository.save(
User(userID=1, email=testemail#gmail.com, timeCreated=2022-12-14 03:18:24.0235563, password=test, firstName=john, lastName=doe)
);
My Service Class that I'm creating the test for:
public class UserServiceImpl implements UserService {
UserRepository userRepository;
#Autowired
public UserServiceImpl(UserRepository repository){
this.userRepository = repository;
}
#Override
public User saveUser(UserModel userModel) {
if(!Objects.equals(userModel.getPassword(), userModel.getMatchPassword())){
throw new UserException("Passwords do not match");
}
User user = User.builder().
email(userModel.getEmail()).
firstName(userModel.getFirstName()).
lastName(userModel.getLastName()).
password(userModel.getPassword()).
timeCreated(Timestamp.valueOf(LocalDateTime.now(ZoneId.systemDefault()))).build();
User returnedUser = userRepository.save(user);
System.out.println(returnedUser.getEmail());
System.out.println("userID" + returnedUser.getUserID());
return returnedUser;
}
}
Thanks for reading! :)
I guess that your User class has an equals/hashCode defined either on the userID field or on all fields. When you mock your repository in your setUp method, you define what the method should do when it is called with the exact object that you specified, comparing the given object to the object specified in the mock by calling the equals/hashCode method.
You define the User object in your setUp method to have the userID 1 but in your UserServiceImpl the userID is not ever set (as it is generated by the persistence layer). Therefore the equals/hashCode check to determine if Mockito should execute the stub logic will never be called because the object passed by the UserServiceImpl will never be equals to the one that you defined in your mock.
There are several ways how you can solve this.
1) Integration test
My advice would be to convert your Unit-Test to a #SpringBootTest. There is no value in testing mocked behaviour. If this test was an integration test, you would test that the repository inserts the User into the database and generates an ID with your assertion.
2) Unit test
If you want to mock the repository, you should use an any() matcher for the input argument and then do what the repository would do, namely set the id:
when(repository.save(any(User.class))).thenAnswer(invocation -> {
final User entity = invocation.getArgument(0);
ReflectionTestUtils.setField(entity, "userID", RandomUtils.nextLong());
return entity;
});
I would then assert, that the userID is not null, as the userID will be randomly generated as it would in production:
#ExtendWith(MockitoExtension.class)
public class UserServiceTest {
#Mock
private UserRepository repository;
#InjectMocks
private UserServiceImpl userServiceImpl;
#Test
void saveUser_userHasID(){
// Arrange
final UserModel inputUserModel = new UserModel();
inputUserModel.setEmail("testemail#gmail.com");
inputUserModel.setFirstName("john");
inputUserModel.setLastName("doe");
inputUserModel.setPassword("test");
inputUserModel.setMatchPassword("test");
when(repository.save(any(User.class))).thenAnswer(invocation -> {
final User entity = invocation.getArgument(0);
ReflectionTestUtils.setField(entity, "userID", RandomUtils.nextLong());
return entity;
});
// Act
final User user = userServiceImpl.saveUser(inputUserModel);
// Assert
assertThat(user.getUserID()).isNotNull();
}
}
I highly recommend to use AssertJ for your assertions as it offers fluent asssertions and way more assertion methods than JUnit.
tl;dr
Spring data can't generate a userID through a simple unit test with a mock, you will need a spring context running in an Integration test.
Details
There are two fields leading to the error you are having : UserID and timeCreated.
For the timeCreated field : in your test you create a inputUser
object that you use for your mock. the problem is that this object
inputUser is NOT the one used by your method under test
saveUser(UserModel userModel) you could clearly see the that the
timestamp differs in the erreor between the two objects.
For the UserID field : again you give your expect your mock to use
the inputUser object. this object has userID = 1. but in the real
method saveUser(UserModel userModel) this field is not set
explicitly so the default value will be set to 0 you could see that
also in the error.
Now since your test case whenSaveUser_ThenUserHasID is meant to verify that a saved record has an ID, you can't do it with a mock. The ID is generated by the Spring Data you are using and yo make it run, you should use and Integration test to run your spring context in your test in order for your spring data to be able to generate an ID for your user, here is a previous question that will be helpful for you to do so. With this, you will neither need the inputUser in your test nor the mock. (You can use #DataJpaTest from JUnit 5 or #SpringBootTest...)
tl;dr:
Seems like the Mock of the repository I created with custom behavior regarding the save method when injected loses the custom behavior.
Problem Description
I've been trying to test a Service in Spring. The method of interest in particular takes some parameters and creates a User that is saved into a UserRepository through the repository method save.
The test I am interest in making is comparing these parameters to the properties of the User passed to the save method of the repository and in this way check if it is properly adding a new user.
For that I decided to Mock the repository and save the param passed by the service method in question to the repository save method.
I based myself on this question to save the User.
private static User savedUser;
public UserRepository createMockRepo() {
UserRepository mockRepo = mock(UserRepository.class);
try {
doAnswer(new Answer<Void>() {
#Override
public Void answer(InvocationOnMock invocation) throws Throwable {
savedUser= (User) invocation.getArguments(0);
return null;
}
}).when(mockRepo).save(any(User.class));
} catch( Exception e) {}
return mockRepo;
}
private UserRepository repo = createMockRepo();
Two notes:
I gave the name repo in case the name had to match the one in the service.
There is no #Mock annotation since it starts failing the test, I presume that is because it will create a mock in the usual way (without the custom method I created earlier).
I then created a test function to check if it had the desired behavior and all was good.
#Test
void testRepo() {
User u = new User();
repo.save(u);
assertSame(u, savedUser);
}
Then I tried doing what I saw recommended across multiple questions, that is, to inject the mock into the service as explained here.
#InjectMocks
private UserService service = new UserService();
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
This is where the problems arise, the test I created for it throws a null exception when I try to access savedUser properties (here I simplified the users properties since that doesn't seem to be the cause).
#Test
void testUser() {
String name = "Steve";
String food = "Apple";
service.newUser(name, food);
assertEquals(savedUser.getName(), name);
assertEquals(savedUser.getFood(), food);
}
Upon debugging:
the service seems to have received the mock: debugged properties of the service
the savedUser is indeed null: debugged savedUser propert .
I decided to log the function with System.out.println for demonstrative purposes.
A print of my logging of the tests, demonstrating that the user test doesn't call the answer method
What am I doing wrong here?
Thank you for the help in advance, this is my first stack exchange question any tips for improvement are highly appreciated.
Instead of instanciating your service in the test class like you did, use #Autowired and make sure your UserRepository has #MockBean in the test class
#InjectMocks
#Autowired
private UserService service
#MockBean
private UserRepository mockUserRepo
With this, you can remove your setup method
But make sure your UserRepository is also autowired insider your Service
You should not need Spring to test of this. If you are following Spring best practicies when it comes to autowiring dependencies you should be able just create the objects yourself and pass the UserRepository to the UserService
Best practices being,
Constructor injection for required beans
Setter injection for optional beans
Field injection never unless you cannot inject to a constructor or setter, which is very very rare.
Note that InjectMocks is not a dependency injection framework and I discourage its use. You can see in the javadoc that it can get fairly complex when it comes to constructor vs. setter vs. field.
Note that working examples of the code here can be found in this GitHub repo.
A simple way to clean up your code and enable it to be more easily tested would be to correct the UserService to allow you to pass whatever implementation of a UserRepository you want, this also allows you to gaurentee immuability,
public class UserService {
public UserService(final UserRepository userRepository) {
this.userRepository = userRepository;
}
public final UserRepository userRepository;
public User newUser(String name, String food) {
var user = new User();
user.setName(name);
user.setFood(food);
return userRepository.save(user);
}
}
and then your test would be made more simple,
class UserServiceTest {
private UserService userService;
private UserRepository userRepository;
private static User savedUser;
#BeforeEach
void setup() {
userRepository = createMockRepo();
userService = new UserService(userRepository);
}
#Test
void testSaveUser(){
String name = "Steve";
String food = "Apple";
userService.newUser(name, food);
assertEquals(savedUser.getName(), name);
assertEquals(savedUser.getFood(), food);
}
public UserRepository createMockRepo() {
UserRepository mockRepo = mock(UserRepository.class);
try {
doAnswer(
(Answer<Void>) invocation -> {
savedUser = (User) invocation.getArguments()[0];
return null;
})
.when(mockRepo)
.save(any(User.class));
} catch (Exception e) {
}
return mockRepo;
}
}
However, this doesn't add a lot of benefit in my opinion as you are interacting with the repository directly in the service unless you fully understand the complexity of a Spring Data Repository, you are after all also mocking networking I/O which is a dangerous thing to do
How do #Id annotations work?
What about Hibernate JPA interact with my Entitiy?
Do my column definitions on my Entitiy match what I would deploy against when
using something like Liquibase/Flyway to manage the database
migrations?
How do I test against any constraints the database might have?
How do I test custom transactional boundaries?
You're baking in a lot of assumptions, to that end you could use the #DataJpaTest documentation annotation that Spring Boot provides, or replicate the configuration. A this point I am assuming a Spring Boot application, but the same concept applies to Spring Framework applications you just need to setup the configurations etc. yourself.
#DataJpaTest
class BetterUserServiceTest {
private UserService userService;
#BeforeEach
void setup(#Autowired UserRepository userRepository) {
userService = new UserService(userRepository);
}
#Test
void saveUser() {
String name = "Steve";
String food = "Apple";
User savedUser = userService.newUser(name, food);
assertEquals(savedUser.getName(), name);
assertEquals(savedUser.getFood(), food);
}
}
In this example we've went a step further and removed any notion of mocking and are connecting to an in-memory database and verifying the user that is returned is not changed to what we saved.
Yet there are limitations with in-memory databases for testing, as we are normally deploying against something like MySQL, DB2, Postgres etc. where column definitions (for example) cannot accurately be recreated by an in-memory database for each "real" database.
We could take it a step further and use Testcontainers to spin up a docker image of a database that we would connecting to at runtime and connect to it within the test
#DataJpaTest
#Testcontainers(disabledWithoutDocker = true)
class BestUserServiceTest {
private UserService userService;
#BeforeEach
void setup(#Autowired UserRepository userRepository) {
userService = new UserService(userRepository);
}
#Container private static final MySQLContainer<?> MY_SQL_CONTAINER = new MySQLContainer<>();
#DynamicPropertySource
static void setMySqlProperties(DynamicPropertyRegistry properties) {
properties.add("spring.datasource.username", MY_SQL_CONTAINER::getUsername);
properties.add("spring.datasource.password", MY_SQL_CONTAINER::getPassword);
properties.add("spring.datasource.url", MY_SQL_CONTAINER::getJdbcUrl);
}
#Test
void saveUser() {
String name = "Steve";
String food = "Apple";
User savedUser = userService.newUser(name, food);
assertEquals(savedUser.getName(), name);
assertEquals(savedUser.getFood(), food);
}
}
Now we are accurately testing we can save, and get our user against a real MySQL database. If we took it a step further and introduced changelogs etc. those could also be captured in these tests.
I'm trying to test a service in my API that when given a certain id, it should return user that corresponds to that id. Pretty straightforward, but i'm getting the following error that should be simple to fix but have no idea how :
java.lang.AssertionError:
Expecting:
<User(id=89, name=null, email=null)>
and actual:
<Optional[User(id=89, name=null, email=null)]>
to refer to the same object
My test code is :
#RunWith(MockitoJUnitRunner.class)
public class ServiceDetailUserTest {
#Mock
private UserRepository userRepository;
#InjectMocks
private UserDetailService userDetailService;
#Test
public void when_given_id_it_should_return_user() {
User user = new User();
user.setId(89L);
when(userRepository.findById(user.getId())).thenReturn(Optional.of(user));
Optional<User> expected = userDetailService.listUser(user.getId());
assertThat(expected).isSameAs(user);
}
}
And my service code (not even sure if needed) is :
#Service
public class UserDetailService {
#Autowired
UserRepository repository;
public Optional<User> listUser(Long id) {
return repository.findById(id);
}
}
So, to compare my expected with my user, i need them to be the exact same type...but how?
I've seen variations of this test, with one using the expression assertThat(expected).isNotNull(); instead of assertThat(expected).isSameAs(user);, but i'm not sure if that's correct.
This should work:
#Test
public void when_given_id_it_should_return_user() {
User user = new User();
user.setId(89L);
Optional<User> userMock = Optional.of(user);
when(userRepository.findById(user.getId())).thenReturn(userMock);
Optional<User> expected = userDetailService.listUser(user.getId());
assertEquals(expected, userMock);
}
This compares two instances of different types, since expected is an Optional, and user is a User:
assertThat(expected).isSameAs(user);
Either unwrap expected.get(), or make user an Optional.
In my unit tests, I need to mock a data-model instance in a spring #Controller, else the return value of the #RequestMapping method gets wrong.
To do this I tried the following:
Create a User mock, which calls user.login() and needs to return "true"
Inject mock object in the LoginController
Stub the login method to return true
Perform POST /Login with MockMVC from spring test
verify that mockUser.login got called
Here is the controller method:
#RequestMapping(value = "/Login", method = RequestMethod.POST)
public String updateUI(Locale locale, Model model, #RequestParam("username") String username,
#RequestParam("hashedPW") String hashedPW, HttpServletRequest request) {
model.addAttribute("username", username);
user = new User(username, username, hashedPW.getBytes(), LoginHandler.getInstance());
boolean loginResult = user.login();
if(loginResult == true) {
return "profile";
}
String output = "Failed login (" + username + ") requested, locale = " + locale;
log(output);
return "home";
}
and my initialization of mock objects with injection:
#Mock
private User mockUser;
#InjectMocks
private LoginController injectedLoginController;
#Before
public void setup() throws ServletException {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(injectedLoginController).build();
LOGFILE = new File("logs/general.log");
}
and finally the unit test:
#Test
public void testLoginSuccess() throws Exception {
String username = "Stefan";
byte[] hashedPW = "".getBytes();
when(mockUser.login()).thenReturn(true);
ResultActions ra = mvc
.perform(post("/Login").param("username", username).param("hashedPW", hashedPW.toString()))
.andExpect(status().isOk());
verify(mockUser).login();
}
All together I expected the User object that is handled by the controller to be of mockUser type instead of User, and the login() method to get called once (accordingly) and return "true".
But all I get is
"Wanted but not invoked: mockUser.login()
Actually, there was zero interaction with this mock."
I appreciate any suggestions to solve my problem since I am working on this for quite some time now and I don't seem to get the trick.
1) This seems to be an IT test.. you should not force any injection.. spring does that:
#InjectMocks
private LoginController injectedLoginController;
2) You need to spy on your controller:
#SpyBean
private LoginController injectedLoginController;
3) You need to move the creation of the User to a package level method inside the controller:
user = createUser(username, username, hashedPW.getBytes(), LoginHandler.getInstance());
...
User createUser(...){
return new User(username, username, hashedPW.getBytes(), LoginHandler.getInstance());
}
4) Make that method return a mocked User:
doReturn(mockUser).when(injectedLoginController).createUser(...);
when(mockUser.login()).thenReturn(true);
If you don't want to change your code, you can take help from PowerMockito which can help to mock construction of new objects.
#RunWith(PowerMockRunner.class)
#PrepareForTest({User.class})
public class ControllerUnderTest {
// here User is class for which we want to mock object creation
}
Now, let's mock object
#Test
public void testLoginSuccess() throws Exception {
....
User userMock = PowerMockito.createMock(User.class);
PowerMockito.whenNew(User.class).withArguments(username, username, hashedPW.getBytes(), LoginHandler.getInstance()).thenReturn(userMock);
expect(userMock.login()).andReturn(true);
verify(mockUser).login();
...
}
For more details on powermock, please check this PowerMockito
I have a spring boot application which requires login for some actions. I am trying to test them using MockMvc, but it doesn't seem to work. I keep getting a HTTP response with status 403 (forbidden). Probably there is something wrong with the authentication part.
I have tried following the documentation, but I wasn't able to get it working.
This is my current testing code:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {Application.class})
#WebIntegrationTest("server.port = 8093")
public class PasswordChangeTests {
#Autowired
private EmbeddedWebApplicationContext webApplicationContext;
#Autowired
private UserRepository userRepository;
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
#Test
public void changePasswordWorks() throws Exception {
// Send password change request
PasswordChangeRepresentation passwordChange = new PasswordChangeRepresentation(DefaultUsers.Admin.getPassword(), "12345678");
mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/password/change")
.content(new ObjectMapper().writeValueAsString(passwordChange))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Check that the password has been changed
User user = this.userRepository.findByUsername(DefaultUsers.Admin.getEmail());
Assert.assertEquals(user.getPassword(), "12345678");
}
}
Sorry if I am missing something obvious. This is my first experience with spring boot.
You need to specify which user you want to run the test as. You have a few options (each option is a link to the detailed documentation):
#WithMockUser
This option will create a fake user (i.e. the user does not need to exist in a data store). The problem with this approach is if your application relies on a custom User implementation you may get class cast Exceptions. If you do not return a custom type from a custom UserDetailsService, then this solution should work fine.
#Test
#WithMockUser(username="admin",roles={"USER","ADMIN"})
public void changePasswordWorks() throws Exception {
#WithUserDetails
If you implemented a custom UserDetailsService that returns a custom implementation of UserDetails, this solution may work for you.
For it to work you need to expose a UserDetailsService as a Bean and the user must exist. For example:
#Test
#WithUserDetails("admin")
public void changePasswordWorks() throws Exception {
#WithSecurityContext
This is the best of both worlds, but requires a little additional setup. If you have a custom UserDetailsService returning a custom implementation of UserDetails and do NOT want the user to necessarily have to exist you can use this method. I'll let you read the documentation on this setup as it is a bit more lengthy and well documented.
Using a RequestPostProcessor
If annotations aren't your thing you can use a RequestPostProcessor. For example:
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
...
#Test
public void changePasswordWorks() throws Exception {
// Send password change request
PasswordChangeRepresentation passwordChange = new PasswordChangeRepresentation(DefaultUsers.Admin.getPassword(), "12345678");
mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/password/change")
// ADD this line
.with(user("admin").roles("USER","ADMIN"))
.content(new ObjectMapper().writeValueAsString(passwordChange))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Check that the password has been changed
User user = this.userRepository.findByUsername(DefaultUsers.Admin.getEmail());
Assert.assertEquals(user.getPassword(), "12345678");
}