I am trying to write test case for my java function. My function is something of the following type
public static String parse33_05_x_Data(String message, Transaction transaction){
String returnValue="";
/**
*Some Java code which I actually want to test.
*
**/
//Writing the transaction to the file.
FileManager.getInstance().WriteDataToFile(transaction);
return returnValue;
}
But in the above code I want to somehow ignore/mock the line FileManager.getInstance().WriteDataToFile(transaction);
as it is giving an exception. without making any code changes to the above function itself.
Whatever changes are required should happen inside my Test class
.
Is it possible to do something like this?
Thanks in advance!
You should put the fileManager instance as a param. Then it is possible to mock this instance.
public static String parse33_05_x_Data(String message, FileManager fileManager, Transaction transaction){
String returnValue="";
/**
*Some Java code which I actually want to test.
*
**/
// mock doesnt write
fileManager.WriteDataToFile(transaction);
return returnValue;
}
Alternatively, (you write you dont want to change the method) you can use PowerMockito to mock the static method FileManager.getInstance(), but I would not recommend this, because in my opinion this is a code smell.
You can use a test framework called Mockito to "mock" parameters to a method. This will make it possible to create a FileManager that "doesn't do anything".
You should refactor the fileManager to a parameter to make it mockable
public static String parse33_05_x_Data(String message, Transaction transaction){
String returnValue="";
/**
*Some Java code which I actually want to test.
*
**/
//Writing the transaction to the file.
FileManager.getInstance().WriteDataToFile(transaction);
return returnValue;
}
to:
public static String parse33_05_x_Data(String message, Transaction transaction, FileManager fileManager){
String returnValue="";
/**
*Some Java code which I actually want to test.
*
**/
//Writing the transaction to the file.
fileManager.WriteDataToFile(transaction);
return returnValue;
}
You can then use Mockito to mock objects in your JUnit test cases like this:
@Test
public void test1() {
// create mock
FileManager mockedFileManager = Mockito.mock(FileManager.class);
// define return value for method
when(mockedFileManager.WriteDataToFile()).thenReturn("something");
// use mock in test....
assertEquals(MyObj.parse33_05_x_Data("message") new Transaction(), mockedFileManager), "expected value");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.