Testing for void methods dependency using EasyMock - java

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.

Related

MockitoException when trying to mock java.lang.System

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

Powermock verifyPrivate does not work with any()

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.

PowerMockito private void method issue

I have below class
class PowerMockitoTest{
private void TestPrivateMethod(){
System.out.println("Inside private method");
}
public void TestPublicMethod(){
System.out.println("Inside public method");
TestPrivateMethod();
}
}
I have created Test class as below
#RunWith(PowerMockRunner.class)
public class PowerMockitoExampleTest {
#Test
public void test() throws Exception {
PowerMockitoTest testclass = PowerMockito.spy(new PowerMockitoTest());
PowerMockito.doNothing().when(testclass,"TestPrivateMethod");
testclass.TestPublicMethod();
}
}
Instead of getting OP as 'Inside public method' I am getting very strange OP as 'Inside private method'. Though i have stubbed private method to do nothing its getting called as well as sysout for public method is not getting printed.
Its working fine when i used PowerMockito.doAnswer() but it requires method to be at package level instead of private.
Write it this way:
PowerMockitoTest testclass = PowerMockito.spy(new PowerMockitoTest());
try {
PowerMockito.doNothing().when(testclass, PowerMockito.method(PowerMockitoTest.class, "TestPrivateMethod")).withNoArguments();
} catch (Exception e) {
e.printStackTrace();
}
testclass.TestPublicMethod();
btw:
Testing is about mocking input and investigating outputs (it can be state of module, result of function or calls to another functions).
You should not mock private methods, as their result should not be treated as an input becouse they are not visible from outside.
The missing part in your code i believe is the #PrepareForTest part. You have to add class name with #PrepareForTest after #RunWith annotation
#RunWith(PowerMockRunner.class)
#PrepareForTest({Class1.class, Class2.class})
public class ClassTest

Dependency verify functions call mockito

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.

Do multiple #Before methods work in Controller inheritance?

I'm trying something similar to this, and only one of the #Before methods gets called:
public abstract class ControllerBase extends Controller {
#Before
static void foo() {
// this actually gets called
}
}
public class ConcreteController extends ControllerBase {
#Before
static void bar() {
// This DOES NOT get called
}
public static void index() {
render();
}
}
Is this a bug, feature, or something I'm doing wrong?
You're trying to do something weird. And I think your example doesn't match your question. Did you mean to implement ConcreteController on ControllerBase? Rather than both of them extending on Controller?
The #before tag is a concrete class tag. Only the one in the concrete class will get executed.
You can #override the original function, but I don't think that's what you were looking for.
The best way to get what you want is to remove #before from the abstract and from the concrete function call the implemented function you want to run.
public abstract class ControllerBase extends Controller {
static void foo() {
// this actually gets called
}
}
public static class ConcreteController extends Controller {
#Before
static void bar() {
foo();
// This DOES NOT get called
}
public static void index() {
render();
}
}
Yes, Play! will call all the methods in the inheritance hiererchy annotated with #Before.
The problem I ran into was that the #Before I was using was actually org.junit.Before instead of play.mvc.Before !

Categories