Mock static method in Quarkus - junit

Hi I'm new to Quarkus and I've one Quarkus app which has one filter, from filter I'm calling static method I want to mock that static method call. How can I do that?
#Provider
public class AuthFilter implements ContainerRequestFilter{
#Context
HttpServerRequest request;
public void filter(ContainerRequestContext context) {
if (isPermittedPath()) {
return;
}
String company = Util.getCompany(request.host());
//some code here
}
}
I want to mock call of Util.getCompany(request.host()) method.
I'm following this document to write test cases https://quarkus.io/guides/getting-started-testing

Related

How do I use Mockito to mock a protected method?

I’m using Mockito 1.9.5. How do I mock what is coming back from a protected method? I have this protected method …
protected JSONObject myMethod(final String param1, final String param2)
{
…
}
However, when I attempt to do this in JUnit:
final MyService mymock = Mockito.mock(MyService.class, Mockito.CALLS_REAL_METHODS);
final String pararm1 = “param1”;
Mockito.doReturn(myData).when(mymock).myMethod(param1, param2);
On the last line, I get a compilation error “The method ‘myMethod’ is not visible.” How do I use Mockito to mock protected methods? I’m open to upgrading my version if that’s the answer.
This is not an issue with Mockito, but with plain old java. From where you are calling the method, you don't have visibility. That is why it is a compile-time issue instead of a run-time issue.
A couple options:
declare your test in the same package as the mocked class
change the visibilty of the method if you can
create a local (inner) class that extends the mocked class, then mock this local class. Since the class would be local, you would have visibility to the method.
Responding to the request for a code sample of option 3 from John B's answer:
public class MyClass {
protected String protectedMethod() {
return "Can't touch this";
}
public String publicMethod() {
return protectedMethod();
}
}
#RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
class MyClassMock extends MyClass {
#Override
public String protectedMethod() {
return "You can see me now!";
}
}
#Mock
MyClassMock myClass = mock(MyClassMock.class);
#Test
public void myClassPublicMethodTest() {
when(myClass.publicMethod()).thenCallRealMethod();
when(myClass.protectedMethod()).thenReturn("jk!");
}
}
You can use Spring's ReflectionTestUtils to use your class as it is and without needing of change it just for tests or wrap it in another class.
public class MyService {
protected JSONObject myProtectedMethod(final String param1, final String param2) {
return new JSONObject();
}
public JSONObject myPublicMethod(final String param1) {
return new JSONObject();
}
}
And then in Test
#RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
#Mock
private MyService myService;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(myService.myPublicMethod(anyString())).thenReturn(mock(JSONObject.class));
when(ReflectionTestUtils.invokeMethod(myService, "myProtectedMethod", anyString(), anyString())).thenReturn(mock(JSONObject.class));
}
}
Something like following worked for me, using doReturn() and Junit5's ReflectionSupport.
[Note: I tested on Mockito 3.12.4]
ReflectionSupport.invokeMethod(
mymock.getClass()
// .getSuperclass() // Uncomment this, if the protected method defined in the parent class.
.getDeclaredMethod("myMethod", String.class, String.class),
doReturn(myData).when(mymock),
param1,
param2);
John B is right, this is because the method you're trying to test is protected, it's not a problem with Mockito.
Another option on top of the ones he has listed would be to use reflection to gain access to the method. This will allow you to avoid changing the method you are testing, and avoid changing the pattern you use to write tests, and where you store these tests. I've had to do this myself for some tests where I was not allowed to change the existing code base which included a large number of private methods that needed to be unit tested.
These links explain Reflection and how to use it very well, so I will link to them rather than copy:
What is reflection and whit is it useful
How to test a class that has private methods, fields, or inner classes
WhiteBox.invokeMethod() can be handy.
public class Test extend TargetClass{
#Override
protected Object method(...) {
return [ValueYouWant];
}
}
In Spring, you can set it high high-priority like this:
#TestConfiguration
public class Config {
#Profile({"..."})
#Bean("...")
#Primary // <------ high-priority
public TargetClass TargetClass(){
return new TargetClass() {
#Override
protected WPayResponse validate(...) {
return null;
}
};
}
}
It is the same to override the origin bean.

