jmock mocking a static method

I have a static method in my code that I would like somehow to mock.

I am using jmock.

One way I suppose I could do this is to have "wrapper class" around the static method and mock this but I was hoping for a better solution.

I am going about this the wrong way?

FEEDBACK:

I was going to have a interface and class that had a method that just called the static method. It would allow me to mock the logic by just mocking the call to this wrapper class. (I feel dirty even talking about it :) )


Asked by: Daryl497 | Posted: 28-01-2022






Answer 1

We don't support mocking static methods in jMock because it doesn't fit our design approach. We prefer not to use static methods for significant features that can affect the state of the system. We tend to use them just to support the OO code and make it more readable. That's why we view mocking a static methods as a hint that there's a problem. One exception is where it's in a third-party library, but we would probably wrap that in something more object-oriented anyway.

Answered by: Marcus151 | Posted: 01-03-2022



Answer 2

JMockit is another toolkit which allows mocking of static methods (as well as final methods, constructors, etc.).

I don't see any problem with the judicious use of static methods when designing an otherwise OO solution.

For example, one pattern/idiom I like to use is the static facade, particularly to provide a simpler and easier to use API to the persistence subsystem in a business application. In my opinion, no other solution is more elegant than something like:


    List<Person> peopleAboveAge = 
        find("select p from Person p where p.age >= ?", age);

where the find method is statically imported from a PersistenceFacade class which defines only static methods, and encapsulates how to obtain the proper Session/EntityManager instance. This solution is unit-testing friendly and flexible. I used it in a business application which had 500+ persistent entities, using Hibernate. The static facade helped when we migrated from Hibernate 2 to Hibernate 3, when we migrated from Oracle to Sybase and then back to Oracle, and when we started using JPA annotations instead of "hbm.xml" files for ORM mapping.

Answered by: Grace140 | Posted: 01-03-2022



Answer 3

Powermock is an extension to EasyMock that allows mocking of static methods.

Answered by: Rafael907 | Posted: 01-03-2022



Similar questions

java - Mocking static method in other static method

