How to write proper JUnit test case rest controllers - junit

I want to write JUnit test case rest controller using mockito framework. I want to know how to write test cases for http request like get and post. Also how to test api which uploads a document.

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
#RunWith(MockitoJUnitRunner.class)
#WebMvcTest
#AutoConfigureMockMvc
public class ControllerTest {
#Autowired
private MockMvc mvc;
#Mock
Service service;
#InjectMocks
private Controller controller;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(marketplaceCatalogController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers(new ViewResolver() {
#Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return new MappingJackson2JsonView();
}
}).build();
}
#Test
public void testGetMethod() throws Exception {
when(service.getMethod(Mockito.any(SomeClass.class))).thenReturn(new SomeOtherClass);
doNothing().when(service).someMethod();
mvc.perform(get("/get-method").param("paramKey",
"paramValue")).andExpect(status().isOk()).andDo(print());
}
#Test
public void testStatusTnC() throws Exception {
String payload = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
mvc.perform(post("/post-method").content(payload)).andExpect(status().isOk()).andDo(print());
}
#Test
public void testUploadFile() throws Exception {
when(service.uploadSomeContent(any(), any(), anyString(), anyString())).thenReturn(new SomeClass());
mvc.perform(fileUpload("/post-request/uploadFile").file("somefile", "Hello, World!".getBytes()).param("param1", "value1").contentType(MediaType.MULTIPART_FORM_DATA)).andExpect(status().isOk()).andDo(print());
}
}

Related

FasterXML ObjectMapper is not working with ExecutorService in a Junit test

It is a very strange issue. Removing the JSON in TestUtil or the executorService/submit will make the following code working:
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ATest {
#BeforeAll
public static void setup(TestInfo test) throws Exception {
}
#Test
void testThis(){
int numThreads = 1;
ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
threadPool.submit(() -> {
TestUtils.doSomething();
});
}
}
Here is the class with the ObjectMapper>
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestUtils {
private static final ObjectMapper JSON;
static {
JSON = new ObjectMapper();
}
public static void doSomething() {
System.out.println("entered the method");
}
}
Currently, the method doSomething() would not be entered at all.
This issue will be resoved if we trigger the Junit test from Maven or if run it from a static main method.

I need to write JUNIT for Apache camel route

I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this
You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}

How to write JUnit Test case

I am learning Junit testing on spring boot Application. my account controller method is depend on service class method. For that I used Mockito. I tried simple But here I am not getting how to write test case for following method? How I can use mockito.
can any one please help me for writing this test case?
AccountController
#RestController
#RequestMapping("/spacestudy/$ {InstituteIdentifier}/admin/account")
public class AccountController {
#Autowired
AccountService accService;
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(#RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
#RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
#RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
#RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
}
AccountService
public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId)throws Exception{
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, investigator);
if (StringUtils.isNotEmpty(sClientAcctId)) {
query.where(account.sClientAcctId.equalsIgnoreCase(sClientAcctId));
}
// code.......
return query.fetch();
}
AccountControllerTest
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
//????
//????
}
}
It will be something like this:
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
when(accountService.populateGridViews("foo","bar")).thenReturn(Arrays.asList(new Tuple("bazz"));
mockMvc.perform(get("/spacestudy/STACKOVERFLOW/admin/account/foo/bar"))
.andExpect(status().isOk())
.andExpect(jsonPath("someField").value("bazz"));
}
}
So basically you are replacing your service with mock and saying what it should return. In your particular case I don't see any reasons for unit testing this class, since it doesn't have any logic inside. But if you would have something like:
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(...) throws Exception {
List<Tuple> result = accService.populateGridViews(...);
if(result==null){
return ResponseEntity.notFound();
}
return ResponseEntity.ok(result);
}
Then it would make more sense to test this class e.g.
1st test - mock your accService to return null and verify that response status is 404
2nd test - mock your accService to return not null and verify that response status is 200

Before Class Method of JUnit not called in correct order

I'm new to JUnit and was learning the various annotations. The code below however is giving me output that seems wrong
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
public class SampleTest {
#BeforeClass
public static void beforeClass() {
System.out.println("Before Class"); }
#AfterClass
public static void afterClass() {
System.out.println("After Class"); }
#Before
public void before() {
System.out.println("Before"); }
#After
public void after() {
System.out.println("After"); }
#Test
public void testAreFirstAndLastNCharactersTheSame() {
System.out.println("testAreFirstAndLastNCharactersTheSame");}
#Test
public void testTruncateAinFirstNPositions() {
System.out.println("testTruncateAinFirstNPositions"); }
}
The output I get is
Before
testTruncateAinFirstNPositions
After
Before
testAreFirstAndLastNCharactersTheSame
After
Before Class
After Class
This seems wrong as the "Before Class" print should be first. Am I doing something wrong? My Junit version is 4.12. I ran the above piece of code on Intellij.
The actual output screenshot is below

Junit #Before annotation is giving a Nullpointer exception

I am using junit 4.8.1.
The following is the code. I am getting "Nullponiter" exception. I suspect that the "SetUp" code under #Before is not been excecuted before other methods. Request the learned friends to help me in resolving the issue. (This is an example for TDD book by Koskela)
import org.junit.*;
import java.util.*;
import static org.junit.Assert.*;
public class TestTemplate {
private Template template;
#Before
public void setUp() throws Exception{
Template template = new Template("${one},${two},${three}");
template.set("one","1");
template.set("two","2");
template.set("three","3");
}
#Test
public void testmultipleVariables() throws Exception{
testassertTemplateEvaluatesTo("1, 2, 3");
}
#Test
public void testUnknownVariablesAreIgnored() throws Exception{
template.set("doesnotexist","whatever");
testassertTemplateEvaluatesTo("1, 2, 3");
}
private void testassertTemplateEvaluatesTo(String expected){
assertEquals(expected,template.evaluate());
}
}
You have two variables with the same name:
private Template template;
#Before
public void setUp() throws Exception{
// declaring second variable here
Template template = new Template("${one},${two},${three}");
change that last line to:
template = new Template("${one},${two},${three}");