I am using powermckito and trying to mock a local object and read a API from it. My implementation class is as below:
public class LogoutUtil {
public static void updateState() {
SrvcContext sc = new SrvcContext();
sc.setUserName("UserNAME");
}
}
I am trying to mock the SrvcContext object and read the user name by calling getter.
Here is my test code:
#Test
public void updateStateTest() {
SrvcContext svc = PowerMockito.mock(SrvcContext.class);
LogoutUtil.updateState();
try {
PowerMockito.whenNew(SrvcContext.class).withNoArguments().thenReturn(svc);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String userName = svc.getUserName(); //This gives null
Assert.assertEquals("UserNAME", userName);
}
Any help how to do it. I cant change the LogoutUtil class.
Thanks
The problem is that the method LogoutUtil.updateState is static and testing and mocking static methods is not always straightforward.
But with PowerMockito you can do it by calling mockStatic method: have a look here: it should solve your issue
Related
I have a project with Morphia ORM - Without transactions. And I have this method:
public void methodForTest() {
try {
methodCanThrowException();
} catch (Exception e) {
methodWhiсhICanNotTest(template);
throw new Exception("message of exception");
}
}
private void methodWhiсhICanNotTest(String template){
serviceWhichCanBeMockOne.clearAll(template);
serviceWhichCanBeMockTwo.clearAll(template);
serviceWhichCanBeMockThree.clearAll(template);
}
Can I check that methodWhiсhICanNotTest(); was called? or how can I rewrite this code for easier testing?
UPDATE ANSWER FOR THE UPDATED QUESTION :D
If your methodWhiсhICanNotTest is a private method. Then you cannot verify it using Mockito in my previous answer. PowerMock is another solution for you. Read this article and try it :-)
=======================
You can use Mockito to verify whether methodWhiсhICanNotTest is called.
Mockito.verify(abc.methodWhiсhICanNotTest())
What is the best way of writing a unit test for a method, such as my setProperties (see below), that uses a private configuration variable (config). I tried but failed to override it using reflection and Makito, but without success. I realize that changing the design to make the code easier to test is best, but I want to created some unit tests before I refactor the code.
public class MainClass {
private final java.lang.String config = "app.properties";
public TestClass() {
try {
setProperties();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setProperties() throws Exception {
try {
InputStream input = new BufferedInputStream(new FileInputStream(config));
..
..
} catch (Exception exception) {
throw exception;
}
}
}
Do refactor a tiny bit by extracting a method with a parameter that takes an input stream. Call this new method (probably package-protected) from the old one. Write tests against the new method. Then do more refactorings.
This is an indication of a broken design; don't hard-code things like this. Better yet, determine what the appropriate responsibility for this class is, and, in decreasing order of preference:
pass in an object with the configuration properties, strongly typed
pass in a Map with the configuration properties
pass in an InputStream for the properties file
As File objects are never available from a jar, you shouldn't ever make interfaces like this more specific than InputStream or Reader, so that you can always pass in streams from your jar classpath.
So you can use Properties class in Java for this. Please have a look at this code.
public class PropertyUtil {
private static Properties prop;
private static Logger logger = Logger.getLogger(PropertyUtil.class);
private PropertyUtil() {
}
public void setProperty() {
String filePath = System.getenv("JAVA_HOME") + "/lib" + "/my_file.properties";
prop = new Properties();
try (InputStream input = new FileInputStream(filePath)) {
prop.load(input);
} catch (IOException ex) {
logger.error("Error while reading property file " + ex);
}
}
public static String getProperty(String key) {
if (prop.containsKey(key)) {
return prop.getProperty(key);
} else {
return null;
}
}
public static <T> T getProperty(String key, Class<T> claz) {
if (claz.getName().equals(Integer.class.getName())) {
return claz.cast(Integer.parseInt(prop.getProperty(key)));
}
if (claz.getName().equals(Long.class.getName())) {
return claz.cast(Long.parseLong(prop.getProperty(key)));
}
if (claz.getName().equals(Boolean.class.getName())) {
return claz.cast(Boolean.parseBoolean(prop.getProperty(key)));
}
if (claz.getName().equals(Double.class.getName())) {
return claz.cast(Double.parseDouble(prop.getProperty(key)));
}
if (claz.getName().equals(String.class.getName())) {
return claz.cast(prop.getProperty(key));
}
return null;
}
I have such problem, as topikstarter here - Using PowerMockito.whenNew() is not getting mocked and original method is called
But I have java 1.4, junit 3.8.1 and jmock 1.2 - and no annotations, of course.
Problem is as it seems in this link - I have a method, which makes new Example(), and then calls Example.someMethod(); I need to get exception from this method to test it. In more wide terms, I need to know how to PowerMockito(or use any other framework) objects in java 1.4 - with junit 3 and without annotations. Make fake object, make any method take this mock object in "new", not create one, and mock it's methods. There is no even method PowerMockito.whenNew() in PowerMockito for junit3...
Any docs, "getting started"s and other things would help - I haven't found anything about PowerMockito for junit3, except of maven dependency link.
public class Example(){
ExampleHelper helper = new ExampleHelper(5);
public void doSmth(){
try{
int i = returnPlus();
System.Out.Println("Nope, we shouldn't come here. We need to visit Catch block");
} catch (myException e){
System.Out.Println("Hoooray, exception!");
}
}
//different package
public class ExampleHelper{
int i;
public ExampleHelper(int i){
this.i = i;
}
public int returnPlus() throws myException{//Yes, method signature tells us, that we are THROWING ecxeption
return i+1;//yes, method DO NOT throws exception
}
}
I'm trying to do something like this, but it doesn't work. In PowerMockito for junit3 there is no such methods - and if I trying to do this with PowerMock+Mockito - there should be annotations, and I have java 4 with no annotations aboard...
public class TestHarderExample extends TestCase {
public void testSomething() {
ExampleHelper exampleHelper = PowerMockito.mock(com.sources.ExampleHelper.class);
Example example = new Example();
try {
PowerMockito.whenNew(ExampleHelper.class).withAnyArguments().thenReturn(exampleHelper);
PowerMockito.when(exampleHelper.giveAplus()).thenThrow(new IOException("Dummy one"));
Example.doSmth();
} catch (IOException e) {
System.out.println("Good one!");
} catch (Exception e){
System.out.println("Bad one...");
}
I'm trying to call different action methods depending on something I put in the session earlier. For this I override the onRequest method in Global like it's recommended in Play's tutorial. I use Java reflection to construct a new method with the same name and parameters but in a different class B. Class B and and the original class with the original actionMethod implement the same interface. So there shouldn't be a problem.
My onRequest in Global looks like:
#Override
public Action onRequest(Request request, final Method actionMethod) {
if (checkSomething) {
return super.onRequest(request, getNewActionMethod(actionMethod));
}
return super.onRequest(request, actionMethod);
}
private Method getNewActionMethod(Method oldActionMethod) {
String name = oldActionMethod.getName();
Class<?>[] parameterTypes = oldActionMethod.getParameterTypes();
Method newActionMethod = null;
try {
newActionMethod = B.class.getMethod(name, parameterTypes);
} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newActionMethod;
}
The Problem here is that Play just ignores my new action method and keeps insisting to call the old one. Am I missing something?
I'm using Play framework 2.2.3.
I'm trying to learn the ins and outs of various mocking libraries and PowerMock(specifically the EasyMock extension) is next on the list. I'm attempting to mock a constructor and the examples provided don't have the same response when I try to replicate them. As far as I can tell, it never mocks the constructor and just proceeds as if it were normal.
This is the test class:
#RunWith(PowerMockRunner.class)
#PrepareForTest({Writer.class})
public class FaultInjectionSituationTest {
#Test
public void testActionFail() throws Exception {
FaultInjectionSituation fis = new FaultInjectionSituation();
PowerMock.expectNew(Writer.class, "test")
.andThrow(new IOException("thrown from mock"));
PowerMock.replay(Writer.class);
System.out.println(fis.action());
PowerMock.verify(Writer.class);
}
}
I've tried replacing the "test" with an EasyMock.isA(String.class), but it yielded the same results.
This is the FaultInjectionSituation:
public class FaultInjectionSituation {
public String action(){
Writer w;
try {
w = new Writer("test");
} catch (IOException e) {
System.out.println("thrown: " + e.getMessage());
return e.getLocalizedMessage();
}
return "returned without throw";
}
}
The "Writer" is nothing more than a shell of a class:
public class Writer {
public Writer(String s) throws IOException {
}
public Writer() throws IOException{
}
}
When the test is run, it prints out "returned without throw", indicating the exception was never thrown.
You need to prepare the class that is calling the constructor as well, so PowerMock knows to expect a mocked constructor call. Try updating your code with the following:
#RunWith(PowerMockRunner.class)
#PrepareForTest({Writer.class, FaultInjectionSituation.class})
public class FaultInjectionSituationTest {
// as before
}
You need to first create a mock object:
Writer mockWriter = PowerMock.createMock(Writer.class)
PowerMock.expectNew(Writer.class, "test").andReturn(mockWriter)