Mocking the object inside the class without PowerMock - junit

I want to mock the object inside the class wihtout using Powermock. How can I do it?
I tried using spy but it didn't work.
/** SOURCE CODE **/
abstract class Parent {
protected final Caller caller = new Caller();
public abstract void call(Connection, Integer);
}
class Child1 extends Parent {
#Override
public void call(Connection con, Integer id1) {
// some logic
caller.getSomething1(connection, id1);
}
}
class Child2 extends Parent {
#Override
public void call(Connection con, Integer id2) {
// some logic
caller.getSomething2(connection, id2);
}
}
class Activity {
#Inject
private MyConnection connection;
public Response process(Request r) {
Parent p = ChildFactory.getChild(r); // returns a child based on some logic related to p
p.call(connection, r.getId());
return new Response("SUCCESS");
}
}
/** TEST CODE **/
public class Test {
#InjectMocks
private Activity activity;
#Mock
private Connection connectionMock;
private Caller caller;
#Before
public void setup() throws Exception {
caller = Mockito.spy(Caller.class);
Mockito.doReturn(null).when(caller).getSomething1(Mockito.any(), Mockito.any());
Mockito.doReturn(null).when(caller).getSomething2(Mockito.any(), Mockito.any());
}
#Test
public void testProcess() {
Request r = new Request(1);
Response r = activity.process(r);
Assert.assertEquals(r.getResult(), "SUCCESS");
}
}
I want to mock the caller object created in Parent class. It is going to be consumed by every children. I am not bothered about the result of the calls so I want to mock all calls (i.e. getSomething1, getSomething2) of callers without use of PowerMock.
I tried using spy but it is not using the spied object and it is calling getSomething1 and getSomething2 methods.

You can use ReflectionTestUtils#setField
#Before
public void setup() throws Exception {
caller = Mockito.spy(Caller.class);
Mockito.doReturn(null).when(caller).getSomething1(Mockito.any(), Mockito.any());
Mockito.doReturn(null).when(caller).getSomething2(Mockito.any(), Mockito.any());
// ... obtain children here ...
ReflectionTestUtils.setField(child1, "caller", caller);
ReflectionTestUtils.setField(child2, "caller", caller);
}
Or better you don't instantiate Caller instance inside Child-classes but inject via constructor for example

Related

Mockito using what "When ... thenReturn" returns caused NullPointerException

