Thrus - srujanabala/springboot-couchbase GitHub Wiki

package org.axp.springbootcouchbase.mvc.service;

import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.ArrayList; import java.util.List; import java.util.Optional;

import org.axp.springbootcouchbase.mvc.model.Student; import org.axp.springbootcouchbase.mvc.repository.UserRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult;

import com.couchbase.client.core.utils.yasjl.JsonArrayByteBufProcessor; import com.couchbase.client.deps.com.fasterxml.jackson.databind.ObjectMapper; import com.couchbase.client.java.document.json.JsonArray;

import net.minidev.json.JSONArray;

@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc(secure = false) @ActiveProfiles("playground") public class ViewControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserRepository userRepository;

@InjectMocks
private ViewController viewController;

List<Student> students = new ArrayList<>();

@Before
public void setup() {
	MockitoAnnotations.initMocks(this);
	Student student = new Student("101", "Sapthika", 2);
	students.add(student);
	Student student2 = new Student("101", "Sapthika", 2);
	students.add(student2);
}

@Test
public void testAddNew() throws Exception {
	doNothing().when(userRepository).deleteAll();
	when(userRepository.save(Mockito.any())).thenReturn(new Student("101", "Sapthika", 2));
	MvcResult result = this.mockMvc
			.perform(get("/add"))
			.andExpect(status().isOk())
			.andDo(print())
			.andReturn();
	System.out.println(result.getResponse());
	verify(userRepository,times(1)).deleteAll();
	verify(userRepository,times(5)).save(Mockito.any());
}

@Test
public void testFetchRecords() throws Exception {
	when(userRepository.findAll()).thenReturn(students);
	//userRepository.findAll().forEach(System.out::println);
	MvcResult result = this.mockMvc
							.perform(get("/get"))
							.andExpect(status().isOk())
							.andDo(print())
							.andReturn();
	System.out.println(result.getResponse());

}

@Test
public void testFetchByName() throws Exception {
	String name ="Abhishek";
	when(userRepository.findByName(name)).thenReturn(students);
	
	MvcResult result = this.mockMvc
							.perform(get("/get/"+name))
							.andExpect(status().isOk())
							.andDo(print())
							.andReturn();
	
	JSONArray jsonArray = new JSONArray();
	System.out.println(result.getResponse());

}

@Test
public void testFetchByQuery() throws Exception {
	when(userRepository.findByTheQuery(Mockito.anyString())).thenReturn(students);
	String name ="Abhishek";
	MvcResult result = this.mockMvc
							.perform(get("/get/"+name))
							.andExpect(status().isOk())
							.andDo(print())
							.andReturn();
	assertNotNull(result.getResponse().getContentAsString());
	assertEquals("101", result.getResponse().getContentAsString());
	
	//JSONArray jsonArray = new JSONArray(students);
	//JsonArray jsonArray = new JsonArray(students);
	//System.out.println(result.getResponse());

}

@Test
public void testDel() throws Exception {
	doNothing().when(userRepository).deleteAll();
	doNothing().when(userRepository).deleteById(Mockito.anyString());
	MvcResult result = this.mockMvc
			.perform(delete("/del"))
			.andExpect(status().isOk())
			.andDo(print())
			.andReturn();
	System.out.println(result.getResponse());
	verify(userRepository,times(1)).deleteAll();
	verify(userRepository,times(1)).deleteById("101");
}

@Test
public void testIpFromHostname() throws Exception {
	String ip ="127.0.0.1";
	MvcResult result = this.mockMvc
							.perform(get("ip-from-hostname/"+ip))
							.andExpect(status().isOk())
							.andDo(print())
							.andReturn();
	assertNotNull(result.getResponse().getContentAsString());
}

@Test
public void testIpFromHostnameUnknownHostException() throws Exception {
	String ip ="127";
	MvcResult result = this.mockMvc
							.perform(get("ip-from-hostname/"+ip))
							.andExpect(status().isBadRequest())
							.andDo(print())
							.andReturn();
	assertNotNull(result.getResponse().getErrorMessage());
}

@Test
public void testPost()throws Exception{
	when(userRepository.save(Mockito.any())).thenReturn(new Student("101", "Sapthika", 2));
	ObjectMapper mapper = new ObjectMapper();
	MvcResult result = this.mockMvc
			.perform(post("/students").contentType(MediaType.APPLICATION_JSON_VALUE).content(
					mapper.writeValueAsString(new Student("101", "Sapthika", 2))))				
			.andExpect(status().isCreated()).andReturn();
	assertNotNull(result.getRequest());
}

@Test
public void testPut()throws Exception{
	Student student =new Student("101", "Abhishek", 2);
	when(userRepository.findById(Mockito.anyString())).thenReturn(Optional.ofNullable(student));
	when(userRepository.save(Mockito.any())).thenReturn(new Student("101", "Abhishek", 2));
	String id ="101";
	MvcResult result = this.mockMvc
			.perform(put("/students/"+id).contentType(MediaType.APPLICATION_JSON_VALUE))				
			.andExpect(status().isOk())
			.andDo(print())
			.andReturn();
	assertNotNull(result.getRequest());
}

@Test
public void testPutDataNotFound()throws Exception{
	when(userRepository.findById(Mockito.anyString())).thenReturn(Optional.ofNullable(null));
	String id ="101";
	MvcResult result = this.mockMvc
			.perform(put("/students/"+id).contentType(MediaType.APPLICATION_JSON_VALUE))				
			.andExpect(status().isOk())
			.andDo(print())
			.andReturn();
	assertNull(result.getResponse().getContentAsString());
}