Powermockito unable to mock the super call

So basically I'm trying to write a Junit using powermockito for a adapter for a service class which consumes a webservice.
I have an adapter with a constructor that inturn creates a new service object in it's own constructor by calling a super class. I have to test my adapter. I have used power mockito to mock my adapter as well as my service class but I don't think the mocked object is able to perform the super call. The following is the structure of my code. I want the super class to return my mocked object upon call.
public class CommonPoolingServiceAdp {
private CPSSecurity cpsServicePort;
public CommonPoolingServiceAdp() {
CommonPoolingService service= new CommonPoolingService();
cpsServicePort=service.getCommonPoolingServicePort();
}
public SercurityDataResponse getBroadcastElements(broadcastReqObj)
{
SercurityDataResponse=null;
response=cpsServicePort.getBroadcastElements(broadcaseRequestObj);
}
}
public class CommonPoolingService extends Service {
{
static
{
//few mandatory initializations
}
public CommonPoolingService()
{
super(WSDL_Location,QName);
}
public CSPSecurity getCommonPoolingServicePort() {
return super.getPort(QName);
}
}
}
Please share a bit more of your code. By the way, this is how you mock a super class method :
public class SuperClass {
public void method() {
methodA(); // I don't want to run this!
}
}
public class MyClass extends SuperClass{
public void method(){
super.method()
methodB(); // I only want to test this!
}
}
#Test
public void testMethod() {
MyClass spy = Mockito.spy(new MyClass());
// Prevent/stub logic in super.method()
Mockito.doNothing().when((SuperClass)spy).methodA();
// When
spy.method();
// Then
verify(spy).methodB();
}
Hope, it will help.

Mocking a class in PowerMock

