I often see someone write
assertThat(Long.valueOf(1), instanceOf(Integer.class));
but am not able to figure out, why and when someone should use ClassName.class (example Integer.class) in java code
I try with https://docs.oracle.com/javase/tutorial/reflect/ resources, still hard to understand it.
Actually calling ClassName.class is popular for example when getting a logger, In this case method expect parameter Class<?> clazz, as LoggerFactory
public static Logger More ...getLogger(Class<?> clazz) {
Logger logger = getLogger(clazz.getName());
...
We can send it simply by using ClassName.class,
see answers about getLogger by class:
I usually do is
private static final Logger logger = LoggerFactory.getLogger(ClassName.class);
Or other:
I prefer
Logger logger = LoggerFactory.getLogger(ClassName.class);
I am not overly familiar with the Hamcrest framework for matching assertions, but this would appear to be from that framework (see examp!e). The contract of the assertThat test function is that it expects parameter 1 to be a value and parameter 2 to be an instance of a class type, it will return true if paramater 1 is of parameter type 2 else false.
So ClassName.class is the actual class (through reflection I guess a reference to the name of the class), instanceOf generates an instance of that class, so instanceOf(ClassName.class) passes an instance of the class to check paramter 1 is the same type.
The overall motivation is to test the assertion that a value of Long 1 is an instance of the Integer wrapper class of the primitive int. I presume would return false in example case.
Hmm I think that makes sense.
Related
I have class TaskType. It has method
public Class<? extends TaskParameters> getTypeParameters() {
return typeParameters;
}
next i want to mock this class and mock this method:
final TaskType TEST_PARAMETERS = Mockito.mock(TaskType.class);
when(TEST_PARAMETERS.getTypeParameters()).thenReturn(ScheduledParameters.class);
Mockito.doReturn(4).when(TEST_PARAMETERS).ordinal();
but i got problem:
error: no suitable method found for thenReturn(java.lang.Class<com.ucp.shard.bulkops.service.executor.ScheduleExecutorTest.ScheduledParameters>)
when(TEST_PARAMETERS.getTypeParameters()).thenReturn(ScheduledParameters.class);
Help, how can i mock this method?
Your question is missing a lot of information, it would be nice if you could update it. For example, you could share the code for TaskType.
First of all, it seems that TaskType is an enum as you are trying to call ordinal(), right? If it's the case, you need to remember that enums are final and cannot be mocked by Mockito by default (please read here for more information). If it's not an enum you can ignore it. :)
Regarding the problem mocking getTypeParameters(), you cannot do it directly due to type erasure (more information here). However, you can solve it using Mockito Answer:
final TaskType TEST_PARAMETERS = Mockito.mock(TaskType.class);
final Answer<Class<ScheduledParameters>> answer = invocation -> ScheduledParameters.class;
when(TEST_PARAMETERS.getTypeParameters())
.thenAnswer(answer);
Mockito.doReturn(4).when(TEST_PARAMETERS).ordinal();
Consider and example as below:
public class LoggerTestClass {
private static final Logger LOGGER = Logger.getLogger(LoggerTestClass.class);
}
In above example parameter passed to getLogger method is hard coded i.e LoggerTestClass.class
Now every time I change the class name I have to change the getLogger method's parameter.
Any other way which will fetch the class name automatically, for example for non static variable we can add this.getClass()
You can use Lombok to achive it in a clean fashion. All you need to do is to put #Log on top of your class and it will give you a log object to work with.
Read more here
Bro,For the question,first of all,we need make clear some concept.
In java,if a identifier is a member of a class,and decorated by 'static' keyword,it's value is Decided in the compile phase.
If the 'final' keyword is added,the identifier is constant,it's value must have a initial value on it is declared.and the value can't be change in the java runtime.
And the interesting thing is, the static constent is only declared inside the class,it can be called 'Classname' + '.' ,but has no connection to the class context.if there's no context ,the identifier con't become dynamic.
I think if let the identifier become dynamic ,there are only two ways:
let the identifier become a variable.remove the 'final' key word.the code look like this:
class Test {
private static Logger LOGGER;
public Test() {
LOGGER = Logger.getLogger(getClass().getSimpleName());
}
}
The 'private' keyword is sufficient if you don't want other classes to access it.
Try the java dynamic proxy. it can change the class in java runtime.
Code happy ~
Welcome to talk with me~
Can you use java 9+? Then solution is pretty simple:
private static final Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass());
As MethodHandles.lookup() creates lookup using caller class. (via Reflection.getCallerClass() but Reflection is internal API, so you need that additional method handle lookup step)
I'm reading the source code about spring, and want to know the class of return value that is generic, What should I do?
public static <T> T getBean(String name) {
assertContextInjected();
System.out.println();
return (T) applicationContext.getBean(name);
}
Unfortunately, in Java the short answer is that you can't. You can consider Generics as basically just a compile-time feature to ensure correct handling. However, the compiled bytecode discards all the type information in a process called "Type Erasure", so effectively what the JVM gets at runtime is simply :
public static Object getBean(String name) {
However, none of that is the root cause of your problem, which is to do with your call. I assume you have something like :
SomeClass someVariable = getBean("someName");
What's happening is that the bean that you have requested is not of type SomeClass (and casting is not going to help you with that) - So what you need to do is figure out what class the bean is that Spring is giving you, and then change the "SomeClass" in the caller to expect that type.
I'm using Mockito 1.9.0. I want mock the behaviour for a single method of a class in a JUnit test, so I have
final MyClass myClassSpy = Mockito.spy(myInstance);
Mockito.when(myClassSpy.method1()).thenReturn(myResults);
The problem is, in the second line, myClassSpy.method1() is actually getting called, resulting in an exception. The only reason I'm using mocks is so that later, whenever myClassSpy.method1() is called, the real method won't be called and the myResults object will be returned.
MyClass is an interface and myInstance is an implementation of that, if that matters.
What do I need to do to correct this spying behaviour?
Let me quote the official documentation:
Important gotcha on spying real objects!
Sometimes it's impossible to use when(Object) for stubbing spies. Example:
List list = new LinkedList();
List spy = spy(list);
// Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
// You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
In your case it goes something like:
doReturn(resultsIWant).when(myClassSpy).method1();
In my case, using Mockito 2.0, I had to change all the any() parameters to nullable() in order to stub the real call.
My case was different from the accepted answer. I was trying to mock a package-private method for an instance that did not live in that package
package common;
public class AnimalĀ {
void packageProtected();
}
package instances;
class Dog extends Animal { }
and the test classes
package common;
public abstract class AnimalTest<T extends Animal> {
#Before
setup(){
doNothing().when(getInstance()).packageProtected();
}
abstract T getInstance();
}
package instances;
class DogTest extends AnimalTest<Dog> {
Dog getInstance(){
return spy(new Dog());
}
#Test
public void myTest(){}
}
The compilation is correct, but when it tries to setup the test, it invokes the real method instead.
Declaring the method protected or public fixes the issue, tho it's not a clean solution.
The answer by Tomasz Nurkiewicz appears not to tell the whole story!
NB Mockito version: 1.10.19.
I am very much a Mockito newb, so can't explain the following behaviour: if there's an expert out there who can improve this answer, please feel free.
The method in question here, getContentStringValue, is NOT final and NOT static.
This line does call the original method getContentStringValue:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), isA( ScoreDoc.class ));
This line does not call the original method getContentStringValue:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), any( ScoreDoc.class ));
For reasons which I can't answer, using isA() causes the intended (?) "do not call method" behaviour of doReturn to fail.
Let's look at the method signatures involved here: they are both static methods of Matchers. Both are said by the Javadoc to return null, which is a little difficult to get your head around in itself. Presumably the Class object passed as the parameter is examined but the result either never calculated or discarded. Given that null can stand for any class and that you are hoping for the mocked method not to be called, couldn't the signatures of isA( ... ) and any( ... ) just return null rather than a generic parameter* <T>?
Anyway:
public static <T> T isA(java.lang.Class<T> clazz)
public static <T> T any(java.lang.Class<T> clazz)
The API documentation does not give any clue about this. It also seems to say the need for such "do not call method" behaviour is "very rare". Personally I use this technique all the time: typically I find that mocking involves a few lines which "set the scene" ... followed by calling a method which then "plays out" the scene in the mock context which you have staged... and while you are setting up the scenery and the props the last thing you want is for the actors to enter stage left and start acting their hearts out...
But this is way beyond my pay grade... I invite explanations from any passing Mockito high priests...
* is "generic parameter" the right term?
One more possible scenario which may causing issues with spies is when you're testing spring beans (with spring test framework) or some other framework that is proxing your objects during test.
Example
#Autowired
private MonitoringDocumentsRepository repository
void test(){
repository = Mockito.spy(repository)
Mockito.doReturn(docs1, docs2)
.when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}
In above code both Spring and Mockito will try to proxy your MonitoringDocumentsRepository object, but Spring will be first, which will cause real call of findMonitoringDocuments method. If we debug our code just after putting a spy on repository object it will look like this inside debugger:
repository = MonitoringDocumentsRepository$$EnhancerBySpringCGLIB$$MockitoMock$
#SpyBean to the rescue
If instead #Autowired annotation we use #SpyBean annotation, we will solve above problem, the SpyBean annotation will also inject repository object but it will be firstly proxied by Mockito and will look like this inside debugger
repository = MonitoringDocumentsRepository$$MockitoMock$$EnhancerBySpringCGLIB$
and here is the code:
#SpyBean
private MonitoringDocumentsRepository repository
void test(){
Mockito.doReturn(docs1, docs2)
.when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}
Important gotcha on spying real objects
When stubbing a method using spies , please use doReturn() family of methods.
when(Object) would result in calling the actual method that can throw exceptions.
List spy = spy(new LinkedList());
//Incorrect , spy.get() will throw IndexOutOfBoundsException
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
I've found yet another reason for spy to call the original method.
Someone had the idea to mock a final class, and found about MockMaker:
As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line: mock-maker-inline
Source: https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#mock-the-unmockable-opt-in-mocking-of-final-classesmethods
After I merged and brought that file to my machine, my tests failed.
I just had to remove the line (or the file), and spy() worked.
One way to make sure a method from a class is not called is to override the method with a dummy.
WebFormCreatorActivity activity = spy(new WebFormCreatorActivity(clientFactory) {//spy(new WebFormCreatorActivity(clientFactory));
#Override
public void select(TreeItem i) {
log.debug("SELECT");
};
});
As mentioned in some of the comments, my method was "static" (though being called on by an instance of the class)
public class A {
static void myMethod() {...}
}
A instance = spy(new A());
verify(instance).myMethod(); // still calls the original method because it's static
Work around was make an instance method or upgrade Mockito to a newer version with some config: https://stackoverflow.com/a/62860455/32453
Bit late to the party but above solutions did not work for me , so sharing my 0.02$
Mokcito version: 1.10.19
MyClass.java
private int handleAction(List<String> argList, String action)
Test.java
MyClass spy = PowerMockito.spy(new MyClass());
Following did NOT work for me (actual method was being called):
1.
doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());
2.
doReturn(0).when(spy , "handleAction", any(), anyString());
3.
doReturn(0).when(spy , "handleAction", null, null);
Following WORKED:
doReturn(0).when(spy , "handleAction", any(List.class), anyString());
I have a class in which I see the following things:
this.logger.severe("");
this.logger.warning("");
this.logger.info("");
I do not understand several things:
How can we use a method that was not defined earlier? I mean, there are no "logger" methods defined in the class. I thought that these methods could be defined because the considered class is an extension of another class in which the "logger" is defined. But in the definition of the class there no "extends" statement (only "implements").
I can understand things like that: "objectName.methodName". But what is that "objectName.something1.something2"? "something1.something2" is name of a method? Can method names contain dots?
What exactly these "logger.*" do? I think they save information about the execution of the code. They kind of write report about what happened during the execution. But where I can find this information?
ADDED:
In the beginning of the file I have: import java.util.logging.Logger;
And then in the class I have: private Logger logger = Logger.getLogger("a.b.c.d");
So, logger is an object of the class Logger (but I do not understand why they could not instantiate the class in a usual way using "new Logger()). I also do not understand what exactly logger.severe("") do.
The logger doesn't make anything special. It's all just Java code.
public class SomeClass {
private Logger logger = LogFactory.getLogger(SomeClass.class);
public void doSomething() {
this.logger.debug("foo");
}
}
The this.logger just points to the instance variable named logger of the current instance (this). The this. prefix is by the way superflous in this example. One could also just do logger.debug("foo") here.
If it is not declared in the SomeClass itself, then it's likely been declared in the extending class. Check the class which is declared in extends.
As to your objectName.something1.something2 doubt, have you already looked how System.out.println() works? The System.out returns a PrintStream object which in turn has a println() method. Thus, if objectName.something returns a fullworthy Object with methods, then you can just continue chaining method calls.
Basically,
objectName.something1.something2;
can be translated as
SomeObject someObject = objectName.something1;
someObject.something2;
But if you don't need someObject anywhere else in the code, then it can just be shortened as in your example.
Update: as per your update:
So, logger is an object of the class Logger (but I do not understand why they could not instantiate the class in a usual way using "new Logger()). I also do not understand what exactly logger.severe("") do.
Just read the javadoc of the class in question what it all does. As to why it can't be instantiated, it's because of the factory pattern.
Update 2: as per the another confusion:
I do not understand why they use "this". I mean, if I use just field name, will it not be, by default, the field of this object? I there any difference between "this.x" and "x"?
This way you can be more explicit about which one you'd like to access. If the method contains for example an argument or a local variable with the name logger, then this.logger would still refer to the instance variable.
public class SomeClass {
private Logger logger = LogFactory.getLogger(SomeClass.class);
public void doSomething(Logger logger) {
this.logger.debug("foo"); // Refers to the instance variable.
logger.debug("foo"); // Refers to the method argument.
}
public void doSomethingElse() {
Logger logger = LogFactory.getLogger(SomeClass.class);
this.logger.debug("foo"); // Refers to the instance variable.
logger.debug("foo"); // Refers to the method local variable.
}
}
The logger usually refers to the usage of a class in log4j.
The logger is a member object whose function e.g. severe is called.
The logger usually logs into a file (this can be configured through log4j.xml or some other config file or during the program start).
Edit: Changed the log4j link.
The 'logger' will be another object, not a method. This logger class will have methods defined on it like public void severe(String message)
'something1' will be an object contained by 'objectName'. For example, Car.Engine.Cylinder.Fire(), it's considered bad practise to use a method to fire a car's cylinders like this, and you should do something more like Car.StartEngine() (see the law of demeter for more info)
The logger will keep a record of what's happened in your program, so if there's a crash or a bug later on, you can see what happened. Whether this is recorded to a text file, or to a database somewhere, will be down to the implementation of your logger.
logger is not a method but a class variable which seems to be an object that exposes the methods "severe", "warning" and "info".
Check your class for something like "someClass logger = new someClass();"
The java.util.Logger class is the main access point to the Java logging API. Here is how you create a logger:
Logger logger = Logger.getLogger("myLogger");
The string passed as parameter to the getLogger() factory method is the name of the Logger to create. You can choose the name freely, but the name implies where the Logger is located in the Logger hierarchy. Every . (dot) in the name is interpreted as a branch in the hierarchy.