In junit how to mock literay multivmpoolutil.class? - junit

In my portlet, I'm using MultiVMPoolUtil.getPortalcache("test")
This portet needs to be tested.. For this Mockito
Mock.. Try to set portalcache using mock of above class..
But mock the above class is not running in junit
... When we mock MultiVMPoolUtil
The mockito junit test states that .. Cannot able to mock the liferay
MultiVMpoolutil.class
#Mock
private MultiVmpoolutil
#Before
public void setup()
How to mock this class.. Is there any other way to slove this?

Static classes can be mocked with PowerMock. It´s also my last sword for fighting against util classes. furthermore it also allows very deep manipulation opportunities, like suppressing constructors of super classes or even static initializers (helpful when mocking the PropsUtil).
https://github.com/powermock/powermock
https://github.com/powermock/powermock/wiki/Suppress-Unwanted-Behavior

Related

#RunWith(SpringRunner.class) vs #RunWith(MockitoJUnitRunner.class)

I was using #RunWith(MockitoJUnitRunner.class) for my junit test with mockito. But now i am working with spring boot app and trying to use #RunWith(SpringRunner.class) . Does using #RunWith(SpringRunner.class) has any advantages over using #RunWith(MockitoJUnitRunner.class)? Can i still use feature like #Injectmock, #Mock, #Spy with #RunWith(SpringRunner.class)
The SpringRunner provides support for loading a Spring ApplicationContext and having beans #Autowired into your test instance. It actually does a whole lot more than that (covered in the Spring Reference Manual), but that's the basic idea.
Whereas, the MockitoJUnitRunner provides support for creating mocks and spies with Mockito.
However, with JUnit 4, you can only use one Runner at a time.
Thus, if you want to use support from Spring and Mockito simultaneously, you can only pick one of those runners.
But you're in luck since both Spring and Mockito provide rules in addition to runners.
For example, you can use the Spring runner with the Mockito rule as follows.
#RunWith(SpringRunner.class)
#SpringBootTest
public class MyTests {
#Rule
public MockitoRule rule = MockitoJUnit.rule();
#Mock
MyService myService;
// ...
}
Though, typically, if you're using Spring Boot and need to mock a bean from the Spring ApplicationContext you would then use Spring Boot's #MockBean support instead of simply #Mock.
When SpringRunner.class is used, Spring provides corresponding annotations:
#MockBean
#SpyBean
Mocks are injected to objects under tests via #Autowired annotation. To enable this functionality tests must be annotated with
#SpringBootTest
or
#TestExecutionListeners(MockitoTestExecutionListener.class)
More details and examples can be found in the official documentation: Mocking and Spying Beans
As per the JavaDoc:
SpringRunner is an alias for the SpringJUnit4ClassRunner.
To use this class, simply annotate a JUnit 4 based test class with #RunWith(SpringRunner.class).
If you would like to use the Spring TestContext Framework with a runner other than this one, use org.springframework.test.context.junit4.rules.SpringClassRule and org.springframework.test.context.junit4.rules.SpringMethodRule.
And the JavaDoc of TestContext:
TestContext encapsulates the context in which a test is executed, agnostic of the actual testing framework in use.
That of method getApplicationContext():
Get the application context for this test context, possibly cached.
Implementations of this method are responsible for loading the application context if the corresponding context has not already been loaded, potentially caching the context as well.
So, SpringRunner does load the context and is responsible for maintaining it. For example, if you want to persist data into an embedded database, like H2 in-memory database, you have to use SpringRunner.class; and, to clean the tables to get rid of the records you inserted after every test, you annotate the test with #DirtiesContext to tell Spring to clean it.
But, this is already an integration or component test. If your test is pure unit test, you don't have to load DB, or you just want to verify some method of a dependency is called, MockitoJUnit4Runner suffices. You just use #Mock as you like and Mockito.verify(...) and the test will pass. And it is a lot quicker.
Test should be fast. As fast as possible. So whenever possible, use MockitoJUnit4Runner to speed it up.
Scenario 2019 November : spring-boot : 2.1.1.RELEASE
You have a spring boot api rest
You need to test a service called MySuperSpringService
But, inside MySuperSpringService, are required two more autowires. One to perform a sql select (MyJpaRepository) and another to call an external api rest (MyExternalApiRest)
#Service
public class MySuperSpringService {
#Autowired
private MyRepository innerComponent1;
#Autowired
private MyExternalApiRest innerComponent2;
public SomeResponse doSomething(){}
}
How test MySuperSpringService mocking database and external api rest ?
So, in order to test this service MySuperSpringService which needs another spring beans: MyJpaRepository and MyExternalApiRest, you need to mock them using #MockBean and create the result as you need.
import static org.mockito.Mockito.when;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import junit.framework.TestCase;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = your.package.Application.class)
public class MySuperSpringServiceTest extends TestCase {
#Autowired
private MySuperSpringService serviceToTest;
#MockBean
private MyRepository myRepository;
#MockBean
private MyExternalApiRest myExternalApiRest;
#Before
public void setUp() {
Object myRepositoryResult = new Object();
//populate myRepositoryResult as you need
when(myRepository.findByClientId("test.apps.googleusercontent.com"))
.thenReturn(myRepositoryResult);
Object myExternalApiRestResult = new Object();
//populate myExternalApiRestResult as you need
when(myExternalApiRest.listUserRoles("john#doe.com")).thenReturn(myExternalApiRestResult);
}
#Test
public void testGenerateTokenByGrantTypeNoDatabaseNoGoogleNoSecurityV1(){
SomeResponse response = serviceToTest.doSomething();
//put your asserts here
}
}
you can absolutely use SpringRunner for both unit tests and integration tests.
SpringRunner Tutorial