I am using PowerMocking for JUNIT and Iam new to PowerMock.
I want to mock one class which is non static.
The class scenario goes as follows.
public class Export extends MyUtil implements ExportFormatting<DeptSummaryByDCDTO, LmReportsInputDTO>{
public String createPDF(List<DeptSummaryByDCDTO> summaryDtoList, LmReportsInputDTO inputDto){
}
public String createPDF(Map<String, DeptSummaryByDCDTO> paramMap,
LmReportsInputDTO paramK) {
}
}
The calling class is as follows.
public static Response getMultiplePackSku{
filePath = new Export(inputDto).createPDF(resultList,null);
}
The Question is,
I am trying to test the above class using powermock.
Can anybody tell how to mock the line filePath.....
You need to first mock the constructor and return an Export mock. On the returned mock you need to record the call to createPDF. The tricky part is the constructor mocking. I'll give you an example, hopefully you'll get all of it:
#RunWith(PowerMockRunner.class) // This annotation is for using PowerMock
#PrepareForTest(Export.class) // This annotation is for mocking the Export constructor
public class MyTests {
private mockExport;
#Before
public void setUp () {
// Create the mock
mockExport = PowerMock.createMock(Export.class)
}
#Test
public void testWithConstructor() {
SomeDtoClass inputDto = PowerMock.createMock(SomeDtoClass.class);
PowerMock.expectNew(Export.class, inputDto).andReturn(mockExport);
PowerMock.replay(mockExport, Export.class);
expect(mockExport.createPDF(resultList, null);
// Run the tested method.
}
}
Here is a description of how to mock a constructor call: MockConstructor

JMockit mock protected method in superclass and still test method in real child class

I am still learning JMockit and need help understanding it.
I am testing a class that uses superclass methods. My test gets a null pointer when it attempts to use the superclass method due to code inside it that uses struts action context to get the session and pull an object from the session.
The method I want to bypass the struts session stuff inside the protected method.
public class MyExtendingClass extends MySuperClass{
public void methodIamTesting(){///}
}
public abstract class MySuperClass{
//I want to mock this method
protected Object myProtectedSuperClassMethod(){
// struts action context code that returns an object//}
}
Test code
#Test
public void testRunsAndDoesntPass() {
Mockit.setUpMock(MySuperClass.class, new MySuperClass(){
public Object myProtectedSuperClassMethod() {
return object;
}
});
// real class method invocation happens
assertEquals(expected, actual);
}
I keep getting NullPointers just like if I didn't have the mock
Not sure what to try next. All the docs and code samples I have read say to just declare the superclass method as public in the setUpMock and it should work.
I can't mock the entire class because that is the class I am testing.
I discovered that I needed to create the MockClass then reference it using setupmock correctly.
I am really falling in love with JMockit.
#MockClass(realClass = MyExtendingClass.class)
public static class MockSuperClass {
final Object object = new Object();
#Mock
public Object myProtectedSuperClassMethod() {
return object;
}}
#Test
public void testRunsAndNowWillPass() {
Mockit.setUpMock(MySuperClass.class, new MockSuperClass(){
public Object myProtectedSuperClassMethod() {
return object;
}});
// real class method invocation happens where i set expected and actual
assertEquals(expected, actual);
}
you mask the parent class implementation out totally #Mocked final MySuperClass base
abstract class MySuperClass{
protected Object myProtectedSuperClassMethod(){
}
class MyExtendingClass extends MySuperClass{
public void methodIamTesting(){///}
}
#Test
public void testRunsAndDoesntPass(#Mocked final MySuperClass base ) {
//you could mask out all the base class implementation like this
new Expectations(){{
invoke(base, "myProtectedSuperClassMethod");
}};
// real class method invocation happens
// ...
assertEquals(expected, actual);
}

Unit testing a Play controller using mocks

The title pretty much says it all. I would like to set up a traditional JUnit test to mock a controller's dependencies and run tests against actions.
I've found that I can achieve my goal like this:
public class AccountsControllerTest {
private controllers.Accounts accountsController;
#Test
public void test() {
running(fakeApplication(), new Runnable() {
public void run() {
accountsController = new controllers.Accounts();
accountsController.setAccountsWorkflow(mock(workflow.Accounts.class));
}
});
}
}
The obvious problem here is that I'm instantiating my class under test and injecting mock dependencies from the test method itself, when I should be doing that in the setup() method. It seems that the setup() method is useless if I'm going to test my controller in a traditional way.
Of course I can test controllers the way Play recommends, but my application is dependent on an external SOAP web service, so I need unit tests to show that our code is working when their servers are down.
So, what's the best way to unit test a Play controller using mocks while still taking advantage of setup() and teardown() methods?
Edit
I realize I'm assuming some knowledge here, so for those who are unaware, controller instantiation in a unit test must be wrapped in a running() function or Play! will throw a runtime exception saying that no application has been started.
You could accomplish this using Mockito and Play's FakeApplication and setting the static Http.Context variable.
This way you can write the test like all other JUnit test.
Example:
...
import static play.test.Helpers.status;
import play.test.FakeApplication;
import play.test.Helpers;
import play.mvc.Http;
import play.mvc.Result;
...
#RunWith(MockitoJUnitRunner.class)
public class ApplicationTest {
public static FakeApplication app;
#Mock
private Http.Request request;
#BeforeClass
public static void startApp() {
app = Helpers.fakeApplication();
Helpers.start(app);
}
#Before
public void setUp() throws Exception {
Map<String, String> flashData = Collections.emptyMap();
Http.Context context = new Http.Context(request, flashData, flashData);
Http.Context.current.set(context);
}
#Test
public void testIndex() {
final Result result = Application.index();
assertEquals(play.mvc.Http.Status.OK, status(result));
}
#AfterClass
public static void stopApp() {
Helpers.stop(app);
}