I have a third party class called Person, one method is to return a string:
public class Person<T> {
public String getName(Object<T> obj) {
// some code here
return "some string"
}
And another third party class called SomeClass, one method is to return a Person object:
public class SomeClass {
public <T> Person<T> createPerson(Object obj) {
// some code here
return new Person<T>(....)
}
}
My class that uses the above two classes to create a person first, then get person's name. I can't make changes to MyClass because it has been system tested successfully:
public class MyClass {
public String myMethod() {
Person<T> person = someClass.createPerson(obj);
return person.getName(...);
// NullPointerException when junit because "person" object is null
}
}
Now I am working on junit to test MyClass to satisfy the code coverage requirements. For some reason, it always gave me NullPointer exception when person.getName() is called by junit.
public class MyClassTest {
#MockBean
private SomeClass someClass;
#Autowired
private MyClass myClass;
#Test
public void test(){
Person<Student> studentPerson =
(Person<Student>)Mockito.mock(Person.class);
Mockito.when(someClass.createPerson(ArgumentMatchers.any()))
.thenReturn(studentPerson);
Mockito.when(studentPerson.getName(ArgumentMatchers.any()))
.thenReturn("some data");
// call real method
myClass.myMethod(); // failed with NullPointerException
I am not sure why studentPerson is not mocked correctly which caused a NullPointerException becacuse it's Null. Can someone please help? Thanks.

How to verify an internal method call using Powermock?

I am trying to use PowerMockito to test a save method by verifying an internal audit() method call.
This internal call is made by auditor object which is being instantiated in an init() method of the class. As it is not injected I will not be able to mock it directly. When I used Mockito to verify it always said "There were zero interaction with the mock".
Question:How exactly do I test the save feature? Kindly help!
public class DaoImpl implements Dao{
private Auditor auditor;
#InjectValue
private ObjectLoader loader;
#InjectValue
private ConfigurationProvider confProvider;
#PostConstruct
public void init() {
//Mock this object instantiation and verify audit is called once
auditor = new SyncAuditor(confProvider.getClientConfiguration(), new EventRegProvider());
}
#Override
public void save(final AuditEvt auditEvt) {
final AuditedEvent auditedEvent = builder.build();
auditor.audit(auditedEvent);
}
Test :
#RunWith(PowerMockRunner.class)
#PrepareForTest({ DaoImplTest.class })
#PowerMockIgnore("javax.management.*")
public class DaoImplTest extends PowerMockito {
#InjectMocks
private DaoImpl dataAccess;
#Mock
private SynchAuditor auditorMock;
#Before
public void setUp() throws Exception {
loader = ObjectLoader.init("JUNIT");
loader.bind(ConfigurationProvider.class, configurationProviderMock);
dataAccess = loader.newInstance(DaoImpl.class);
}
#After
public void tearDown() {
loader.release(dataAccess);
ConnectionMgr.disconnect("JUNIT");
}
#Test
public void testSaveAuditEvent() throws Exception {
PowerMockito.whenNew(SynchAuditor.class).
withArguments(Matchers.any(ClientConfiguration.class), Matchers.any(EventRegProvider.class)).thenReturn(this.auditorMock);
final AuditEvent event = AuditEvent.from(null, "principal", UUID.randomUUID().toString(), "randomText",
new AuditEvtDefn((long) 522, "234242", "234242fdgd", true), SUCCESS, null, new GregorianCalendar());
dataAccess.save(event);
Mockito.verify(auditorMock, times(1)).audit(Matchers.any(AuditedEvent.class));
}
Even PowerMockito.verifyNew says there were zero interaction
PowerMockito.verifyNew(SynchronousAuditor.class,times(1)).withArguments(Matchers.any(AuditorClientConfiguration.class),Matchers.any(EventRegistrationProvider.class));
So, I figured out that java reflection will help in such a situation. You will have to get hold onto the real object and then set mocked object to it.
final Field privateAuditorField = DaoImpl.class.getDeclaredField("auditor");
privateAuditorField.setAccessible(true);
privateAuditorField.set(dataAccess, auditorMock);
Now verify will run sucessfully.
Mockito.verify(auditorMock, Mockito.times(1)).audit(Matchers.any(AuditedEvent.class));

JUnit mocking method call

I am writing a Junit test for a method 'methodA' which is in class 'classA'. In 'methodA' another method 'methodB' of class 'classB' is called. The 'methodB' calls soap web-service. I want to mock this methodB soap web-service call. In this case i am calling classA.methodA. Here i don't find a way that at the time when classB.methodB is called then mock value should get updated. I went through many links about Mockito, but they all refer on updating the mock value from junit class only. So, how can i pass mocked value their.
#Test
public void junitTest() {
String arg1 = "arg1";
classA aObj = new classA();
aObj.methodA(arg1);
}
public classA {
public string methodA(String arg1) {
classB bObj = new classB();
bObj.methodB();
//somwthing on arg1
return result;
}
}
public classB {
public list methodB() {
//web-service call
return list from web - service.
}
}
I am writing a Junit test for a method methodA which is in class
classA
Since you are unit testing methodA of classA, you should be focusing on mocking just the bObj.methodB(); call. You should not get into what it does or doesn't internally.
Not you are creating classB object in methodA which is not the ideal scenario. You should make bObj as the instance variable of classA with appropriate getter, setters and constructor.
Then from you testing class set this classB dependency.
You should structure your code and something tests like this:
class classAMicroTest {
#Test
public void junitTest() {
String arg1 = "arg1";
classA aObj = new classA();
classB mockedBobj = Mockito.mock(classB.class);
Mockito.when(mockedBobj.methodB()).thenReturn(new ArrayList<>());
aObj.setbObj(mockedBobj);
aObj.methodA(arg1);
Mockito.verify(mockedBobj, times(1)).methodB());
}
}
class classA {
classB bObj;
public void setbObj(classB bObj) {
this.bObj = bObj;
}
public String methodA(String arg1) {
bObj.methodB();
// somwthing on arg1
return result;
}
}
class classB {
public List<String> methodB() {
return new ArrayList<>();
}
}

Unit test WCMUsePOJO class

I am writing unit test cases for following class which extends WCMUsePOJO. Now, this class is using a getSlingScriptHelper method shown below.
public class ConstantsServiceProvider extends WCMUsePojo {
private static final Logger logger = LoggerFactory.getLogger(ConstantsServiceProvider.class);
private String var1;
#Override
public void activate() throws Exception {
ConstantsService constantsService = getSlingScriptHelper().getService(ConstantsService.class);
if(constantsService != null) {
var1 = constantsService.getVar1();
}
}
public string getVar1() { return var1; }
}
The question is how do I mock getSlingScriptHelper method? Following is my unit test code.
public class ConstantsServiceProviderTest {
#Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_MOCK);
#Mock
public SlingScriptHelper scriptHelper;
public ConstantsServiceProviderTest() throws Exception {
}
#Before
public void setUp() throws Exception {
ConstantsService service = new ConstantsService();
scriptHelper = context.slingScriptHelper();
provider = new ConstantsServiceProvider();
provider.activate();
}
#Test
public void testGetvar1() throws Exception {
String testvar1 = "";
String var1 = provider.getVar1();
assertEquals(testvar1, var1);
}
}
The only thing that you should "have to"* mock is the SlingScriptHelper instance itself, so that it will mimic the dependency injection of the declared service.
Everything else (e.g. the Bindings instance) can be a concrete implementation, for example:
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.junit.Test;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConstantsServiceProviderTest {
private SlingScriptHelper mockSling = mock(SlingScriptHelper.class);
private ConstantsServiceProvider constantsServiceProvider = new ConstantsServiceProvider();
private Bindings bindings = new SimpleBindings();
#Test
public void testFoo() throws Exception {
//Arrange
final String expected = "Hello world";
final ConstantsService testConstantsService = new TestConstantsService(expected);
when(mockSling.getService(ConstantsService.class)).thenReturn(testConstantsService);
bindings.put(SlingBindings.SLING, mockSling);
//Act
constantsServiceProvider.init(bindings);
//Assert
final String actual = constantsServiceProvider.getVar1();
assertThat(actual, is(equalTo(expected)));
}
class TestConstantsService extends ConstantsService {
String var1 = "";
TestConstantsService(String var1) {
this.var1 = var1;
}
#Override
String getVar1() {
return var1;
}
}
}
The entry point here, as you said above, is via the init() method of the WCMUsePojo superclass (as this method is an implementation of the Use.class interface, this test structure also works for testing that via that interface, even if you don't use WCMUsePojo directly.)
*this could be any type of test-double, not necessarily a mock.
You shouldn't create a mock for ConstantsServiceProvider.class if you want to unit-test it. Instead, you should create mocks of its internal objects. So:
Create real instance of ConstantsServiceProvider with new
Mock objects that are returned by getSlingScriptHelper().getService(.) methods. Usually, dependencies are provided (injected) to classes by some container like Spring or simply provided by other classes of your app using setters. In both cases mocks creation is easy.
If your current implementation doesn't allow this - consider refactoring.
You are testing void activate() method which doesn't return anything. So, you should verify calling constantsService.getVar1() method.
I strongly advice you to study Vogella unit-testing tutorial
Here one of possible solution.
The main idea is to have a real object of your class but with overridden getSlingScriptHelper() to return mocked scriptHelper.
I mocked the ConstantsService as well but may be not needed, I don't know your code.
public class ConstantsServiceProviderTest {
#Mock
public SlingScriptHelper scriptHelper;
#Test
public void getVar1ReturnsActivatedValue() throws Exception {
// setup
final String expectedResult = "some value";
// Have a mocked ConstantsService, but if possible have a real instance.
final ConstantsService mockedConstantsService =
Mockito.mock(ConstantsService.class);
Mockito.when(
mockedConstantsService.getVar1())
.thenReturn(expectedResult);
Mockito.when(
scriptHelper.getService(ConstantsService.class))
.thenReturn(mockedConstantsService);
// Have a real instance of your class under testing but with overridden getSlingScriptHelper()
final ConstantsServiceProvider providerWithMockedHelper =
new ConstantsServiceProvider() {
#Override
SlingScriptHelper getSlingScriptHelper() {
return scriptHelper;
}
};
// when
String actualResult = providerWithMockedHelper.getVar1();
// then
assertEquals(expectedResult, actualResult);
}
}

JUNIT test case for void method

I have a method whose JUnit test case I have to write. It just calls the main processing method of the project and does nothing else. Also, the main processing method also has return type as void.
How shall I test such a "method1"?
public void method1() {
obj1.mainProcessingMethod():
}
Given a class:
public class A {
private Obj obj1;
public void method1() {
obj1.mainProcessingMethod();
}
public void setObj1(Obj obj1) {
this.obj1 = obj1;
}
}
In test for this class, the only thing to test would be verification whether method obj1.mainProcessingMethod() was invoked exactly once.
You can achieve this with Mockito.
import org.junit.Test;
import org.mockito.Mockito;
public class ATest {
private Obj obj1 = Mockito.mock(Obj.class);
private A a = new A();
#Test
public void testMethod1() {
a.setObj1(obj1);
a.method1();
Mockito.verify(obj1).mainProcessingMethod();
}
}
Here you create a mock object for class Obj, inject it into instance of A, and later use mock object to check which method invocations it recorded.
Inside the test you need to verify that the method mainProcessingMethod(): is called on the object obj1.
you can use something like
Mockito.verify(yourMockObject);