Junit test case with Mockito

I am creating junit test cases for my project. I have the below code, where I would like to create a mock,
String propertyFilePath = System.getProperty("path.to.properties");
Resource propertyFile = new FileSystemResourceLoader().getResource(propertyFilePath);
Properties properties = PropertiesLoaderUtils.loadProperties(propertyFile);
I am using junit and mockito-core jar. I tried with below code,
System.setProperty("path.to.properties", "dummyPathToProperties"); //invalid Path
Properties properties = mock(Properties.class);
Resource propertyFile = new FileSystemResourceLoader().getResource("dummyPathToProperties");
when(PropertiesLoaderUtils.loadProperties(propertyFile)).thenReturn(properties);
With above code it throws error when mocking loadProperties method. How can I mock a spring static class and return my mock properties object ?
Any help will be really appreciated.
Mocking static methods requires you to go down the full nine yards and make use of PowerMock. The exact steps to mock static methods are outlined in their documentation for example.
In essence:
Use the #RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
Use the #PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.
Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class.
Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to replay mode.
Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify mode.
But of course: consider not using PowerMock; by changing your code so that you don't have to mock the static call. But of course, it is kinda weird to add a wrapper around such a framework-provided static method.

Deep / Nested Dependency Injection in testing

I am using junit, mockito and mockMVC to test the working of a webapp. I am struggling with a dependency whose injecttion I cannot figure out. My webapp structure is as follows.
Class Controller{
#Autowired Service searchService;
#RequestMapping("Search")
public returnType search(#RequestParam("parameter")String parameter){
searchService.doSearch(parameter);
}
}
and the service class
Class Service{
#Autowired Service2 service2;
public returnType doSearch(String parameter){
//some code
service2.call(parameter);
}
}
I need to test the search method for this controller, however service2 is not currently live and hence calls to it have to be mocked. I can mock service2, but cannot figure out how to inject a mock of service2 in my mockMVC instance of controller. As far as I know #InjectMocks in mockito only injects mocks one level deep and not two.
EDIT:
I am using the following to get MockMVC instance of controller
MockMvc controller;
controller = MockMvcBuilders.standaloneSetup(Controller);
What you are essentially want to do is mock a bean.
In your case, you have to mock bean for service2 using #MockBean annotations.
Please refer this article for details.
You don't need that.
Mocking search service will be sufficient as you get the handle of what needs to be done.
Example:
doReturn(...).when(searchService).doSearch(any());
While performing Unit Testing, the developer need to identify the System Under Test and mock/stub all the collaborators.
So, in this case you would write a separate unit test for Controller and Search Service.
Also, read this brilliant article by Martin Fowler - Mocks Aren't Stubs.

What is the scope of the #SuppressStaticInitializationFor PowerMock annotation?

Does anyone know what is the scope of this annotation? For example, if I have multiple JUnit test classes that run sequentially in the same VM, and the first test uses #SuppressStaticInitializationFor, does that suppress the static initialization for all the subsequent test classes, too? I ask because I am under the impression that static state persists for the life of the JVM.
The scope is per classloader. Once you've used #SuppressStaticInitializationFor it'll affect the class in all other tests. You can however #SuppressStaticInitializationFor at the method level instead and that way it won't affect other tests.
you can use #SuppressStaticInitializationFor annotation at the class-level or at the method-level of the test where you want it to be suppressed.
#RunWith(PowerMockRunner.class)
#SuppressStaticInitializationFor("com.main.java.CassName")
public class TestClassName extends PowerMockTestCase {
//code
#SuppressStaticInitializationFor("com.main.java.AnotherClassName")
public void testMethod() {
//code
}
}
This way you can control which method should suppress static initializers(constructors) and for which class.

Eclipse JUnit #Before annotation problem

I'm experiencing some difficulties using JUnit 4.5 in Eclipse, when I use #Before annotation it just does nothing (I may use setUp() which works of course, but I'm just wondering what is wrong), while it works perfectly in Netbeans.. Any thoughts?
Because I cam here via a Google Search, and had to dig quite a bit deeper to see the actual solution:
As #Pace said in the comments, if you extend TestCase, Eclipse treats the Test as JUnit Version 3 or older, and does not respect the #Before annotation - also descripred here: JUnit + Maven + Eclipse: Why #BeforeClass does not work?
Hence, removing the extend TestCase causes fixes the problem
If you are using JUnit 4, you can just annotate the test class or the test method with #Test annotation, instead of extending TestCase.
Since you are using JUnit 4+ there are two ways to write a test case
1 > You make your test class extend TestCase. In this case classes corresponding to Junit 3 are picked up which are not aware of #Before annotation. In this case you will have to override
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
protected void setUp() throws Exception {
}
2 > use annotations. use #Test annotation for the method in the test class that you are interested in running as a test. There is no need for your class to extend TestCase. Also you do not have to override any method. Simply define your own method that has the logic to be executed before the test method runs and annotate it with #Before annotation.