I want create unit test to test a class which contains another object. I have created a mock to this second object.
When I test a method of my first class, I want verify if the functions of the second object are called. For this, I use the function verify(mock).myfunction();
My problem is that the same function of my object 2 can be called by several function of my first class.
When I write the test class, I write a test function by function but it seems that the "times" isn't reset at the beginning of a test method.
I don't know if I am clear, therefore, an example :
public class Main {
public Object o = createObject();
public void function1(){
o.function();
}
public void function2(){
o.function();
}
public Object createObject() {
return new Object() ;
}
public class MainTest {
private static Main main;
#BeforeClass
public static void setUp() throws Exception {
final Object mockO = mock(Object.class);
main = new Main() {
#Override
public Object createObject() {
return mockO;
}
};
}
#Test
public void testfunction1(){
verify(main.world[0], never()).function();
main.function1();
verify(main.world[0]).function();
}
#Test
public void testfunction2(){
verify(main.world[0], never()).function();
main.function2();
verify(main.world[0]).function();
}
If I test testfunction1() and testfunction2() ignored, it's work.
If I test testfunction2() and testfunction1() ignored, it's work.
But if the two tests are executed, I have an error :
org.mockito.exceptions.verification.NeverWantedButInvoked:
Object.function();
Never wanted here :
-> at test.MainTest.testfunction1
but invoked here :
at source.Main.function2
How I can test independently the two functions?
Rename your setUp() method into something else, make it a non-static method, and make it #Before and not #BeforeClass:
private Main main;
#Before
public void initMain()
{
// what you already do
}
#BeforeClass methods run once before all tests in a class, while #Before methods are run once before each test.
Related
I have a test case that mock a static method of java.lang.System class:
#Test
fun `getLocalTime()`() {
// Arrange
val staticMock = Mockito.mockStatic(System::class.java)
Mockito.`when`(System.currentTimeMillis()).thenReturn(1000L)
// Action
val res = deviceTimeProvider.getLocalTime()
// Assert
Truth.assertThat(res).isEqualTo(1000L)
staticMock.close()
}
But when I run the test, I got this error:
org.mockito.exceptions.base.MockitoException: It is not possible to
mock static methods of java.lang.System to avoid interfering with
class loading what leads to infinite loops
Why does this happen? How can I mock methods of java.lang.System class?
While Mockito since 3.4.0 version allows mocking static methods it is not allowed to mock the Thread and System static methods, see this comment on github
Finally note that Mockito forbids mocking the static methods of System (and Thread). Those methods are to much cemented into class loading which happens in the same thread. At some point, we might add instrumentation to class loading to temporarily disable the static mocks within it to make mocking these classes, too, where we also would need to disable their intensification properties. You can however easily mock Instant.now().
If you like ugly solutions you can still mock System with PowerMockito
#PrepareForTest(System.class)
public class TestCase {
#BeforeClass
public void setup() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.currentTimeMillis()).thenReturn(1000L);
}
...
But I would avoid mocking System classes if possible. You can still wrap it in method and mock this method.
To mock the static methods of java.lang.System class with the help of Mockito.
Create an interface i.e ISystem.java
public interface ISystem {
String getProperty(String name);
Long getCurrentTimeInMillis();
}
2- Create the implementation class of ISystem interface i.e ISystemImpl.java
public class ISystemImpl implements ISystem {
#Override
public String getProperty(final String name) {
return System.getProperty(name);
}
#Override
public Long getCurrentTimeInMillis() {
return System.currentTimeMillis();
}
}
3- Use Isystem.java inside your DeviceTimeProvider.java class.
public class DeviceTimeProvider {
#NonNull private final ISystem mISystem;
public DeviceTimeProvider(ISystem iSystem){
mIsystem = iSystem;
}
public Long getLocalTime(){
return mIsystem.getCurrentTimeInMillis()
}
}
4- Now finally mock the ISystem interface inside your test class.
public class DeviceTimeProviderTest {
private ISystem mISystem;
private DeviceTimeProvider sut;
#Before
public setup(){
mIsystem = mockito.mock(ISystem.class)
sut = new DeviceTimeProvider(mISystem);
}
#Test
public void getDeviceLocalTime(){
Long expectedTime = 1000L;
mockit.when(mISystem.getCurrentTimeInMillis()).thenReturn(expectedTime);
Long actualTime = sut.getLocalTime();
Assert.assertEquals(actualTime, expectedTime);
}
}
OUTPUT
I have a private method whose invocation I want to test without caring about the arguments. I want to test if it was called at all or not.
MyClass.java
public void doStuff(){
unload(args);
}
private void unload(List<String> args) {
//
}
So I used following:
MyClasstest.java
MyClass myClass = PowerMockito.spy(new MyClass());
myClass.doStuff();
verifyPrivate(myClass, times(1)).invoke("unload",any(List.class));
// verifyPrivate(myClass, times(1)).invoke("unload",any()); //same result with this
This test fails with following exception:
Wanted but not invoked com.MyClass.unload(
null );
However, there were other interactions with this mock .......
(actual values with which it was called)
Can verifyPrivate be called with only actual arguments & not with any()?
Here is a working example of what you are trying to do:
You might just missing the #PrepareForTest annotation, which has to point to the correct class. If your class is an external one use #PrepareForTest(MyClass.class), the example below shows it with an internal class.
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClassTest.class)
public class MyClassTest {
static class MyClass {
public void doStuff(){
unload(null);
}
private void unload(List<String> args) {
}
}
#Test
public void test() throws Exception {
MyClass myClass = PowerMockito.spy(new MyClass());
myClass.doStuff();
PowerMockito.verifyPrivate(myClass, Mockito.times(1)).invoke("unload", Mockito.any());
}
}
Note that you should consider whether you really want to do this in a UnitTest. Normally your UnitTest should not be concerned about whether a private method is used or not, it should be focused on verifying that the correct result is returned or the correct object state is reached.
By adding knowledge about the internal behaviour of the class into it, you test is tightly coupled to the implementation which might not be a good thing.
I am unable to mock anything(static or non static methods) from mockito,
These are my classes,
Calculations.java
public class Calculations {
public void printZero() {
System.out.println("zero");
}
public static void printOne() {
System.out.println("one");
}
}
This is my PostData.java
public class PostData {
public static Calculations calc = new Calculations();
public static void postTheData() {
calc.printZero();
Calculations.printOne();
}
}
The unit test class,
TestClass.java
public class TestClass {
#Test
public void addTest() {
Calculations lmock = mock(Calculations.class);
// can't have Calculations.calc.printZero() in when() :cause: argument passes to when() must be a mock object.
doNothing().when(lmock).printZero();
// cause: method when(void) is undefined for the type TestClass
// when(lmock.printZero()).doNothing();
// cause: argument passed to when() must be a mock object.
// doNothing().when(Calculations.printOne());
PostData.postTheData();
}
}
Its compiled and its printing "zero" as well as "one" in my output, which ideally should have been ignored.
I am using cloud-mockito-all-1.10.19.jar for mockito.
And junit's latest jar file.
I know I am missing something here, but can't figure out what! It would be a great help if you can answer me.
The problem is that PostData doesn't use the mocked Calculations object.
In order to do it, you can add a setter for calc field (and perhaps change it to be non static) and set PostData's calc field to the mocked one.
Is there any reason why Powermock wouldn't mock static method call and instead call the initial method within then() statement?
Here's the case where I have a chain of method calls:
TestClass method -call-> Class1 method -call-> Class2 static method -call-> Class3 static method -call-> Class4 method.
Class4 method tries to lookup an object that doesn't exist in context and hangs so I'm trying to mock public static Class3 method with Powermock.
All classes and methods are non-final.
I use TestNg. My testMethod has a #PrepareForTest
I tried the following ways to mock a method call:
PowerMockito.mockStatic(Class3.class);
when(Class3.callEvilMethod()).thenReturn("test");
OR instead of when-thenReturn:
doReturn("test").when(Class3.callEvilMethod());
OR
doAnswer(new Answer() {methos that returns test"}).when(Class3.callEvilMethod());
OR
PowerMockito.stub(PowerMockito.method(Class3.class, "callEvilMethod")).toReturn("test");
But when I run tests the initial Class3.callEvilMethod() gets called within when statement. And I have no idea why. Shouldn't it be mocked?
EDIT: I adapted my test to show you how it looks like:
#PrepareForTest( { Class1.class, Class2.class, Class3.class})
public class TestClass extends AbstractTest {
private Class1 class1;
#BeforeMethod
public void setUp() throws Exception {
class1 = new Class1() {
}
#Test
public void testMethod() throws Exception {
// Create various objects in Db, do other method calls, then:
PowerMockito.mockStatic(Class3.class);
// PowerMockito.suppress(PowerMockito.method(Class3.class, "evilMethod"));
// PowerMockito.when(Class3.EvilMethod()).thenReturn("test");
// doReturn("test").when(Class3.evilMethod());
// PowerMockito.stub(PowerMockito.method(Class3.class, "evilMethod")).toReturn("test");
class1.callMethod();
}
}
Ok what is supposed to fix the problem and was missing in my test is either:
#ObjectFactory
public IObjectFactory setObjectFactory() {
return new PowerMockObjectFactory();
}
or simply sublcassing from PowerMockTestCase
Details
I have a Mainclass that I need to test which is dependent on other class.
Now I am creating a mock for that class
How to test void methods using easymock
MainClass{
mainClassMethod(){
dependencyClass.returnVoidMethod();
//other code
}
}
TestClass{
#Before
setUpMethod(){
DependencyClass dependencyClassMock = EasyMock.createMock(DependencyClass.class);
}
#Test
testMainClassMethod(){
EasyMock.expect(dependencyClassMock.returnVoidMethod()).andRetur //this is not working
dependencyClassMock.returnVoidMethod();
EasyMock.expectLastCall().anyTimes(); //If I use this, it is invoking the method.
}
}
//My dependency class code
DependencyClass implements ApplicationContextAware{
private static ApplicationContext applicationContext;
private static final String AUTHENTICATION_MANAGER = "authenticationManagers";
returnVoidMethod(){
ProviderManager pm = (ProviderManager) getApplicationContext().getBean(AUTHENTICATION_MANAGER); //this is returning null
}
//othercode
//getters and setters of application context
}
As described in the Easymock Documentation you don't put the method inside an expect() (since there is no return). You can just call the mocked method by itself and if it is in "record" mode then it is implied an expect.
dependencyClassMock.returnVoidMethod();
If you need to throw an Exception or say the method can be called anyTimes() you can use expectLastCall()
#Test
public void testMainClassMethod(){
dependencyClassMock.returnVoidMethod();
EasyMock.expectLastCall().anyTimes();
...
//later to replay the mock
EasyMock.replay(dependencyClassMock);
//now this method is actually called
dependencyClassMock.returnVoidMethod();
}
EDIT : Just noticed that you don't have the dependencyClassMock as field:
public class TestClass{
DependencyClass dependencyClassMock
#Before
setUpMethod(){
dependencyClassMock = EasyMock.createMock(DependencyClass.class);
}
...//rest of class is as described above
#dkatzel
the test is completely wrong..... you are calling manually a method and the you verify if it was called...of course it was! ...that's not the right way (my opinion)
A better way (my opinion) would be to extend the mehod class you would like to test, override that method and in the body just put a boolean variable as a flag to k now if the method was called or not....you don't even need to use EasyMock
Example
Class DependencyClass {
public void returnVoidMethod() {
[.... content ...]
}
}
Class A_test {
#Test
public void checkVoidMethodCalled() {
A_mod obj = new A_mod();
mainClassMethod();
assertTrue(obj.called);
}
Class A_mod extends DependencyClass {
boolean called = false;
#Override
public void returnVoidMethod() {
called = true;
}
}
}
You are welcome.