mockito spy doesn't act as I expect - java

I'm trying to use spy mockito in my test. Here is my code:
#Spy
AddressServiceImpl service;
#InjectMocks
AddressController controller;
#Test
void loadAddresses(){
User user = new User();
Address address1 = new Address(user,"2345", "5678", "7890", "test#gmail.com", "street");
Address address2 = new Address(user,"9876", "7654", "6543", "test2#gmail.com", "avenue");
service.save(address1);
service.save(address2);
List<Address> searchAdress = new ArrayList<>();
given(service.findByEmailContaining(anyString())).willCallRealMethod();
searchAdress = controller.loadAddress(address1);
}
And in my controller:
private AddressService addressService;
public List<Address> loadAddress(Address address){
List<Address> theAddresses = new ArrayList<>();
theAddresses = addressService.findByEmailContaining("%"+ address.getEmail() + "%");
return theAddresses;
}
I expect that controller searches in my saved addresses(address1,address2) by address1.getEmail() and returns the address1 object. but it dosen't return any thing.
In fact service.save(address1) retuurn null object instead of adress1.
this method call save method from JPA repository.

Related

How to mock repository to perform the flush() method

I am trying to write a test of a service method. Most of the logic performed in their is covered by tests of those methods. I am mostly trying to see if the correct repository calls are being performed.The method returns the id of the receipt/bon it just created.
I can train the mocks of the repository with the calls being performed in the service. But my test keeps failing, because the service call is unable to return an id value (long). This is because the id is generated by performing the save method followed by the flush. I cannot seem to train my mocks to do this right.
This is the only error eccuring, that it cannot perform the service call, because it returns a null value instead of an id.
How can I mock the repository correct so testing my method will not fail on not having an id?
method:
#Override
#Transactional
public long addBonAndProducts(Boninfo boninfo) {
Consignatiebon bon = new Consignatiebon(boninfo.getGebruiker(), LocalDate.now(), boninfo.getOpmbon(), boninfo.getSolden());
LocalDate dateUit = this.createCorrectDateOut(bon.getDatumIn(), bon.getSolden());
bon.setDatumUit(dateUit);
//creates correct bonnr - logic tested elswhere
String currentLetterBon = this.findCurrentLetter();
Integer numberToInsert = this.findMostRecentBoncode(currentLetterBon);
bon.setBonCode(currentLetterBon, (numberToInsert + 1));
consignatiebonRepository.save(bon);
consignatiebonRepository.flush();
for(var product:boninfo.getLijstproducten()) {
product.setConsignatiebon(bon);
if(!(product.getStatus()==Status.STOCK)) {
product.setDatumUit(dateUit);
}
//creates correct articlenr - logi tested elswhere
String currentLetter = this.findCurrentLetter();
Integer numberToInsertBon = this.findMostRecentArtikelcode(currentLetter);
product.setArtikelCode(currentLetter, (numberToInsertBon + 1));
productRepository.save(product);
productRepository.flush();
long idProduct = product.getProductId();
bon.add(product);
}
consignatiebonRepository.save(bon);
consignatiebonRepository.flush();
bon.setTotalPieces();
bon.setTotalValueBon();
// these values are correct
System.out.println("inside function pieces: " + bon.getTotalPieces());
System.out.println("inside function pieces: " + bon.getTotalPrice());
consignatiebonRepository.save(bon);
// in the test, this is outputted as null, cause the flush method doesn't get performed
System.out.println("inside function pieces: " + bon.getIdConsignatiebon());
return bon.getIdConsignatiebon();
}
test:
#ExtendWith(MockitoExtension.class)
class ProductServiceTest {
private DefaultProductService productService;
private Kleur kleur;
private Maat maat;
private Merk merk;
private Eigenschap eigenschap;
private Product product;
private Product productTwo;
private Product productThree;
private Adres adres;
private Gebruiker gebruiker;
private Consignatiebon consignatiebon;
private Consignatiebon consignatiebonToFill;
#Mock
private ProductRepository productRepository;
#Mock
private GebruikerRepository gebruikerRepository;
#Mock
private ConsignatiebonRepository consignatiebonRepository;
#Mock
private WoocommerceApi woocommerceApi;
#Mock
private Mailing mailing;
#BeforeEach
void beforeEach() {
productService = new DefaultProductService(productRepository, consignatiebonRepository, gebruikerRepository,
woocommerceApi, mailing);
kleur = new Kleur("testkleur");
maat = new Maat("testmaat");
merk = new Merk("testmerk");
eigenschap = new Eigenschap("testclustereigenschap", "testsubeigenschap");
adres = new Adres("teststraat", "testhuisnummer", "testpostcode", "testgemeente", "testland");
gebruiker = new Gebruiker("testvoornaam","testnaam", "testriziv", "testmail#hotmail.be", true,
"testtelefoonnr", adres, Gebruikersrol.TESTLEVERANCIER, "testopmerking");
consignatiebon = new Consignatiebon(gebruiker, LocalDate.of(2020, 1, 1), "testopmerking", true);
product = new Product(gebruiker, consignatiebon, eigenschap, kleur, merk, maat, Soort.DAMES,
"testbeschrijving", BigDecimal.valueOf(10), BigDecimal.valueOf(25), Status.TEKOOP, false, true);
productTwo = new Product(gebruiker, consignatiebon, eigenschap, kleur, merk, maat, Soort.DAMES,
"testbeschrijvingTwo", BigDecimal.valueOf(10), BigDecimal.valueOf(25), Status.TEKOOP, false, true);
productThree = new Product(gebruiker, consignatiebon, eigenschap, kleur, merk, maat, Soort.DAMES,
"testbeschrijvingThree", BigDecimal.valueOf(10), BigDecimal.valueOf(25), Status.TEKOOP, false, true);
}
#Test
void addBonAndProducts() {
when(consignatiebonRepository.save(Mockito.any(Consignatiebon.class))).thenAnswer(i -> i.getArguments()[0]);
when(productRepository.save(Mockito.any(Product.class))).thenAnswer(i -> i.getArguments()[0]);
// when(productService.addBonAndProducts(Mockito.any(Boninfo.class))).thenReturn(1L);
List<Product> productlist = new ArrayList<>();
productlist.add(product);
productlist.add(productTwo);
productlist.add(productThree);
Boninfo testboninfo = new Boninfo(productlist, gebruiker, "testopmerkingbon", true);
productService.addBonAndProducts(testboninfo);
verify(consignatiebonRepository, times(3)).save(consignatiebon);
verify(productRepository, times(1)).save(product);
verify(productRepository, times(1)).save(productTwo);
verify(productRepository, times(1)).save(productThree);
}
}

