In a simple test class like the one below:
#SpringBootTest
#Slf4j
#ActiveProfiles("test")
public class LocalizerTest {
#Autowired
AddressInfoLocalizer addressInfoLocalizer;
#Test
public void localizeIp() {
String ip = "8.8.8.8";
Optional<CityResponse> response = addressInfoLocalizer.localize(ip);
response.ifPresent(cityResponse -> log.info("{}", cityResponse));
}
}
With the AddressInfoLocalizer (sorry for the strange name but I had to make it up) being basically like this:
#Slf4j
#Component
public class AddressInfoLocalizer {
#Value("${geolocalization.dbpath}")
private String databasePath;
private DatabaseReader database;
#PostConstruct
public void initialize() {
log.info("GeoIP2 database path:{}", databasePath);
File database = new File(databasePath);
try {
this.database = new DatabaseReader.Builder(database).build();
} catch (IOException ioe) {
this.database = null;
log.warn("Problems encountered while initializing IP localization database, skipping resolutions");
}
}
public Optional<CityResponse> localize(String ipAddressString) {
if (isNull(database)) {
log.warn("Attempted to resolve an IP location with database problems, skipping.");
return Optional.empty();
}
try {
InetAddress ipAddress = InetAddress.getByName(ipAddressString);
return ofNullable(database.city(ipAddress));
} catch (UnknownHostException uhe) {
log.error("Unknown host {}, {}", ipAddressString, uhe.getCause());
return Optional.empty();
} catch (IOException ioe) {
log.error("IO error while opening database, {}", ioe.getCause().toString());
return Optional.empty();
} catch (GeoIp2Exception gip2e) {
log.error("GeoIP error, {}", gip2e.getCause().toString());
return Optional.empty();
}
}
}
I keep getting a NullPointerException when calling (in the test) addressInfoLocalizer.localize(ip);,
java.lang.NullPointerException
at com.bok.parent.LocalizerTest.localizeIp(LocalizerTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
while debugging I can actually see that the addressInfoLocalizer object is null.
I've created other classes the same way, but only this one seems to have that problem, what could be wrong?
What I found out is that not always the #SpringBootTest is enough, in some classes/cases (to be honest I don't have a 100% clear idea so I'm not gonna say stupidities) it is needed that you manually choose the test-runner, like below:
#SpringBootTest
#RunWith(SpringRunner.class)
public class FooTest {
...
}
Keep in mind that if you decide to instantiate a dependency by yourself then Spring won't be able to inject all the needed classes, and then you'd need to change the runner into something like #RunWith(MockitoJUnitRunner.class)
(credits to JUNIT Autowired instance is always null)
A better approach is to use spring's underlying mock beans.
#SpringBootTest(classes= AddressInfoLocalizer.class)
this is actually the new recommended way.
Two things here:
If you're testing, the ideal way is to mock instead of autowire(there can be exceptions)
You should use #ExtendWith(MockitoExtension.class) or #RunWith(MockitoJUnitRunner.class) so that your components will be loaded in spring context. However ExtendWith is preferred way to initialize beans/components. Because the later(RunWith) loads the entire spring context which might take more time
So, your code should look something like:
#Slf4j
#ActiveProfiles("test")
#ExtendWith(MockitoExtension.class)
public class LocalizerTest {
#Mock
AddressInfoLocalizer addressInfoLocalizer;
#Test
public void localizeIp() {
String ip = "8.8.8.8";
//Mock here.
Optional<CityResponse> response = addressInfoLocalizer.localize(ip);
response.ifPresent(cityResponse -> log.info("{}", cityResponse));
}
}
Reference/Read more:
https://www.baeldung.com/mockito-junit-5-extension
https://stackoverflow.com/questions/55276555/when-to-use-runwith-and-when-extendwith
https://www.javadoc.io/static/org.mockito/mockito-junit-jupiter/3.10.0/org/mockito/junit/jupiter/MockitoExtension.html
Related
I have a simple spring boot project--
Here is the project structure-
If I run my spring boot application, it runs fine without any errors. I was able to get all the customers, get a single customer, delete a customer and add a customer through my rest controller methods.
Through Postman I am able to add customers--
<Customer>
<firstName>TestData</firstName>
<lastName>Test</lastName>
<gender>M</gender>
<date>2020-01-26T09:00:00.000+0000</date>
<authId>6AE-BH3-24F-67FG-76G-345G-AGF6H</authId>
<addressdto>
<city>Test City</city>
<country>Test Country</country>
</addressdto>
</Customer>
Response
Customer with 34 sucessfully added
This means while the application is up, it is able to instantiate PropertyService.java.
thus I am able to access an authentication id which is present in my application-dev.properties through PropertyService.java. The same property is present in my src/test/resources-> application.properties.
There are two problems--
Now when I run my HomeControllerTest.java class asjUnit test , I
am getting a error. I debugged and found out the root cause of the
error. Inside my HomeController.java class , it is unable to
instantiate the PropertyService.java class, so i am getting a
null pointer exception there.Thus the further execution of test class failed.
I am unable to access the authId through PropertyService.java in my test class., so I had to hardcode.
Can anyone tell me why I am getting this issue? And how do I fix it?
HomeController.java
#PostMapping("/customer")
public ResponseEntity<String> addCustomer(#RequestBody CustomerDto customerDto) {
String message = "";
ResponseEntity<String> finalMessage = null;
try {
if ((!customerDto.getAuthId().equals(propertyService.getKeytoAddCustomer()))) {
System.out.println("If check failed: "+propertyService.getKeytoAddCustomer());
System.out.println("Unauthorized access attempted");
message = "Unauthorized access attempted";
finalMessage = new ResponseEntity<>(message, HttpStatus.UNAUTHORIZED);
}
System.out.println("If check passed :"+propertyService.getKeytoAddCustomer());
Customer customer = mapper.mapToEntity(customerDto);
customerService.addCustomer(customer);
message = "Customer with " + customer.getId() + " sucessfully added";
finalMessage = new ResponseEntity<>(message, HttpStatus.OK);
} catch (Exception e) {
message = "Failed to add customer due to " + e.getMessage();
finalMessage = new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR);
}
return finalMessage;
}
PS- equals(propertyService.getKeytoAddCustomer())) (Problem 1) --> here I am getting the null pointer exception
PropertyService.java
package com.spring.liquibase.demo.utility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
#Configuration
#PropertySource("classpath:config.properties")
public class PropertyService {
#Autowired
private Environment env;
public String getKeytoAddCustomer() {
return env.getProperty("auth.key.to.add.customer");
}
}
HomeControllerTest.java
#ExtendWith(SpringExtension.class)
class HomeControllerTest {
private MockMvc mvc;
#InjectMocks
private HomeController homeController;
#MockBean
private CustomerService customerService;
//
// #Autowired
// private PropertyService propertyService;
#BeforeEach
public void setup() {
mvc = MockMvcBuilders.standaloneSetup(homeController).build();
MockitoAnnotations.initMocks(this);
}
#Test
public void testaddCustomer() throws Exception {
String uri = "/customer";
CustomerDto custDto = this.mockCustomerObject();
String actualResult = mvc
.perform(MockMvcRequestBuilders.post(uri).contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(custDto)))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn().getResponse().getContentAsString();
Assertions.assertEquals(actualResult, "Customer with " + custDto.getId() + " sucessfully added");
}
private CustomerDto mockCustomerObject() {
CustomerDto cusDto = new CustomerDto();
AddressDto addressDto = new AddressDto();
addressDto.setCity("BBSR");
addressDto.setCountry("INDIA");
cusDto.setDate(new Date());
cusDto.setFirstName("Biprojeet");
cusDto.setLastName("KAR");
cusDto.setGender("M");
cusDto.setAuthId(" 6AE-BH3-24F-67FG-76G-345G-AGF6H");
cusDto.setAddressdto(addressDto);
return cusDto;
}
public static String asJsonString(CustomerDto cusDto) {
try {
return new ObjectMapper().writeValueAsString(cusDto);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
PS- I have commented out the codes as I am unable to access the prop file here.Need help here as well(Problem 2)
application.properties-- inside src/test/resources
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:mysql******useSSL=false
spring.datasource.username=****
spring.datasource.password=****
# Hibernate
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
logging.level.org.springframework.web=INFO
logging.level.com=DEBUG
customer.auth.key = 6AE-BH3-24F-67FG-76G-345G-AGF6H
application-dev.properties
same as above
application.properties inside->src/main/resources
spring.profiles.active=dev
logging.level.org.springframework.web=INFO
logging.level.com=DEBUG
server.port=8080
jUnit Error Log
java.lang.AssertionError: Status expected:<200> but was:<500>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at com.spring.liquibase.demo.controller.HomeControllerTest.testaddCustomer(HomeControllerTest.java:50)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:436)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:112)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)
at java.base/java.util.Iterator.forEachRemaining(Unknown Source)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.base/java.util.stream.ReferencePipeline.forEach(Unknown Source)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)
at java.base/java.util.Iterator.forEachRemaining(Unknown Source)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.base/java.util.stream.ReferencePipeline.forEach(Unknown Source)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
After gone through with your repo here is the final code
#WebMvcTest(HomeController.class)
class HomeControllerTest {
#Autowired
private MockMvc mvc;
#MockBean
private CustomerService customerService;
#MockBean
private PropertyService propertyService;
#MockBean
private EntityToDtoMapper mapper;
#Test
public void testaddCustomer() throws Exception {
String uri = "/customer";
CustomerDto custDto = this.mockCustomerObject();
Customer customer = getCustomerEntity();
Mockito.when(mapper.mapToEntity(Mockito.any(CustomerDto.class))).thenReturn(customer);
String actualResult = mvc
.perform(MockMvcRequestBuilders.post(uri).contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(custDto)))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn().getResponse().getContentAsString();
Assertions.assertEquals(actualResult, "Customer with " + custDto.getId() + " sucessfully added");
}
private CustomerDto mockCustomerObject() {
CustomerDto cusDto = new CustomerDto();
AddressDto addressDto = new AddressDto();
addressDto.setCity("BBSR");
addressDto.setCountry("INDIA");
cusDto.setDate(new Date());
cusDto.setFirstName("Biprojeet");
cusDto.setLastName("KAR");
cusDto.setGender("M");
cusDto.setAuthId(" 6AE-BH3-24F-67FG-76G-345G-AGF6H");
cusDto.setAddressdto(addressDto);
return cusDto;
}
private Customer getCustomerEntity() {
Customer customer = new Customer();
Address address = new Address();
address.setCity("BBSR");
address.setCountry("INDIA");
customer.setDate(new Date());
customer.setFirstName("Biprojeet");
customer.setLastName("KAR");
customer.setGender("M");
customer.setAddress(address);
return customer;
}
public static String asJsonString(CustomerDto cusDto) {
try {
return new ObjectMapper().writeValueAsString(cusDto);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
The issue over here that you are mixing the concepts. In your implementation you were trying to do unit testing but was expecting the behaviour of integration.
As you been using Spring boot with it's test starter kit which comes with the dependencies of framework like JUnit and Mockito, You can easily mock those classes and methods which throwing the Null pointer exception by using mockitio framework because server is not running and IOC container is not up that's why those are NULL.
So in your code CustomerService, PropertyService and EntityToDtoMapper was NULL.
So question over here is how we can upload the spring application context without starting the server.
It can be done by two ways either load the whole spring application context by using #SpringBootTest and #AutoConfigureMockMvc annotations.
Or we can narrow the spring application context only for the controller itself by using #WebMvcTest annotation
So the solution which I used over here is narrow the test to the controller only by using #WebMvcTest(HomeController.class) annotation.
But still those CustomerService, PropertyService and EntityToDtoMapper are NULL. So to mock those classes We can use either #Mock or #MockBean annotation, but there is a slight difference between those annotation
The Mockito.mock() method allows us to create a mock object of a class or an interface and the #MockBean to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context.
So as we have uploaded the spring application context for the controller so the controller is expecting those beans in the application context as well, which can be achieved by #MockBean annotation.
After mocking all those beans your controller bean will be created but there are the methods where you expecting some return values so you have to code the expected return value in your code which could be done like that
Mockito.when(mapper.mapToEntity(Mockito.any(CustomerDto.class))).thenReturn(customer);
if you miss this particular step then in the controller you will get an NULL pointer exception on this line of code
message = "Customer with " + customer.getId() + " sucessfully added";
Because you code
Customer customer = mapper.mapToEntity(customerDto);
will return NULL.
I hope this will help and motivate you to get more knowledge on those concepts.
Please let me know if any further help is required
And there is one more error. This is a major one-- my test case passes even if i give a wrong authId . Please try in your local and let me know if u r having the same behaviour.
Off-course your test will be passed because your code is only checking the conditions it's not preventing the code to get executed, Please refer your code below:
try {
if ((!customerDto.getAuthId().equals(propertyService.getKeytoAddCustomer()))) {
System.out.println("If check failed: "+propertyService.getKeytoAddCustomer());
System.out.println("Unauthorized access attempted");
message = "Unauthorized access attempted";
finalMessage = new ResponseEntity<>(message, HttpStatus.UNAUTHORIZED);
}
System.out.println("If check passed :"+propertyService.getKeytoAddCustomer());
Customer customer = mapper.mapToEntity(customerDto);
customerService.addCustomer(customer);
message = "Customer with " + customer.getId() + " sucessfully added";
finalMessage = new ResponseEntity<>(message, HttpStatus.OK);
}
Over here under if condition you are only executing the block of codes and then instructed to execute the block of code which is outside the if condition.
So under if condition it's doing nothing. So you have to improve your code as per your expected behaviour.
If you would like to prevent your code execution then please refer the code below
try {
if ((!customerDto.getAuthId().equals(propertyService.getKeytoAddCustomer()))) {
System.out.println("If check failed: "+propertyService.getKeytoAddCustomer());
System.out.println("Unauthorized access attempted");
message = "Unauthorized access attempted";
return new ResponseEntity<>(message, HttpStatus.UNAUTHORIZED);
}
System.out.println("If check passed :"+propertyService.getKeytoAddCustomer());
Customer customer = mapper.mapToEntity(customerDto);
customerService.addCustomer(customer);
message = "Customer with " + customer.getId() + " sucessfully added";
finalMessage = new ResponseEntity<>(message, HttpStatus.OK);
} catch (Exception e) {
message = "Failed to add customer due to " + e.getMessage();
e.printStackTrace();
finalMessage = new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR);
}
Here I have set the return statement under If condition.
But If you want to fail the current test case where you comparing the message then please refer the code below:
try {
if ((!customerDto.getAuthId().equals(propertyService.getKeytoAddCustomer()))) {
System.out.println("If check failed: "+propertyService.getKeytoAddCustomer());
System.out.println("Unauthorized access attempted");
message = "Unauthorized access attempted";
finalMessage = new ResponseEntity<>(message, HttpStatus.UNAUTHORIZED);
}else {
System.out.println("If check passed :" + propertyService.getKeytoAddCustomer());
Customer customer = mapper.mapToEntity(customerDto);
customerService.addCustomer(customer);
message = "Customer with " + customer.getId() + " sucessfully added";
finalMessage = new ResponseEntity<>(message, HttpStatus.OK);
}
} catch (Exception e) {
message = "Failed to add customer due to " + e.getMessage();
e.printStackTrace();
finalMessage = new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR);
}
Here you just need to set the block of code which is outside the if condition under the else part.
Try mocking the PropertyService with either #MockBean or #Mock.
I notice you're missing #WebMvcTest(Controller.class) above the class definition which you'll need for unit testing Mvc Controllers.
Explanation
If #MockBean doesn't work.
Try:
Using Mockito.when(), you can simply return your desired/expected result and when the desired method is called.
Use Mockito.verify() to ensure the desire when is executed.
when(propertyService.getKeytoAddCustomer()).thenReturn("Desired String");
when(customerService.addCustomer(customerObject)).thenReturn("Desired result");
//DO mvc.perform(...);
verify(propertyService).getKeytoAddCustomer();
verify(customerService).addCustomer(customerObject());
Problem Two
The issue with the property file I assume is because you're using spring.profile.active=dev but property file is test/resources is application.properties instead of application-dev.properties despite that it is the only property file in test/resources. Rename the files exactly the same in both resources folder and see what happens.
I am facing some difficulties in writing junit test to pass the for loop condition to getParts() method from SlingHttpServletRequest.getParts(). There is no problem with the implementation, I am able to process the file attachment properly. However, I am unable to do so in the junit test.
The following is my implementation:
#Model(adaptables = SlingHttpServletRequest.class)
public class Comment {
//Variables declaration
#Inject
private CommentService service;
#PostConstruct
public void setup() {
requestData = new JSONObject();
for (String item : request.getRequestParameterMap().keySet()) {
try {
requestData.put(item, request.getParameter(item));
}
} catch (Exception e) {
Throw error message
}
}
//Upload attachment to server
try {
for (Part part : request.getParts()) { <= The JUnit test stopped at this line and throw the error below
} catch (Exception e) {
Throw error message
}
I have tried using a SlingHttpServletRequestWrapper class to override the getParts method but to no avail.
The following is my junit test:
public class CommentTest {
public final AemContext context = new AemContext();
private CommentService commentService = mock(CommentService.class);
#InjectMocks
private Comment comment;
private static String PATH = "/content/testproject/en/page/sub-page";
#Before
public void setUp() throws Exception {
context.addModelsForPackage("de.com.adsl.sightly.model");
context.load().json("/components/textrte.json", PATH);
context.currentPage(PATH);
}
#Test
public void testSetup() throws IOException, ServletException {
//before
context.request().setParameterMap(getRequestCat1());
context.registerService(CommentService.class, commentService);
Resource resource = context.resourceResolver().getResource(PATH + "/jcr:content/root/responsivegrid/textrte");
assertNotNull(resource);
//when
comment = new CustomRequest(context.request()).adaptTo(Comment.class);
//then
comment.setup();
}
private class CustomRequest extends SlingHttpServletRequestWrapper {
public CustomRequest(SlingHttpServletRequest request) {
super(request);
}
#Override
public Collection<Part> getParts() {
final String mockContent =
"------WebKitFormBoundarycTqA2AimXQHBAJbZ\n" +
"Content-Disposition: form-data; name=\"key\"\n" +
"\n" +
"myvalue1\n" +
"------WebKitFormBoundarycTqA2AimXQHBAJbZ";
final List<Part> parts = MockPart.parseAll(mockContent);
assertNotNull(parts);
return parts;
}
};
}
The following is the error message that I encountered:
14:53:04.918 [main] ERROR de.com.adsl.sightly.model.Comment - Error Message: null
java.lang.UnsupportedOperationException: null
at org.apache.sling.servlethelpers.MockSlingHttpServletRequest.getParts(MockSlingHttpServletRequest.java:882) ~[org.apache.sling.servlet-helpers-1.1.10.jar:?]
at de.com.adsl.sightly.model.Comment.uploadFile(Feedback.java:137) ~[classes/:?]
at de.com.adsl.sightly.model.Comment.setup(Feedback.java:82) [classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_201]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_201]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_201]
at org.apache.sling.models.impl.ModelAdapterFactory.invokePostConstruct(ModelAdapterFactory.java:792) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.createObject(ModelAdapterFactory.java:607) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.internalCreateModel(ModelAdapterFactory.java:335) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.getAdapter(ModelAdapterFactory.java:211) [org.apache.sling.models.impl-1.3.8.jar:?]
...
I have looked up various solutions online such as writing two mockito when statements but has not been successful. I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!
From the source code of MockSlingServletResquest it always throws that exception as it's not supported yet by the mocked class.
https://github.com/apache/sling-org-apache-sling-servlet-helpers/blob/71ef769e5564cf78e49d6679a3270ba8706ae406/src/main/java/org/apache/sling/servlethelpers/MockSlingHttpServletRequest.java#L953
Maybe you should consider writing a servlet, or another approach.
I have a unit test I am writing for a class, and this class uses a ConfigurationManager I wrote to get configuration from a TOML object (and therefore from a TOML file).
The Code
Here is the relevant ConfigurationManager code:
public class ConfigurationManager {
// DEFAULT_LOGGING_LEVEL should represent level to use in production environment.
private final static Level DEFAULT_LOGGING_LEVEL = Level.FINE;
private final static String LOG_LEVEL_ENV_PROPERTY = "LOG_LEVEL";
private final static String TOML_FILE_NAME = "config.toml";
private final static String LOCAL_ENV_PROPERTY = "local";
private final static String ENV_PROPERTY = "MY_ENV";
private static Logger CM_LOGGER;
private Environment environment;
public ConfigurationManager() {
environment = new Environment();
CM_LOGGER = new LoggerUtil(ConfigurationManager.class.getName(), getLoggingLevel()).getLogger();
}
public File getTomlFile() throws URISyntaxException, FileNotFoundException {
URI uri = getConfigURI();
File tomlFile = new File(uri);
if (!tomlFile.exists()) {
String err = TOML_FILE_NAME + " does not exist!";
CM_LOGGER.severe(err);
throw new FileNotFoundException(err);
}
return tomlFile;
}
/**
* #return A URI representing the path to the config
* #throws URISyntaxException if getConfigURI encounters bad URI syntax.
*/
private URI getConfigURI() throws URISyntaxException {
return getClass().getClassLoader().getResource(TOML_FILE_NAME).toURI();
}
/**
* Method for getting the app configuration as a toml object.
*
* #return A toml object built from the config.toml file.
* #throws URISyntaxException if getConfigURI encounters bad URI syntax.
* #throws FileNotFoundException if getTomlFile can't find the config.toml file.
*/
public Toml getConfigToml() throws URISyntaxException, FileNotFoundException {
return new Toml().read(getTomlFile());
}
}
And here is the code that calls this Configuration Manager:
public class Listener {
// Initializations
private static final String CONFIG_LISTENER_THREADS = "listenerThreads";
private static final String DEFAULT_LISTENER_THREADS = "1";
/**
* Constructor for getting app properties and initializing executor service with thread pool based on app prop.
*/
#PostConstruct
void init() throws FileNotFoundException, URISyntaxException {
ConfigurationManager configurationManager = new ConfigurationManager();
int listenerThreads = Integer.parseInt(configurationManager.getConfigToml()
.getString(CONFIG_LISTENER_THREADS, DEFAULT_LISTENER_THREADS));
this.executorService = Executors.newFixedThreadPool(listenerThreads);
LOGGER.config("Listener executorService threads: " + listenerThreads);
}
...
}
And here is the test for that code (See comment to see where NPE is triggered):
public class ListenerTests {
#Mock
ConfigurationManager mockCM;
#InjectMocks
Listener listener = new Listener();
#Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
#Test
public void testListener_ShouldInit() throws FileNotFoundException, URISyntaxException {
when(mockCM.getConfigToml().getString(any(), any())).thenReturn("5"); // !!!NPE TRIGGERED BY THIS LINE!!!
listener.init();
verify(mockCM, times(1)).getConfigToml().getString(any(), any());
}
}
The Problem
I get a NullPointerException as follows
java.lang.NullPointerException
at com.bose.source_account_listener.ListenerTests.testListener_ShouldInit(ListenerTests.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I have a guess as to the problem here but I'm not sure how to validate my guess. My guess is that I am mocking the ConfigurationManager, but the mock doesn't know that the ConfigurationManager can generate a TOML file which has a getString method, so I end up getting the NPE. This makes me think that I need a mock TOML for my mock ConfigurationManager, but I am neither certain this is the case or that this is the proper solution.
I am new to Mockito and Java in general so any help would be appreciated.
You need to mock every bit of your call, not just the full call. mockCM.getConfigToml() has no mock response, so it returns null, and a toString is invoked on a null object. Your options are to return a non-mocked "Toml" or mock a Toml and then set that up with a when configuration.
Toml tomlMock = Mockito.mock(Toml.class);
when(mockCM.getConfigToml()).thenReturn(tmolMock);
when(tmolMock.getString(any(), any())).thenReturn("5");
You're trying to mock the method of what is returned by calling getConfigToml. That is, you need to mock the object of what should be returned by getConfigToml, and then call getString on that object.
I am writing a JUnit test case for a method which internally invokes another method through interface. I am using Mockito to mock the interface but for some reason it gives me NPE. I debugged through but wasn't able to get any clue to fix it. getAllVendors() method throws exception which comes through an Interface.
MUT
public void prepare() throws AccountServiceException, ManagerException {
vendors = getVendorManager().getAllVendors();
microsites = new ArrayList<VendorMicrositeTO>();
microsites.add( new VendorMicrositeTO( "http://www.docusign.com", "docuSign" ) );
clientUser = createClientUserObject();
}
JUnit
#Test
public void testPrepare() throws Exception {
AccountAction accountAction = new AccountAction();
Map<String, Object> actionMap = new HashMap<>();
actionMap.put("application", "ESignatureIntegrationAction");
ActionContext.setContext(new ActionContext(actionMap));
String beanName = Constants.VENDOR_MANAGER_SPRING_BEAN;
PowerMockito.mockStatic(AppContext.class);
PowerMockito.when(AppContext.containsBean( beanName )).thenReturn( true );
IVendorDto iVendorDto = new VendorDto();
iVendorDto.setActive(true);
iVendorDto.setCreatedBy("9/15/2016");
iVendorDto.setName("CorpESignClientUser");
iVendorDto.setCreatedBy("SYSTEM");
List<IVendorDto> vendorList = new ArrayList<>();
vendorList.add(iVendorDto);
IVendorManager iManager = Mockito.mock((IVendorManager.class));
Mockito.when(iManager.getAllVendors()).thenReturn(vendorList);
accountAction.setVendors(vendorList);
accountAction.prepare();
}
Stack trace
java.lang.NullPointerException
at com.mercuryinsurance.esignature.ui.webapp.action.AccountAction.prepare(AccountAction.java:65)
at test.com.mercuryinsurance.esignature.ui.webapp.action.TestAccountAction.testPrepare(TestAccountAction.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Thanks, in advance
Seems you forgot to add a line in your test like:
accountAction.setVendorManager(iManager);
So yeah, I have been tackling a very similar issue.
This usecase is a logical outcome of the application of the SOLID principles within an IoT based application. If you decouple the layers of your application using interfaces and are testing an innner layer you are bound to come across testing an interface whose implementations have more interface dependencies.
You can achieve this goal using two testing angles combined
Use the Parameterized JUnit runner to launch the one set of unit tests for all of the implementations.
Then internally during each run initialize the mocked dependencies using Mockito
For more information on Parameterized testing (that's where i originally found it) be sure to visit this post. The manual initialization of mockito was something i found here.
All and all the resulting code looks like this:
#RunWith(Parameterized.class)
public class YourInterfaceTest {
#Mock
private ImplementationDependency sneakyBreakyNpeAvoided;
#InjectMocks
private YourInterfaceToTest iface;
// constructor is used by the Parameterized runner to provide impelementations
public YourInterfaceTest (YourInterfaceToTest ifaceToTest) {
this.iface = ifaceToTest;
}
// this method is called always before running tests so a good time to inject anything
#Before
public void init() {
MockitoAnnotations.initMocks(this);
Mockito.when(sneakyBreakyNpeAvoided.returnTrue()).thenReturn(true);
}
#Test(expected = IllegalArgumentException.class)
public void doSomething_nullParameter_throwsIllegalArgumentException() {
Assert.fail(); // tests here :)
}
#Parameterized.Parameters
public static Collection<YourInterfaceToTest > provideImplementations() {
// change to Arrays.asList when multiple implementations are available
return Collections.singletonList(new YourInterfaceImpl());
}
}
Hope I understood the OP's issue well.
I have the following code
public class A{
public void createFile() {
File tempXmlFile = null;
String extension = ".xml";
String name = "someName";
try {
tempXmlFile = File.createTempFile(name, extension);
if (tempXmlFile.exists()) {
tempXmlFile.delete();
}
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(A.class)
public class testA extends TestCase{
private A classUnderTest;
#Override
#Before
public void setUp() {
classUnderTest = PowerMock.createMock(A.class); //the class is more complex in my case and I have to mock it
}
public void testCreateFile() throws IOException{
String extension = ".xml";
String name = "someName";
PowerMock.mockStatic(File.class);
File tempFileMock = PowerMock.createMock(File.class);
expect(File.createTempFile(name, extension)).andReturn(tempFileMock);
expect(tempFileMock.exists()).andReturn(true);
expect(tempFileMock.delete()).andReturn(true);
replay(File.class, tempFileMock, classUnderTest);
classUnderTest.createFile();
verify(File.class, tempFileMock, classUnderTest);
}
}
In the test class as I said the class under test must be mocked(I can't create a new object).
When I run the test I get:
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:174)
at org.easymock.EasyMock.expect(EasyMock.java:156)
at myPackage.testA.testCreateFile(testA.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:163)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:113)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:111)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:87)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:44)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I read the documentation here http://code.google.com/p/powermock/wiki/MockSystem but the test stil wont't work. Am I missing something?
Edit: I tested the previous code with a real A object (and removed it from replay)
classUnderTest = new A();
but I still get the same exception.
Try adding File.class to #PrepareForTest.
try the org.powermock.reflect.internal.WhiteboxImpl.newInstance() method to create the object of the class and then call method directly.
1) this will suppress the constructor of the class
2) if your class contains static block then use suppressStaticInitilaizationFor to suppress that.
regards
Anil Sharma
Add File.class to #PrepareForTest and check the imports of replay and verify. They should be from PowerMock.
I think you need to suppress constructor
Check this
http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior