Powermock + Mockito + Testng implementation not working - mockito

So I'm basing my implementation on this site "http://www.handverdrahtet.org/2012/10/unittest-to-verify-that-static-method.html" but it's giving me an error:
-------------------------------------------------------------------------------
Test set: TestSuite
-------------------------------------------------------------------------------
Tests run: 3, Failures: 2, Errors: 0, Skipped: 1, Time elapsed: 1.675 s <<< FAILURE! - in TestSuite
com.example.Activity1Test.shouldShowInputDialogOnUpdateTextButtonClick Time elapsed: 0.005 s <<< FAILURE!
java.lang.reflect.InaccessibleObjectException: Unable to make protected native java.lang.Object java.lang.Object.clone() throws java.lang.CloneNotSupportedException accessible: module java.base does not "opens java.lang" to unnamed module #30cb5b99
at com.example.Activity1Test.shouldShowInputDialogOnUpdateTextButtonClick(Activity1Test.java)
com.example.Activity1Test.afterPowerMockTestMethod Time elapsed: 0.007 s <<< FAILURE!
java.lang.reflect.InaccessibleObjectException: Unable to make protected native java.lang.Object java.lang.Object.clone() throws java.lang.CloneNotSupportedException accessible: module java.base does not "opens java.lang" to unnamed module #4089713
Here is the test() function I used in my Test file:
public void test(String msg) {
JOptionPane.showInputDialog("Enter a string.");
}
Here is the current Test file:
package com.example;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.*;
import javax.swing.*;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.Test;
#PrepareForTest(JOptionPane.class)
public class Activity1Test extends PowerMockTestCase {
/**
* Unittest to verify that static method is called with the specified parameter.
*/
#Test
public void shouldShowInputDialogOnUpdateTextButtonClick() {
mockStatic(JOptionPane.class);
Activity1 activity1 = new Activity1();
activity1.test("foo");
verifyStatic(JOptionPane.class);
JOptionPane.showInputDialog("foo");
}
}

Related

Mockito.when method doesn't manage my service call

i'm trying to make Unit Test testing a simple GET controller method apply MockMvc.perform method but when the controller receive a request the method Mockito.when seems to doesn't manage the method call of MenuService and the test throw an exception. The Exception says menuServiceMock is null
I'm working with Mockito MockMvc JUnit
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import edu.AG.LandingPageSanpietro.domain.Menu;
import edu.AG.LandingPageSanpietro.service.MenuService;
import java.util.Arrays;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
class MenuControllerTest {
private MockMvc mockMvc;
#Autowired
private MenuService menuServiceMock;
#Test
public void testHomeController1() throws Exception {
Menu first=new Menu("titolo1","descrizione1","filename1");
Menu second=new Menu("titolo2","descrizione2","filename2");
Mockito.when(menuServiceMock.getMenus()).thenReturn(Arrays.asList(first, second));
mockMvc.perform(get("/manageMenu"))
.andExpect(status().isOk())
.andExpect(view().name("manageMenu"))
.andExpect(forwardedUrl("/src/main/resources/tamplates/manageMenu.html"))
.andExpect(model().attribute("menus", hasSize(2)));
}
My Controller
#GetMapping("/manageMenu")
public String chiamataGestisciMenu(Model model) {
model.addAttribute("menus", menuService.getMenus());
return "manageMenu";
}
The error
java.lang.NullPointerException: Cannot invoke "edu.AG.LandingPageSanpietro.service.MenuService.getMenus()" because "this.menuServiceMock" is null
at edu.AG.LandingPageSanpietro.controller.MenuControllerTest.testHomeController1(MenuControllerTest.java:44)
I can't understand why when() method doesn't manage my menuServiceMock.getMenus() request for returning the specified list.
Use the annotation #Mock from mockito instead of #Autowired.
Seems like you have not initialized MockMvc. Try Autowiring it or initialize it in #Before method:
#RunWith(SpringJUnit4ClassRunner.class)
#WebMvcTest(controllers = ControllerToBeTested.class)
class MenuControllerTest {
#Autowired
private MockMvc mockMvc;
...
or you can even initialize it in #Before lik this:
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new ControllerToBeTested()).build();
}

Junit mockito unit test case gives null pointer exception

Hello i am new in Junit mockito i am trying to write a unit test
case but when i am run the test case i am getting null pointer
exception.
Code Snip:
package com.dataguise.webservices;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*;
import com.dataguise.cache.CacheManager;
import com.dataguise.controller.CentralController;
import com.dataguise.webservices.beans.DgUserAuthorities;
class RestAPIsTest {
#InjectMocks
private CentralController controller;
#Mock
DgUserAuthorities dgUserAuthorities;
#Mock
private CacheManager cacheManager;
#BeforeEach
public void setup() {
when(this.cacheManager.getCache(anyString())).thenReturn(true);
MockitoAnnotations.initMocks(this);
}
#Test
void testSession() {
try {
dgUserAuthorities = controller.login("d", "d", "", false);
when(controller.login("d", "d", "", false)).thenReturn(dgUserAuthorities);
assertEquals(dgUserAuthorities, dgUserAuthorities);
} catch (Exception e) {
e.printStackTrace();
}
}
}
While the same method call in the rest api gives the appropriate result.
There are 2 errors in your test
Error 1: Mixing JUnit4 and JUnit5 annotations
org.junit.jupiter.api.Test is from JUnit 5
org.junit.Before is from JUnit 4
Thus, your #Before method is never executed. Use org.junit.jupiter.api.BeforeEach instead
Error 2: Using Spring annotations without Spring Extension
#Autowired comes from Spring's DI framework. It will be injected only if you use Spring Injection/ runner
If you want MockitoAnnotations.initMocks(this); to build object under test and inject all mocks, use #InjectMocks
Error 3: confusing way of initializing mocks
There are 2 ways to initialize your mocks:
Manually:
this.dgUserAuthorities = mock(DgUserAuthorities.class);
this.controller = new CentralController(this.dgUserAuthorities);
Using annotations
#InjectMocks
private CentralController controller;
#Mock
DgUserAuthorities dgUserAuthorities;
Annotations require a call to MockitoAnnotations.initMocks(this) or using a Mockito Extension: #ExtendWith(MockitoExtension.class)
I strongly discourage you to mix the 2 approaches.
Also, if you use annotations, do not initialize the fields yourself.

Junit for QueryDsl

I'm trying to write a test case for a query dsl, I'm getting null pointer exception when I run the test case
Dsl Class
QMyClass myClass= QMyClass.myClass;
queryFactory = new JPAQueryFactory(em);
JPAQuery<?> from = queryFactory.from(myClass);
JPAQuery<?> where = from
.where(prepdicates);
orderBy(orderSpecifier).offset(sortOrder.getOffset())
.limit(sortOrder.getPageSize());
**Junit test case:**
import javax.inject.Provider;
import javax.persistence.EntityManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.data.jpa.repository.support.QueryDslRepositorySupport;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.JPQLTemplates;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
#RunWith(PowerMockRunner.class)
public class MyClass{
#Mock
QueryDslRepositorySupport queryDslRepositorySupport;
#Mock
EntityManager entityManager;
#Mock
JPAQueryFactory queryFactory;
#Mock
JPAQuery step1;
#InjectMocks
MyClass myClass;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Provider<EntityManager> provider = new Provider<EntityManager>() {
#Override
public EntityManager get() {
return entityManager;
}
};
queryFactory = new JPAQueryFactory(JPQLTemplates.DEFAULT, provider);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Test
public void sampleTest() throws Exception {
QMyClass class= Mockito.mock(QMyClass.class);
Mockito.when(queryFactory.from(class)).thenReturn(step1);
Predicate step2 = Mockito.mock(Predicate.class);
Mockito.when(step1.where(step2)).thenReturn(step1);
OrderSpecifier step3 = Mockito.mock(OrderSpecifier.class);
Mockito.when(step1.orderBy(step3)).thenReturn(step1);
Mockito.when(step1.offset(Mockito.anyLong())).thenReturn(step1);
Mockito.when(step1.limit(Mockito.anyLong())).thenReturn(step1);
myClass.method("");
}
}
When I run this test case I'm getting null pointer exception at line number 2 in sampleTest() method. I googled but did't find any article for this, not sure why this NE, even after mocking the queryfacotry
Here is the trace :
java.lang.NullPointerException
at com.querydsl.core.DefaultQueryMetadata.addJoin(DefaultQueryMetadata.java:154)
at com.querydsl.core.support.QueryMixin.from(QueryMixin.java:163)
at com.querydsl.jpa.JPAQueryBase.from(JPAQueryBase.java:77)
at com.querydsl.jpa.impl.JPAQueryFactory.from(JPAQueryFactory.java:116)
at
As I mentioned in the comment, your problem is that you do not use a mock, but the real object instead.
Remove the queryFactory initialisation from your setup method.
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Provider<EntityManager> provider = new Provider<EntityManager>() {
#Override
public EntityManager get() {
return entityManager;
}
};
// remove this line
// queryFactory = new JPAQueryFactory(JPQLTemplates.DEFAULT, provider);
}
Also you need to change your implementation, you can not use
queryFactory = new JPAQueryFactory(em); inside your code, as it can not be mocked.
What you could do instead is having a method that returns the JPAQueryFactory,
either from another class - which you can mock -
or in the same method, then you would need to spy on your class instead.
As you didnt add the code for the class you want to test (MyClass - hopefully a different one from the identical named UnitTest?), another possibility would be that you try to use Field or Constructor Injection (as indicated by the use of your annotations), but then there should not be an object creation for the JPAQueryFactory in your code at all.
This also seems to be wrong:
You should inject mocks into your class under test, not in your UnitTest class.
#RunWith(PowerMockRunner.class)
public class MyClass{
...
#InjectMocks
MyClass myClass;

How to register an app for Sony Smart Glass?

I was trying to develop an app in Android Studio 2.1.2 for Sony Smart Glass. I wrote the coding and now I have to register the app so that the Smart Connect can recognize the app, so that it can be used for Sony Smart Glass.
Sony has given few set of instructions to register but I couldn't understand it. Nevertheless I tried my best to register it. I am getting around 13 errors. I have posted my coding below.
package com.example.balakrishnan.newapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements RegistrationInformation {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButonTap(View v) {
Toast myToast = Toast.makeText(getApplicationContext(), "sony smart glass", Toast.LENGTH_LONG);
myToast.show();
}
public void browserapp(View view) {
Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://192.168.72.101/smartglass/datetime.php"));
startActivity(browserIntent);
}
#Override
public int getRequiredControlApiVersion() {
return 4;
}
#Override
public int getTargetControlApiVersion() {
return 4;
}
#Override
public int getRequiredSensorApiVersion() {
// Return 0 if the API is not required for your app
return 0;
}
#Override
public boolean isDisplaySizeSupported(int width, int height) {
boolean isSEG =
(width == HelloLayoutsSEGControl.getSupportedControlWidth(mContext) &&
height == HelloLayoutsSEGControl.getSupportedControlHeight(mContext));
return isSW2 || isSEG;
}
#Override
protected RegistrationInformation getRegistrationInformation() {
return new SampleRegistrationInformation(this);
}
}
Errors:
Error:(13, 64) error: cannot find symbol class RegistrationInformation
Error:(60, 15) error: cannot find symbol class RegistrationInformation
Error:(37, 5) error: method does not override or implement a method from a supertype
Error:(31, 5) error: method does not override or implement a method from a supertype
Error:(43, 5) error: method does not override or implement a method from a supertype
Error:(49, 5) error: method does not override or implement a method from a supertype
Error:(52, 75) error: cannot find symbol variable mContext
Error:(52, 27) error: cannot find symbol variable HelloLayoutsSEGControl
Error:(53, 84) error: cannot find symbol variable mContext
Error:(53, 35) error: cannot find symbol variable HelloLayoutsSEGControl
Error:(55, 16) error: cannot find symbol variable isSW2
Error:(59, 5) error: method does not override or implement a method from a supertype
Error:(61, 20) error: cannot find symbol class SampleRegistrationInformation
:app:compileDebugJavaWithJavac FAILED
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Follow these steps for registration process:
Create a class that extends RegistrationInformation.
Override the methods to define the API versions used.
Override the getExtensionRegistrationConfiguration() method to define your app’s registration info.
Override the isDisplaySizeSupported() method to define which accessories your app supports.
Return an instance of RegistrationInformation in your ExtensionService class.

cannot resolve method "when"

I'm following the Vogella tutorial on Mockito and get stuck pretty much immediately. IntelliJ displays cannot resolve method 'when' for the class below.
...what did I miss?
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
#Test
public void test1() {
MyClass test = Mockito.mock(MyClass.class);
// define return value for method getUniqueId()
test.when(test.getUniqueId()).thenReturn(43);
// TODO use mock in test....
}
}
The method when() is not part of your class MyClass. It's part of the class Mockito:
Mockito.when(test.getUniqueId()).thenReturn(43);
or, with a static import:
import static org.mockito.Mockito.*;
...
when(test.getUniqueId()).thenReturn(43);
you are trying to get when from the mocked class. You need to do something like:
...
MyClass test = Mockito.mock(MyClass.class);
Mockito.when(test.getUniqueId()).thenReturn(43);
...

Resources