Spring Controller Test - object in controller is null

I try to test a controller and have a problem with an object City c = cityService.findByID(city); It is always null when I run the test. If I run the program and not the test it works as it should.
City c shouldn't be null because it is an object which should be fetched from DB by city id of last selected city(option from dropdown list) and I pass the city id here: .param("city", String.valueOf(306)).
void selectCityTest() throws Exception { //post
Integer voivodeship = 10;
Integer city = 306;
List<City> cities = cityService.getAllCitiesByVoivodeship(voivodeship);
mockMvc.perform(MockMvcRequestBuilders.post("/select_city")
.contentType(MediaType.APPLICATION_JSON)
.param("city", String.valueOf(306))
.content(new Gson().toJson(cities)))
.andExpect(status().isOk());
}
Controller.java
#RequestMapping(value = "/select_city", method = RequestMethod.POST)
public String selectCity(Integer city, Model model) {
City c = cityService.findByID(city);
List<City> cities = cityService.getAllCitiesByVoivodeship(c.getVoivodeship().getId());
model.addAttribute("cities", cities);
model.addAttribute("city_selected", city);
return "taxoffice";
}

Unable to mock accountStatus with Mockito

From below piece of code I am not able to mock checkAccountStatus and its coming as null. What changes do I need to do to resolve this issue?
Class
public AccessIDSearchResponse searchAccessID(AccessIDSearchRequest accessIDRequest) {
String[] productTypes = accessIDRequest.getProductTypes();
AccountResponse actResponse = checkAccountStatus(accessIDRequest);
System.out.println("Response is---->"+JsonService.getJsonFromObject(actResponse));
if (accessIDRequest.getSearchtype().equalsIgnoreCase("accountId") && !Utility.isEmpty(actResponse)
&& !"FREEVIEW".equalsIgnoreCase(actResponse.getAccountStatus())) {
errorHandler.error(ErrorMessages.EPO_EXISTINGTV_ERR_07, ErrorMessages.ACCESS_ID_NOT_FOUND);
}
}
public AccountResponse checkAccountStatus(AccessIDSearchRequest request) {
AccessIDSearchResponse response = new AccessIDSearchResponse();
SearchAccessIdContent content = new SearchAccessIdContent();
DTVNAccountDetails accountDetails = new DTVNAccountDetails();
accountDetails.setAccountNumber(request.getSearchvalue());
List<DTVNAccountDetails> list = new ArrayList<>();
list.add(accountDetails);
content.setDtvAccountList(list);
response.setContent(content);
return helper.getAccountStatus(response);
}
Helper
public AccountResponse getAccountStatus(AccessIDSearchResponse accessIDResponse) {
AccountResponse accountResponse = null;
AccountRequest request = new AccountRequest();
Account account = new Account();
account.setCustomerID(accessIDResponse.getContent().getDtvAccountList().get(0).getAccountNumber());
request.setAccount(account);
String response = dtvnClients.callandGetDtvnStatus(request);
System.out.println("Response is--->"+response);
if (!Utility.isEmpty(response)) {
accountResponse = JqUtil.runJqQueryAndGetString(".content.accountResponse", response,
AccountResponse.class);
if (!Utility.isEmpty(accountResponse) && accountResponse.isSubscribable()
&& !Utility.isEmpty(accountResponse.getAccountStatus())
&& accountResponse.getAccountStatus().equalsIgnoreCase("FREEVIEW")) {
return accountResponse;
}
}
return accountResponse;
}
Test Class
#Test(expected = ServiceException.class)
public void test_searchAccessID_3_sample() throws Exception {
AccessIDSearchRequest request = new AccessIDSearchRequest();
CommonData commonData = new CommonData();
commonData.setAppName("IDSE");
commonData.setLoginId("qay_slid_sr1281");
request.setCommonData(commonData);
request.setSearchtype("accountId");
request.setSearchvalue("qay_slid_sr1281");
request.setMode("abc");
SearchAccessIdContent content = new SearchAccessIdContent();
AccountResponse accountResponse = new AccountResponse();
accountResponse.setAccountStatus("Sucess");
accountResponse.setSubscribable(true);
Mockito.when(helper.getAccountStatus(accessIDResponse)).thenReturn(accountResponse);
Mockito.when(service.checkAccountStatus(request)).thenReturn(accountResponse);
service.searchAccessID(header, request);
}
Your mocks are not properly configured.
When you call
service.searchAccessID(header, request);
it was make the underlying call
checkAccountStatus(request);
(which is correctly mocked and returns accountResponse), but this one does instanciate its result object, so your first mock will never be triggered.
Updating your first mock to something more permissive will probably fix your problem
Mockito.when(helper.getAccountStatus(any(AccessIDSearchResponse.class))).thenReturn(accountResponse);
To be honest, your code is hardly testable because you instanciate too many objects everywhere. Going for mocks here will be a pain in the future when you refactor something. If I were you I would rewrite this piece of code using a TDD approach and favorizing more testable patterns.

