Can a Controller be Invoked from a normal Java Class - java

Wanted to know if it is possible to invoke a controller and return a view from a normal Java File.
For Example:
#Controller
class ToBeInvokedController {
#RequestMapping(value="/invoke")
public String invokedMethod() {
return "view_name";
}
}
class DemoJava{
//Want to Invoke the method InvokedMethod() of ToBeInvokedController class and return the view_name
}

Just Create an object of it and invoke it like normal method.
Like :
class DemoJava{
ToBeInvokedController c = new ToBeInvokedController();
String s = c.InvokedMethod();
System.out.print(s)
}

Wanted to know if it is possible to invoke a controller and return a
view from a normal Java File.
Yes, you can but you need to instantiate the ToBeInvokedController class Since it's a non-static method.
ToBeInvokedController obj = new ToBeInvokedController();
obj.InvokedMethod();
if it would have been a static method you can invoke it directly via
ToBeInvokedController.InvokedMethod();
I strong suggest you to use camelCase convention when naming methods in Java

Related

Returning a generic in java without casting it?

I have an interface like so
public interface ClientBuilder <Client> {
Client build();
}
and it's being used in a function like this
private static Service createImpl(ClientBuilder clientBuilder) {
return new serviceImpl((x) clientBuilder.build());
}
Is there a way where I wouldn't have to type cast it, so that I can remove the (x)? It's not entirely necessary, just would be a nice to have
Yes. You make ClientBuilder generic in the function. And, you should follow Java naming conventions. serviceImpl looks like a method name (and x looks like a variable not a class name). But using your names, something like
private static Service createImpl(ClientBuilder<x> clientBuilder) {
return new serviceImpl(clientBuilder.build());
}

EasyMock - Throwing NullPointerexception due to not accessible to parent class private object(i18n)

A)
Class Parent4{
private I18nUtils i18n;
//-----------Here Nullpointerexception occur----------------
public Parent4(){
SetText(i18n.getText("HELLO");
}
}
B)
Class Parent3 extends Parent4{
private I18nUtils i18n;
}
C)
Class ParentParent2 extends Parent3{
private I18nUtils i18n;
}
D)
Class Parent extends ParentParent2{
private I18nUtils i18n;
}
E)
Class Child extends Parent{
protected method_name(){
//.......DO Something......
}
}
My Test Class:
public testclass{
Class cls = Class.forName("Child");
Object obj = cls.newInstance();
Method method = cls.getDeclaredMethod("method_name",Null);
method.setAccessible(true);
method.invoke(obj, null);
So while creating object of child class it called and invoke all dependency of child class and initialize with mock object and called all parent class and its constructor.
While i18n is set null by default.
1) I tried to accessed with reflection. with the help superClass().getDeclared("i18n"). But eventually it only access to its preceding class only. So it not set the value for Parent5() class.
2) Also I have tried to direct access Parent5 class i18n field.
But when invoking the child class. It will create new instance and same as that it will reset parent5() class i18n as null.
I will answer following one of your comments.
Yes, calling another method instead of super and using a partial mock is a correct solution. EasyMock can't mock super.
Then, if you want to mock a method called by a constructor, that's indeed impossible. EasyMock doesn't provide a way to mock before having the mock.
In both cases, modifying the design will probably improve the design.
I probably handle this situation. I read the Easymock documentation. From there I got some similar case to handle this kind of situtation.
Code here:
Objenesis objenesis = new ObjenesisStd(); // or ObjenesisSerializer
child obj_1 = objenesis.newInstance(child.class);
Method method = obj_1.getClass().getDeclaredMethod("method_name",MessageReceiver.class);
method.setAccessible(true);
method.invoke(obj_1, null);
For my case it working fine. As such I did not able to mock parent field anywhere.
NOTE: I did not have any field dependency of parent class on my child class method. Only I need to mock the (i18n) field so it does not cause "nullpointerexception". But eventually I handle with objensis.

Mockito: Mocking different classes method in a specific class scope