I have small class that return Properties object populated by message_xx.properties located in my classpath: public class PropertiesUtils { public static Properties loadProperties(Locale locale) { try { ClassLoader loader = getClassLoader(); Properties properties = new Properties(); String filePath = "messages_" + locale.getLanguage().toLowerCase() + ".properties"; InputStream...


java - Mocking a class which uses static void method of another class

public class ProjectIdInitializer { public static void setProjectId(String projectId) { //load spring context which i want to escape in my test } } public class MyService { public Response create(){ ... ProjectIdInitializer.setProjectId("Test"); } } @RunWith(PowerMockRunner.class) @PrepareForTest({ProjectIdInitializer.class}) public class MyServiceTest{ @InjectMocks ...


java - Mocking a static method

Below is the method i want to test. I am using TestNG framework for unit testing. class Random{ List&lt;String&gt; namesOfLinks; public List&lt;String&gt; methodIwantToTest(List&lt;String&gt; cktNames) { Map&lt;String, Graph&gt; maps = DataBaseReader.getGraphs(cktNames); for (Entry&lt;String, Graph&gt; entry : maps.entrySet()) { graphList.add(entry.getVal...


java - Mocking a static method which calls another static method of the same class

I have to write a unit test for a static method which requires mocking another static method of the same class. Sample code: public class A { public static boolean foo(){} public static boolean bar(){ return foo(); } } @PrepareForTest({A.class}) public ATest{ testMethod(){ mockStatic(A.class); when(A.foo()).thenReturn(true); assertTrue(A.bar()); }


java - Mocking static method

I want to mock static method which is called within other static method. public class MyClass { public static void methodA(String s) { ... methodB(s); ... } public static void methodB(String s) { ... } } So, I want to mock methodA, but I want to skip calling methodB. I tried almost all solutions that I was ab...


java - Mocking a static method chain

I am trying to mock a static method StaticClass.staticMethod(id).setContentType("text/plain").build(); I was able to mock static method and its return type using PowerMockito as below : PowerMockito.when(StaticClass.staticMethod(id)).thenReturn(returnValue); But How do I send that value to the chained method setContentType()?


java - Mocking static method in other static method

I have small class that return Properties object populated by message_xx.properties located in my classpath: public class PropertiesUtils { public static Properties loadProperties(Locale locale) { try { ClassLoader loader = getClassLoader(); Properties properties = new Properties(); String filePath = "messages_" + locale.getLanguage().toLowerCase() + ".properties"; InputStream...


java - Mocking a class which uses static void method of another class

public class ProjectIdInitializer { public static void setProjectId(String projectId) { //load spring context which i want to escape in my test } } public class MyService { public Response create(){ ... ProjectIdInitializer.setProjectId("Test"); } } @RunWith(PowerMockRunner.class) @PrepareForTest({ProjectIdInitializer.class}) public class MyServiceTest{ @InjectMocks ...


java - Mocking a static method

Below is the method i want to test. I am using TestNG framework for unit testing. class Random{ List&lt;String&gt; namesOfLinks; public List&lt;String&gt; methodIwantToTest(List&lt;String&gt; cktNames) { Map&lt;String, Graph&gt; maps = DataBaseReader.getGraphs(cktNames); for (Entry&lt;String, Graph&gt; entry : maps.entrySet()) { graphList.add(entry.getVal...


java - Mocking a static method which calls another static method of the same class

I have to write a unit test for a static method which requires mocking another static method of the same class. Sample code: public class A { public static boolean foo(){} public static boolean bar(){ return foo(); } } @PrepareForTest({A.class}) public ATest{ testMethod(){ mockStatic(A.class); when(A.foo()).thenReturn(true); assertTrue(A.bar()); }


java - Mocking static class

I have a method in a class that instantiate a static class instance and call operation on it. public class SomeClass { public void someMethod() { MyClass.MyStaticClass myStaticClassInstance = new MyClass.MyStaticClass( arg1, arg2, arg3 ); myStaticClassInstance.callSomeMethod(); } } public class MyClass { public static class MyStaticClass { public MyStaticClass( Ob...


java - Mocking static method

I want to mock static method which is called within other static method. public class MyClass { public static void methodA(String s) { ... methodB(s); ... } public static void methodB(String s) { ... } } So, I want to mock methodA, but I want to skip calling methodB. I tried almost all solutions that I was ab...


java - Mocking a static method chain

I am trying to mock a static method StaticClass.staticMethod(id).setContentType("text/plain").build(); I was able to mock static method and its return type using PowerMockito as below : PowerMockito.when(StaticClass.staticMethod(id)).thenReturn(returnValue); But How do I send that value to the chained method setContentType()?


Mocking a URL in Java

We have a URL object in one of our Java classes that we want to mock, but it's a final class so we cannot. We do not want to go a level above, and mock the InputStream because that will still leave us with untested code (we have draconian test coverage standards). I've tried jMockIt's reflective powers but we work on Macs and there are problems with the Java agent handler that I haven't been able to resolve.


java - Mocking / Testing a core object in my system

I've been asked to work on changing a number of classes that are core to the system we work on. The classes in question each require 5 - 10 different related objects, which themselves need a similiar amount of objects. Data is also pulled in from several data sources, and the project uses EJB2 so when testing, I'm running without a container to pull in the dependencies I need! I'm beginning to get overwhel...


Mocking java object for unit test

I am looking for a good unit test framework that I can use to mock private methods that can run under JDK 1.4.2. Cheers,


Mocking with java 1.4

Is there any framework, whick allows to mock concrete classes, not only interfaces in java 1.4? I have third party code with a singleton class, where I wanna change one function, without touching orignal code. Is it possible?


Mocking sockets in java with mockito

I am trying to mock the following call: s.socket().bind(new InetSocketAddress(serverIPAddress_, serverPort_), 0); so I can test what the rest of the code does when this fails in predictable ways. I use this in my test case: ServerSocketChannel ssc = mock(ServerSocketChannel.class); when(ServerSocketChannel.open()).thenReturn(ssc); doNothing().when(ssc.socket().bind(any(), a...


Mocking a MySQL server with Java

Since I'm not really proficient with databases, some details may be irrlevant, but I'll include everything: As part of a project in my University, we're creating a website that uses JSP, servlets and uses a MySQL server as backend. I'm in charge of setting up the tables on the DB, and creating the Java classes to interact with it. However, we can only connect to the MySQL server from inside the University,...


java - Is it wise to use mocking in BDD test cases?

We are going to implement a small java application with BDD, which reads an MS excel sheet using POI of apache.org and prints some text based on that excel to the STDOUT. We agreed that the simplest solution would be to create a test.xls for each BDD test case. There was another idea, which is that we should mock the POI library calls and expectations for testing. The reasoning behind this idea is that we don't want...


java - Groovy mocking File factory with Spock

I decided to use the File Factory to mock the File object construction. class FileClass { def basePath def listObjects = [] def createFilePerObject() { listObjects.each {currentObject -&gt; // Use some other libraries for mocking(cant run PowerMockito, Gareth Davis adviced me to use JMockit) // File currentFile = new File("${basePath.toString()}/${currentObject.objectName}") ...


java - Mocking the current time with JRE 1.4

I'm currently restricted to only using JRE 1.4 (java runtime environment) and i have a class which has some current time calculations. I am trying to unit test the class but it seems quite hard as all the mocking tools that i have encountered require annotations which aren't support by JRE1.4. I'd tried using a JRE 1.4 friendly version of mockito but that does not allow me to mock out static classes. Jmockit has a ...


java - Mocking Static Methods

As i did some research i have found out that PowerMock is able to mock static java methods. Can someone explain (technically) what is PowerMock doing different than JUnit and others which can not or do not? And also why static methods are(were) causing issues when they are tried to mock? thanks






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top