Replacing a Mocked Spring Boot Controller with the actual Controller

I'm new to Spring Boot and Testing.
tl;dr How do I replace a #MockBean controller with the actual controller, in a spring boot application so that I can test that the controller is working instead of just testing that my objects are output correctly?
I'm writing a gradle managed API with dependencies (from build.gradle):
// Spring Boot (2.0.5 Release)
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-hateoas')
compile('org.springframework.boot:spring-boot-starter-web')
runtime('org.springframework.boot:spring-boot-devtools')
// Testing
testImplementation('org.junit.jupiter:junit-jupiter-api:5.3.1')
testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.3.1')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile("org.assertj:assertj-core:3.11.1")
testCompile 'org.mockito:mockito-core:2.+'
I've got an API controller class with the following relevant code:
#Controller
public class ObjectivesApiController extends AbstractRestHelperFunctionality implements ObjectivesApi {
protected ObjectivesApiController(
UserRepository userRepository,
CompaniesRepository companiesRepository,
TeamsRepository teamsRepository,
ProjectsRepository projectsRepository,
OdiAssessmentRepository odiAssessmentRepository,
OdiCustomerRatingRepository odiCustomerRatingRepository,
OdiTechRatingRepository odiTechRatingRepository,
OdiValueRatingRepository odiValueRatingRepository,
ObjectivesRepository objectivesRepository,
KeyResultRepository keyResultRepository) {
super(
userRepository,
companiesRepository,
teamsRepository,
projectsRepository,
odiAssessmentRepository,
odiCustomerRatingRepository,
odiTechRatingRepository,
odiValueRatingRepository,
objectivesRepository,
keyResultRepository);
}
public ResponseEntity<KeyResult> createKeyResult(#ApiParam(value = "id", required = true) #PathVariable("id") Long id, #ApiParam(value = "keyResult", required = true) #Valid #RequestBody KeyResult keyResultDTO) {
KeyResult keyResult = KeyResultBuilder
.aKeyResult()
.withDescription(keyResultDTO.getDescription())
.withCompleted(keyResultDTO.getCompleted())
.build();
Objective parentObjective = objectivesRepository.findByObjectiveId(id);
parentObjective.addKeyResult(keyResult);
keyResultRepository.save(keyResult);
objectivesRepository.save(parentObjective);
return new ResponseEntity<KeyResult>(HttpStatus.CREATED);
}
public ResponseEntity<Objective> createObjective(#ApiParam(value = "objective", required = true) #Valid #RequestBody Objective objectiveDTO) {
Objective objective = ObjectiveBuilder
.anObjective()
.withDescription(objectiveDTO.getDescription())
.withCompleted(objectiveDTO.getCompleted())
.withKeyResults(objectiveDTO.getKeyResults())
.build();
objective.getKeyResults().forEach(keyResultRepository::save);
objectivesRepository.save(objective);
return new ResponseEntity<Objective>(HttpStatus.CREATED);
}
public ResponseEntity<Void> deleteAllLinkedKeyResults(#ApiParam(value = "id", required = true) #PathVariable("id") Long id) {
Objective subjectObjective = objectivesRepository.findByObjectiveId(id);
subjectObjective.getKeyResults().clear();
objectivesRepository.save(subjectObjective);
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
public ResponseEntity<Void> deleteObjective(#ApiParam(value = "id", required = true) #PathVariable("id") Long id) {
objectivesRepository.delete(objectivesRepository.findByObjectiveId(id));
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
public ResponseEntity<Void> deleteOneKeyResult(#ApiParam(value = "the id of the objective you want key results for", required = true) #PathVariable("objectiveId") Long objectiveId, #ApiParam(value = "the id of the key result", required = true) #PathVariable("keyResultId") Long keyResultId) {
Objective subjectObjective = objectivesRepository.findByObjectiveId(objectiveId);
KeyResult keyResult = keyResultRepository.findByKeyResultId(keyResultId);
subjectObjective.removeKeyResult(keyResult);
objectivesRepository.save(subjectObjective);
keyResultRepository.delete(keyResult);
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
public ResponseEntity<List<Objective>> getAllObjectives() {
List<Objective> allObjectives = objectivesRepository.findAll();
return new ResponseEntity<List<Objective>>(allObjectives, HttpStatus.OK);
}
public ResponseEntity<List<KeyResult>> getKeyResultsForObjective(#ApiParam(value = "id", required = true) #PathVariable("id") Long id) {
Objective subjectObjective = objectivesRepository.findByObjectiveId(id);
List<KeyResult> allKeyResults = subjectObjective.getKeyResults();
return new ResponseEntity<List<KeyResult>>(allKeyResults, HttpStatus.OK);
}
public ResponseEntity<Objective> getObjective(#ApiParam(value = "id", required = true) #PathVariable("id") Long id) {
Objective subjectObjective = objectivesRepository.findByObjectiveId(id);
return new ResponseEntity<Objective>(subjectObjective, HttpStatus.OK);
}
public ResponseEntity<KeyResult> getKeyResultForObjective(#ApiParam(value = "the id of the objective you want key results for", required = true) #PathVariable("objectiveId") Long objectiveId, #ApiParam(value = "the id of the key result", required = true) #PathVariable("keyResultId") Long keyResultId) {
Objective subjectObjective = objectivesRepository.findByObjectiveId(objectiveId);
KeyResult subjecKeyResult = subjectObjective.getKeyResults().stream()
.filter(KeyResult -> keyResultId.equals(KeyResult.getKeyResultId()))
.findFirst()
.orElse(null);
return new ResponseEntity<KeyResult>(subjecKeyResult, HttpStatus.OK);
}
public ResponseEntity<Objective> updateObjective(#ApiParam(value = "id", required = true) #PathVariable("id") Long id, #ApiParam(value = "objective", required = true) #Valid #RequestBody Objective objectiveDTO) {
Objective existingObjective = objectivesRepository.findByObjectiveId(id);
Objective objective = ObjectiveBuilder
.anObjective()
.withObjectiveId(existingObjective.getObjectiveId())
.withDescription(objectiveDTO.getDescription())
.withCompleted(objectiveDTO.getCompleted())
.withKeyResults(objectiveDTO.getKeyResults())
.build();
objective.getKeyResults().forEach(keyResultRepository::save);
objectivesRepository.save(objective);
return new ResponseEntity<Objective>(HttpStatus.NO_CONTENT);
}
public ResponseEntity<KeyResult> updateKeyResult(#ApiParam(value = "the id of the objective you want key results for", required = true) #PathVariable("objectiveId") Long objectiveId, #ApiParam(value = "the id of the key result", required = true) #PathVariable("keyResultId") Long keyResultId, #ApiParam(value = "keyResult", required = true) #Valid #RequestBody KeyResult keyResultDTO) {
if (objectivesRepository.existsById(objectiveId) && keyResultRepository.existsById(keyResultId)) {
Objective subjectObjective = objectivesRepository.findByObjectiveId(objectiveId);
KeyResult subjecKeyResult = subjectObjective.getKeyResults().stream()
.filter(KeyResult -> keyResultId.equals(KeyResult.getKeyResultId()))
.findFirst()
.orElse(null);
KeyResult updatedKeyResult = KeyResultBuilder
.aKeyResult()
.withKeyResultId(subjecKeyResult.getKeyResultId())
.withDescription(keyResultDTO.getDescription())
.withCompleted(keyResultDTO.getCompleted())
.build();
keyResultRepository.save(updatedKeyResult);
Collections.replaceAll(subjectObjective.getKeyResults(), subjecKeyResult, updatedKeyResult);
objectivesRepository.save(subjectObjective);
}
return new ResponseEntity<KeyResult>(HttpStatus.NO_CONTENT);
}
}
For context on this class, all the AbstractRestHelper super class is doing, is creating singletons of my repositories, which are then .. field injected (unsure if this is the right term) in to the controller. This pattern is repeated across all controllers hence the clutter.
The API being implemented is a Swagger 2 API interface that keeps this controller free of annotations where possible.
The final piece is the test class. This is the core of my question.
#ExtendWith(SpringExtension.class)
#WebMvcTest(ObjectivesApiController.class)
class ObjectivesApiControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private ObjectivesApiController objectivesApiControllerMock;
#BeforeEach
void setUp() {
}
#AfterEach
void tearDown() {
}
#Test
void getAllObjectives() throws Exception {
// Create two objects to test with:
Objective testObjective1 = ObjectiveBuilder
.anObjective()
.withObjectiveId(1L)
.withDescription("Test Objective")
.withCompleted(false)
.build();
Objective testObjective2 = ObjectiveBuilder
.anObjective()
.withObjectiveId(2L)
.withDescription("Test Objective")
.withCompleted(true)
.build();
List<Objective> testList = new ArrayList<Objective>();
testList.add(testObjective1);
testList.add(testObjective2);
// Set expectations on what should be found:
when(objectivesApiControllerMock.getAllObjectives()).thenReturn(new ResponseEntity<List<Objective>>(testList, HttpStatus.OK));
// Carry out the mocked API call:
mockMvc.perform(get("/objectives"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].objectiveId", is(1)))
.andExpect(jsonPath("$[0].description", is("Test Objective")))
.andExpect(jsonPath("$[0].completed", is(false)))
.andExpect(jsonPath("$[1].objectiveId", is(2)))
.andExpect(jsonPath("$[1].description", is("Test Objective")))
.andExpect(jsonPath("$[1].completed", is(true)));
// Validate the response is what we expect:
verify(objectivesApiControllerMock, times(1)).getAllObjectives();
verifyNoMoreInteractions(objectivesApiControllerMock);
}
#Test
void getKeyResultsForObjective() throws Exception {
KeyResult testKeyResultWithParentObjective1 = KeyResultBuilder
.aKeyResult()
.withKeyResultId(1L)
.withCompleted(false)
.withDescription("My parent Key Result is 1")
.build();
KeyResult testKeyResultWithParentObjective2 = KeyResultBuilder
.aKeyResult()
.withKeyResultId(2L)
.withCompleted(true)
.withDescription("My parent Key Result is 1")
.build();
Objective testObjectiveWithKeyResults = ObjectiveBuilder
.anObjective()
.withObjectiveId(1L)
.withDescription("Test Objective")
.withKeyResults(new ArrayList<KeyResult>())
.withCompleted(false)
.build();
testObjectiveWithKeyResults.addKeyResult(testKeyResultWithParentObjective1);
testObjectiveWithKeyResults.addKeyResult(testKeyResultWithParentObjective2);
when(objectivesApiControllerMock.getKeyResultsForObjective(1L)).thenReturn(new ResponseEntity<List<KeyResult>>(testObjectiveWithKeyResults.getKeyResults(), HttpStatus.OK));
mockMvc.perform(get("/objectives/1/keyresult"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].keyResultId", is(1)))
.andExpect(jsonPath("$[0].description", is("My parent Key Result is 1")))
.andExpect(jsonPath("$[0].completed", is(false)))
.andExpect(jsonPath("$[1].keyResultId", is(2)))
.andExpect(jsonPath("$[1].description", is("My parent Key Result is 1")))
.andExpect(jsonPath("$[1].completed", is(true)));
}
}
My question is this:
Having mocked the objective controller using Mockito to validate that my objects are being formed properly, I now want to do the same thing but instead of mocking, I want to actually test the controller.
What do you think is the most naive way of getting this to work (I can refactor later). The resources I've search through either use different versions of Junit or rely on mockito rather than the actual controller.
Nothing fits quite right - since the controller is mocked, I'm not actually covering any code, and so the tests are worthless right? The only thing I'm looking at is that the objects are formed properly, where I now need to check that the controller is functioning as it should, AND are returning well formed objects.
Has anyone done anything simillar? What approaches do you use to manage the testing of field injected controllers?
Any advice on this would be hugely appreciated. I'd love to learn how people working on production grade applications are handling the testing of Spring Boot Apps with Controllers, Repos, etc.
Thanks so much!
You could use #SpyBean. That way you can both use it as it is or mock some calls. https://www.baeldung.com/mockito-spy

Unit Tests Junit NullPointerException and NoSuchElement help! Rest endpoints

When I am accessing my class to test the methods, I am getting exceptions every time I try to define a new object and use the newly defined object.
Tests in error:
UserInformationControllerTest.deleteUser:83 » NullPointer
UserInformationControllerTest.getUserInfo:27 » NullPointer
UserInformationControllerTest.updateUserInfo:68 » NullPointer
UserOrderControllerTest.createUserOrder:60 » NoSuchElement
UserOrderControllerTest.getUserOrder:47 » NullPointer
UserOrderControllerTest.updateUserOrder:85 » NullPointer
My assignment is to make 4 happy cases and 4 unhappy cases for each class
I am thoroughly confused.
My test class for UserInformation
private HashMap<Integer,UserInformation> userInformationHashMap;
#Test
public void getUserInfo(){
UserInformationController userInformationController = new UserInformationController();
this.userInformationHashMap = new HashMap<>();
int user0 = 0;
int user1 = 1;
UserInformation userInformation0 = new UserInformation("Doug","Jones", "djones#gmail.com","17073");
UserInformation userInformation1 = new UserInformation("Natalie","Peirce", "nataliepeirce12#yahoo.com","dynamicrabbit");
this.userInformationHashMap.put(user0,userInformation0);
this.userInformationHashMap.put(user1,userInformation1);
userInformationController.getUserInfo(user0);
userInformationController.getUserInfo(user1);
Assert.assertEquals(userInformationController.getUserInfo(user0),userInformationController.getUserInfo(user1)); //False
Assert.assertNotEquals(user0,user1); //True
}
#Test
public void createUser(){
UserInformationController userInformationController = new UserInformationController();
this.userInformationHashMap = new HashMap<>();
UserInformation userInformation0 = new UserInformation("Troy","Green","tjg217#verizon.com","2012hummingbirds");
UserInformation userInformation1 = new UserInformation("Sierra", "West","themostimportantwest#msn.com","shadeyglasses77");
int user0 = userInformationController.createUser(userInformation0);//Can you tell me why this does not work
int user1 = userInformationController.createUser(userInformation1);//Can you tell me why this does not work
this.userInformationHashMap.put(user0, userInformation0);
this.userInformationHashMap.put(user1, userInformation1);
Assert.assertNotEquals(this.userInformationHashMap.get(user0),this.userInformationHashMap.get(user1)); //True
Assert.assertNotNull(this.userInformationHashMap.get(user0)); //False
}
#Test
public void updateUserInfo(){
UserInformationController userInformationController = new UserInformationController();
this.userInformationHashMap = new HashMap<>();
int userId = 0;
UserInformation userInformation = new UserInformation("Nicole", "Rigby", "sexygirl69#babellon.com","throwmethemoney");
UserInformation newUserInformation = new UserInformation("Kitty", "Morgan", "ilovecats#cats.com","cats");
this.userInformationHashMap.put(userId,userInformation);
Assert.assertEquals(this.userInformationHashMap.get(userId),userInformation); //True
userInformationController.updateUserInfo(userId,newUserInformation); //Can you tell me why this does not work
Assert.assertNotEquals(this.userInformationHashMap.get(userId),newUserInformation); //False
}
#Test
public void deleteUser(){
UserInformationController userInformationController = new UserInformationController();
this.userInformationHashMap = new HashMap<>();
int user = 0;
UserInformation userInformation = new UserInformation("Camryn","Resele","smartcookie#email.com","28564088");
this.userInformationHashMap.put(user,userInformation);
userInformationController.deleteUser(user);
Assert.assertNull(this.userInformationHashMap.get(user)); //True
Assert.assertTrue(this.userInformationHashMap.containsKey(user)); //False
}
}
UserInformationController
private HashMap<Integer,UserInformation> userInformationHashMap;
/**
* Default json constructor`enter code here`
* #return new user object
*/
#GetMapping(path = "/defaultUserInformation")
public UserInformation test()
{
return new UserInformation("fname", "lname", "email", "pass");
}
/**
* Gets the users information
* #return users information
*/
#GetMapping (path = "/userInfo")
public UserInformation getUserInfo(#RequestParam ("id") int id){
return userInformationHashMap.get(id);
}
/**
* Sets the users information
* #param userInformation userInformation model
* #return users key
*/
#PostMapping (path = "/createUser")
public int createUser(#RequestBody UserInformation userInformation){
if(this.userInformationHashMap == null){
this.userInformationHashMap = new HashMap<>();
}
int maxKey = 0;
if(this.userInformationHashMap.size() != 0){
maxKey = Collections.max(this.userInformationHashMap.keySet()) + 1;
}
this.userInformationHashMap.put(maxKey,userInformation);
return maxKey;
}
#PutMapping (path = "/updateUserInfo")
public void updateUserInfo(#RequestParam ("id") int id, #RequestBody UserInformation userInformation) {
if (this.userInformationHashMap.containsKey(id)) {
this.userInformationHashMap.put(id, userInformation);
}
}
#DeleteMapping (path = "/deleteUser")
public void deleteUser(#RequestParam ("id") int id){
this.userInformationHashMap.remove(id);
}
}
userInformationHashMap within UserInformationController is never initialized, this is why you're getting the NullPointerExceptions.
You're initializing the HashMap in the createUser endpoint and it's never being called within the test.
The createUser endpoint I can't see where it's failing, but anyway this code should really be reorganized because it has many points of failure. The HashMapshould really be initialized when the Bean is created, and you should revisit the way you are calculating the Key.
Also for Controller testing purposes, you should be using MockMvc instead of calling controller methods directly.

Categories