I'd like to do this mocking with Mockito
MyServiceClass
(this isn't the actual code, just a fake example with a similar intent)
public String getClassObjects() {
OtherClassObject otherclass = OtherClassObject.createOtherClassObject();
String id = otherclass.getParentObject().getId();
return id;
}
So essentially I want to mock ".getId()" but only in the context of this class "MyServiceClass" if I call the same method of "getId()" in a different class I want to be able to mock a different return.
This will return "3" in every method call for the OtherClassObject
new MockUp<MyServiceClass>() {
#Mock
public String getId(){
return "3";
}
};
Is there a way to isolate method calls for a class object within the scope of a specific class?
Plain Mockito is unable to mock static calls, so you need PowerMock here. To achieve desired you should return different values from the mocked object like this
// from your example it's not clear the returned type from getParentObject method.
// I'll call it ParentObj during this example. Replace with actual type.
ParentObj poOne = mock(ParentObj.class);
when(poOne.getId()).thenReturn("3");
ParentObj poTwo = mock(ParentObj.class);
when(poTwo.getId()).thenReturn("10");
...
OtherClassObject otherClassObjectMock = mock(OtherClassObject.class);
// return all your stubbed instances in order
when(otherClassObjectMock.getParentObject()).thenReturn(poOne, poTwo);
PowerMockito.mockStatic(OtherClassObject.class);
when(OtherClassObject.createOtherClassObject()).thenReturn(otherClassObjectMock);
Thus, you can customize your mocks per needs, specifying desired return value, or propagating call to actual (real) method.
Don't forget to use annotations #RunWith(PowerMockRunner.class) and #PrepareForTest(OtherClassObject.class) on class level to activate the magic of PowerMock.
An alternative idea is to get rid of static call inside your getClassObjects method and pass factory using constructor, so you can easily mock it, setting mocked object only for single class.
Hope it helps!

Java: Is it possible to add / attach a proxy to a live object instance during runtime?

I know Java supports proxies. I've been checking Javassist but not sure whether it can support the following trick:
public class Hello {
public void hi() {
System.out.println("hi");
}
}
Hello hello = new Hello();
Hello proxyHello = createProxy(hello);
proxyHello.hi(); // method will be intercepted by a predefined proxy
Is it possible to do something like that?
What is available in the JDK only allows to create proxies that implement a set of interfaces, if you want to create a proxy of a Class, you will need to use Javassist but to be able to do it you need a constructor that is accessible from the class where you create your proxy.
Here is a way to implement what you need:
final Hello hello = new Hello() {
public void hi() {
System.out.println("Hello World");
}
};
ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(Hello.class);
MethodHandler handler = (self, m, proceed, args) -> {
// This allows to proxy even non accessible methods, it could not be
// needed depending on your context
if (!m.isAccessible())
m.setAccessible(true);
return m.invoke(hello, args);
};
Hello proxy = (Hello)factory.create(new Class<?>[0], new Object[0], handler);
proxy.hi();
Output:
Hello World
In this example:
First I create my factory
Then I provide the super class
Then I define how to handle all method calls on the proxy (here I delegate everything to my live object)
Finally I create my proxy (here I use the default constructor to create the proxy).
More details here
Assuming that you have a constructor with one String argument you will need to modify the last line as next:
Hello proxy = (Hello)factory.create(
new Class<?>[]{String.class}, new Object[]{"bar"}, handler
);
Here I call a constructor with one argument of type String and I provided bar as value.
You can use java.lang.reflect.Proxy to accomplish something like this.
https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html

Mocking helper class with Mockito

I have a plain helper class with public methods which I am using in the service level class. When I am writing test for the service class and trying to mock this helper class for one of the method it is going inside the methods and running every line. Since code inside this method is more complex I want to mock helper class with method(s) so that I don't have to take care of every detail inside helper class method.
Service Class
class HistoryServiceImpl implements CaseHistory {
#Override
public List<CaseHistoryDto> getCaseHistory(Individual member, Individual provider) {
MemberUtil memberUtil = new MemberUtil();
List<CaseHistoryDto> caseHistoryDtoList = new ArrayList<CaseHistoryDto>();
List<CaseHistory> caseHistoryList = caseDetailDao.fetchCaseHistory(member.getId(), provider.getId());
for(CaseHistory caseHistory : caseHistoryList) {
CaseHistoryDto caseHistoryDto = new CaseHistoryDto();
caseHistoryDto.setMemberInfo(memberUtil.getMemberInfo(member, caseHistory.getCreateDate()));
caseHistoryDtoList.add(caseHistoryDto);
}
return caseHistoryDtoList;
}
}
Test Class
Class HistoryServiceTest {
#Mock MemberUtil memberUtil;
#InjectMocks private HistoryServiceImpl historyServiceImpl = new HistoryServiceImpl();
#Test
public void testGetCaseHistory() {
//why this line going inside real method and executing all lines?
when(memberUtil.getMemberInfo(any(Individual.class), any(Date.class))).thenReturn(member);
}
}
The reason that your test case is running all the lines in the "real" method, is because your mock object is never being used anywhere.
As written, you cannot mock MemberUtil in your HistoryServiceImpl, because you are manually instantiating it in the getCaseHistory() method. You need to make getCaseHistory() get its MemberUtil from somewhere else, so that you can inject your mock version in your test class.
The simplest solution would be to define your MemberUtil as a member variable, so that the #InjectMocks annotation can override the default value:
class HistoryServiceImpl implements CaseHistory {
MemberUtil memberUtil = new MemberUtil();
#Override
public List<CaseHistoryDto> getCaseHistory(Individual member, Individual provider) {
...
}
}
Alternately you could have HistoryServiceImpl accept an externally provided MemberUtil, either in its constructor or via a setter method. You can then easily pass in a mocked version in your test class.
Generally, utility classes are stateless, so another possible solution would be to convert MemberUtil to make all of its methods static. Then you can use something like PowerMock to mock your static methods.

Categories

Resources