Junit #Before annotation is giving a Nullpointer exception - junit

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}");

Related

How to write proper JUnit test case rest controllers

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());
}
}

Getting NullPointerException while accessing the SuperClass method call using powermock

Getting NullPointerException while accessing the SuperClass method call using powermock
While running the below mentioned testclass getting NullPointerException error at above mentioned line in switch(super.getType())
public class CommandParamInput extends AbstractCommandParam {
public CommandParamInput(
final ParameterFeedType commandParameterSourceToSet,
final Object definedValueToSet) {
this.commandParameterSource = commandParameterSourceToSet;
this.definedValue = definedValueToSet;
}
public void evaluateValue(final FDPRequest fdpRequest)
throws EvaluationFailedException {
switch (super.getType()) {
case ARRAY:
evaluateComplexValue(fdpRequest);
break;
}
}
}
While running the below mentioned testclass getting NullPointerException error at above mentioned line in switch(super.getType())
#RunWith(PowerMockRunner.class)
#PrepareForTest({AbstractCommandParam.class,CommandParameterType.class,ParameterFeedType.class,LoggerUtil.class,Logger.class})
public class CommandParamInputTest {
private Logger loggerMock;
private FDPRequest instFDPRequest;
private FDPResponse instFDPResponse;
private FDPCacheable instFDPCacheable;
private AbstractCommandParam cmdParam;
private CommandParamInput spy;
#Mock
AbstractCommandParam absCommandParam;
#Mock
CommandParameterType cmdParameterType;
#Mock
ParameterFeedType parameterFeedType;
#InjectMocks
private CommandParamInput commandParamInput;
#Before
public void init() {
FDPRequestImpl fdoRequestImpl = new FDPRequestImpl();
fdoRequestImpl.setCircle(new FDPCircle(new Long(10),"10","test"));
fdoRequestImpl.setChannel(ChannelType.USSD);
instFDPRequest = fdoRequestImpl;
spy = PowerMockito.spy(new CommandParamInput(parameterFeedType.AUX_REQUEST_PARAM, instFDPCacheable));
}
#Test
public void testEvaluateValue()throws ExecutionFailedException,
EvaluationFailedException, FileNotFoundException, RuleException{
mockCommonObjects();
commonMockExternalCall();
absCommandParam = new CommandParamInput(parameterFeedType.AUX_REQUEST_PARAM, instFDPCacheable);
absCommandParam.setType(cmdParameterType.PARAM_IDENTIFIER);
PowerMockito.doReturn(cmdParameterType.PARAM_IDENTIFIER).when(spy).getType();
// when(absCommandParam.getType()).thenReturn(cmdParameterType.PARAM_IDENTIFIER);
PowerMockito.suppress(PowerMockito.methods(AbstractCommandParam.class, "getType"));
commandParamInput.evaluateValue(instFDPRequest);
}
}

Unit Test class not running properly - Mocking Interfaces

I have a simple Controller class like below:-
#RestController
public class CrawlerAppController {
private static final Logger LOGGER = LoggerFactory.getLogger(CrawlerAppController.class);
#Autowired
private CrawlerServiceInterface crawlerService;
/* The response time of the crawling operation is directly proportional to the no of pages
* we want to crawl. Keeping a default value of 10 so we can view the results quicker.
* author: Arunava Paul
*/
#RequestMapping(value = "/crawl", method = { RequestMethod.GET })
public Object crawlUrl(#RequestParam(value = "URL") String URL,
#RequestParam(value = "max", defaultValue = "10") int maxPages) throws Exception {
if(!URL.startsWith("https://"))
URL="https://"+URL;
LOGGER.info("Request Received. Domain "+URL+" Pages to be Crawled "+maxPages);
return crawlerService.crawlService(URL, maxPages);
}
}
I have written a Junit class like below:-
#RunWith(PowerMockRunner.class)
public class CrawlerAppControllerTest {
Object obj=new Object();
#Spy
#InjectMocks
private CrawlerServiceInterface crawlerService = Mockito.any(CrawlerService.class);
#InjectMocks
CrawlerAppController appController = new CrawlerAppController();
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void testController() throws Exception {
when(crawlerService.crawlService("https://vogella.com", 20)).thenReturn(obj);
assertEquals(appController.crawlUrl("vogella.com",20), obj);
}
}
It's always going into the Service class and the when statement is not running.
Can someone please advise what have I done wrong. Below error comes if I run Junit.
You should declare crawlerService like this:
#Mock
private CrawlerServiceInterface crawlerService;
The declaration of crawlerService in the test class should be:
#Mock
private CrawlerServiceInterface crawlerService;

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

#Mock objects returning null

So I have code below-
#RunWith(MockitoJUnitRunner.class)
public class TeamSubscriptionServiceTest {
#InjectMocks
private TeamSubscriptionService teamSubscriptionService;
#Mock
private ImsCustomerProfileService imsService;
#Mock
private IUserService userService;
#Mock
private HttpRequestService httpRequestService;
#Mock
private ISubscriptionDbService subscriptionDbService;
private String imsToken = "IMS_Token";
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(imsService.getAccessToken()).thenReturn(imsToken);
ReflectionTestUtils.setField(teamSubscriptionService, "jilEndpoint", "www.testJil.com");
ReflectionTestUtils.setField(teamSubscriptionService, "adobeIOApiKey", "api_key");
}
#Test(groups = { TestGroup.UNIT_TESTS })
public void testAddSeat() throws IOException {
String teamId = "TestTeamID";
String locale = "En_US";
String jasonValue = "TestJasonData";
String apiCallContent = "addSeatAPIResult";
HttpResponse addSeatResponse = mock(HttpResponse.class);
when(addSeatResponse.getCode()).thenReturn(200);
when(addSeatResponse.getContent()).thenReturn(apiCallContent);
HttpServletResponse response = mock(HttpServletResponse.class);
when(httpRequestService.makeHttpRequest(anyString(),anyString(),anyMap(),anyString())).thenReturn(addSeatResponse);
String result = teamSubscriptionService.addSeat(teamId,locale,jasonValue,response);
assertNotNull(result);
assertEquals(result, "addSeatAPIResult");
}
}
When I test it I get a NullPointerException on the line
when(httpRequestService.makeHttpRequest(anyString(),anyString(),anyMap(),anyString())).thenReturn(addSeatResponse);
I feel that all the objects annotated with #Mock are somehow null and the object are not getting injected to the teamSubscriptionService object.
Any Idea whats wrong with the code?
The problem is that you are mixing TestNG and JUnit annotations.
Test method is annotated with #Test(groups = { TestGroup.UNIT_TESTS }) - it is clearly a TestNG annotation #org.testng.annotations.Test, because JUnit's equivalent does not have element called groups.
However, you are using JUnit's #Before annotation on setup() method, therefore this method is never invoked. TestNG equivalent for this annotation is #org.testng.annotations.BeforeTest. Use it instead.
<...>
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
<...>
public class TeamSubscriptionServiceTest {
#InjectMocks
private TeamSubscriptionService teamSubscriptionService;
#Mock
private ImsCustomerProfileService imsService;
#Mock
private IUserService userService;
#Mock
private HttpRequestService httpRequestService;
#Mock
private ISubscriptionDbService subscriptionDbService;
private String imsToken = "IMS_Token";
#BeforeTest
public void setup() {
MockitoAnnotations.initMocks(this);
<...>
}
#Test(groups = { TestGroup.UNIT_TESTS })
public void testAddSeat() throws IOException {
<...>
}
}
As a side note, #RunWith(MockitoJUnitRunner.class) is redundant as well, when using TestNG.