@Test
public void testHostnameFromIp() {
	String test = viewController.hostnameFromIp("127.0.0.1");
	assertNotNull(test);		
}

@Test
public void testAddNewMethod() {
	doNothing().when(userRepository).deleteAll();
	when(userRepository.save(Mockito.any())).thenReturn(new Student("101", "Sapthika", 2));
	List<Student> list = viewController.addNew();
	assertNotNull(list);
	assertFalse(list.isEmpty());
	assertEquals(5, list.size());
	verify(userRepository,times(1)).deleteAll();
	verify(userRepository,times(5)).save(Mockito.any());
	verify(userRepository,times(1)).findAll();
}


@Test
public void testDelMethod() throws Exception {
	doNothing().when(userRepository).deleteAll();
	doNothing().when(userRepository).deleteById(Mockito.anyString());
	viewController.del();
	verify(userRepository,times(1)).deleteAll();
	verify(userRepository,times(1)).deleteById("101");
}

@Test
public void testFetchRecordsMethod() throws Exception {
	when(userRepository.findAll()).thenReturn(students);
	List<Student> list = viewController.fetchRecords();
	assertNotNull(list);
	assertFalse(list.isEmpty());
	assertEquals(2, list.size());
	verify(userRepository,times(1)).findAll();
}

@Test
public void testGetCount() throws Exception {
	when(userRepository.count()).thenReturn((long) 5);
	long count = viewController.getCount();
	assertEquals(5, count);
	verify(userRepository,times(1)).findAll();
}

}

———————————————————————————————-

View controller.java ———————————————————————————

package org.axp.springbootcouchbase.mvc.service;

import java.util.ArrayList; import java.util.List; import java.util.Optional;

import org.axp.springbootcouchbase.mvc.model.Student; import org.axp.springbootcouchbase.mvc.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;

@RestController @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class ViewController {

@Autowired
private UserRepository userRepo;

@RequestMapping(path = "/add", method = RequestMethod.GET)
public List<Student> addNew() {
	userRepo.deleteAll();
	Student s = new Student("8", "Abhishek", 30);
	Student s2 = new Student("64", "Alex", 35);
	Student s3 = new Student("80", "John", 40);
	Student s4 = new Student("88", "Shankle", 44);
	Student s5 = new Student("45", "jackie", 45);
	userRepo.save(s);
	userRepo.save(s2);
	userRepo.save(s3);
	userRepo.save(s4);
	userRepo.save(s5);
	System.out.println("finished ass");
	List<Student> list = new ArrayList<>();
	userRepo.findAll().forEach(list::add);
	return list;
}

@DeleteMapping("/del")
// @RequestMapping(path = "/del", method = RequestMethod.DELETE)
public void del() {
	userRepo.deleteAll();
}

@DeleteMapping("/del/{id}")
// @RequestMapping(path = "/del", method = RequestMethod.DELETE)
public void delById(@PathVariable("id") String id) {
	userRepo.deleteById(id);
}

@RequestMapping(path = "/get", method = RequestMethod.GET, produces = "application/json")
public List<Student> fetchRecords() {
	System.out.println("From controller");
	List<Student> list = new ArrayList<>();
	userRepo.findAll().forEach(list::add);
	// userRepo.findAll().forEach(System.out::println);
	return list;
}

@RequestMapping(path = "/get/{name}", method = RequestMethod.GET, produces = "application/json")
public List<Student> fetchByName(@PathVariable("name") String name) {
	System.out.println("inside get");
	return userRepo.findByName(name);
}

@RequestMapping(path = "/fetch-by-query", method = RequestMethod.GET, produces = "application/json")
public List<Student> fetchByQuery() {
	return userRepo.findByTheQuery("Abhishek");
}

@RequestMapping(path = "/custom-query", method = RequestMethod.GET, produces = "application/json")
public List<Student> fetchCustom() {
	return userRepo.getAllOrderAndGroup();
}

@RequestMapping(path = "/ip-from-hostname/{ifh}", method = RequestMethod.GET, produces = "application/json")
public String ipFromHostname(@PathVariable("ifh") String ifh) {
	long a = System.currentTimeMillis();
	JavaLookup.lookup(ifh);
	return System.currentTimeMillis() - a + "";

}

@RequestMapping(path = "/hostname-from-ip/{hfi}", method = RequestMethod.GET, produces = "application/json")
public String hostnameFromIp(@PathVariable("hfi") String hfi) {
	long a = System.currentTimeMillis();
	JavaLookup.lookup(hfi);
	return System.currentTimeMillis() - a + "";
}

// @PostMapping(path = "/students",consumes = "application/json")
@RequestMapping(path = "/students", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Student> addStudent(@RequestBody Student student) {
	userRepo.save(student);
	return new ResponseEntity<>(student, HttpStatus.CREATED);
}

// @PutMapping
@RequestMapping(path = "/students/{id}", method = RequestMethod.PUT, consumes = "application/json")
public Student updateStudent(@PathVariable("id") String id) {
	Optional<Student> student = userRepo.findById(id);
	if (student.isPresent()) {
		Student stu = student.get();
		stu.setName("updatedName");
		userRepo.save(stu);
		return stu;
	} else {
		System.out.println("DataNot found");
		return null;
	}

}

@RequestMapping(path = "/count", method = RequestMethod.GET, produces = "application/json")
public long getCount() {
    System.out.println("Getting total count...");
    return userRepo.count();
}

}

⚠️ **GitHub.com Fallback** ⚠️