Mock a specific constructor - mockito

mockito-1.10.19
powermock-mockito-1.7.1
powermock-1.7.4
junit 4.12
I have a class that has multiple constructors (java). Once constructor calls the other. I want to mock only 1 of the constructors (the one that is called from the other). I cannot change the code unfortunately - I am just testing it. Here is the class to be tested:
import java.io.File;
import java.sql.connection;
public class Foo {
public Foo (Connection connection){
this(connection, new File ());
}
public Foo (Connection connection, File file){
// do stuff
}
// other methods
}
Here is the test class I have written:
import java.io.File;
import java.sql.connection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.legacy.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Foo.class)
#PowerMockIgnore("javax.management.*")
public class FooTest {
#Test
public void testFoo() throws Exception {
Connection mockConnection = Mockito.mock(Connection.class);
Foo fooObj = Mockito.mock(Foo.class);
PowerMockito.whenNew(Foo.class).withArguments(Matchers.notNull(), Matchers.notNull()).thenReturn(fooObj);
Foo newFooObj = new Foo (mockConnection);
assertNotNull ("newFooObj should not be null", newFooObj);
}
}
The problem is that Foo(Connection) is not being entered. Is there something I am missing?

I tried your code with the latest 1.7.x version of Powermock (1.7.4) and it works as you wanted it to. So you might just need to upgrade a few minor versions.

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();
}

Katalon Studio to call custom keyword from other custom keyword

I have 2 CustomKeywords, located in the same package in Katalon Studio project. I try to call one custom keyword from the other one. This code isn’t working in this case:
CustomKeywords.'mypack.myclass.mymethod'()
Keyword, which should be called:
package uploadFile
import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.checkpoint.Checkpoint
import com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords as CucumberKW
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling
import com.kms.katalon.core.testcase.TestCase
import com.kms.katalon.core.testdata.TestData
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import java.awt.Robot
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
import java.awt.event.KeyEvent
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import internal.GlobalVariable
class upload2Files {
#Keyword
def upload(TestObject to, String filePath , String file , String file2) {
WebUI.click(to)
StringSelection ss = new StringSelection("\""+filePath+"\" " +"\""+ file +"\" "+ file2 );
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL)
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
}
Other keyword, where I try to call it:
(new uploadFile.upload2Files()).upload(findTestObject('Object Repository/validateFile/input_originalFile'), (d_directory.toString() + '\\') + detachedTXT1, (d_directory.toString() + '\\') + detachedTXT2)
Error message:
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: uploadFile.upload2Files.upload() is applicable for argument types: (com.kms.katalon.core.testobject.TestObject, java.lang.String, java.lang.String) values
I will explain on the example "(new packagename.classname()).methodname()"
I have keyword1:
package closeAplication
import...
public class closeApp {
#Keyword
public void cmdAdbCloseApp(String ApplicationID){
String CMDclose = ('adb shell am force-stop ' + ApplicationID)
println ('This CMD Windows command will be executed: ' + CMDclose)
Runtime.getRuntime().exec(CMDclose)
}
}
I will use keyword1 in the test case:
def ApplicationID = (GlobalVariable.ApplicationIDds)
CustomKeywords.'closeAplication.closeApp.cmdAdbCloseApp'(ApplicationID)
I want to write another keyword2 and call inside keyword1:
package runAppInMobile
import ...
public class runAppClass {
#Keyword
public void runApp (String ApplicationID){
new closeAplication.runAppClass().cmdAdbCloseApp(ApplicationID) //here's the call of the above keyword1
Mobile.startExistingApplication(ApplicationID)
}
}
(new packagename.classname()).methodname()

Error: Could not find or load main class

I executed this command to compile my program
java -Xms16m -Xmx64m -cp ".:boilerpipe-1.2.0.jar:lib/nekohtml-1.9.13.jar:lib/xerces-2.9.1.jar:lib/langdetect.jar:lib/jsonic-1.2.8.jar" ExampleProgram.java
It reports this error:
Error: Could not find or load main class ExampleProgram.java
Here is ExampleProgram.java:
import java.io.InputStream;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import org.xml.sax.InputSource;
import de.l3s.boilerpipe.document.TextDocument;
import de.l3s.boilerpipe.extractors.ArticleExtractor;
import de.l3s.boilerpipe.sax.BoilerpipeSAXInput;
// Language detect librarys
import com.cybozu.labs.langdetect.*;
import net.arnx.jsonic.JSON;
import net.arnx.jsonic.JSONException;
import java.io.*;
import java.net.*;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class ExampleProgram {
public static void main(String[] args) throws Exception {
EveryDetector evr = new EveryDetector();
InetSocketAddress addr = new InetSocketAddress("127.0.0.1",8080);
HttpServer server = HttpServer.create(addr, 0);
MyHandler hndl = new MyHandler();
hndl.setDetector(evr);
MyHandlerExtractContent hnd2 = new MyHandlerExtractContent();
hnd2.setDetector(evr);
MyHandlerDetectLanguage hnd3 = new MyHandlerDetectLanguage();
hnd3.setDetector(evr);
server.createContext("/",hndl);
server.createContext("/extractcontent",hnd2);
server.createContext("/detectlanguage",hnd3);
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080" );
}
}
Source: https://github.com/remdex/boilerpipe-and-language-detect-api-server
How can I solve my problem?
For me, in Windows environment this worked (My class location : C:/MyFolder/MyClass.java) :
cd C:/MyFolder/MyClass.java
Compiling:
C:/MyFolder/MyClass.java> javac MyClass.java
Executing:
C:/MyFolder/MyClass.java> java -classpath C:/external.jar;. MyClass

The method ListSelectionListener(new ListSelectionListener(){}) is undefined for the type JList

This is a simple program that's supposed to change the background color of a pane from a list of colors. However,
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JCheckBox;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JRadioButton;
import javax.swing.event.ListSelectionListener;
public class JL1st extends JFrame{
private JList list;
private static String[] colornames = {"black","blue","red","white"};
private static Color[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.WHITE};
public JL1st(){
super("title");
setLayout(new FlowLayout());
list = new JList(colornames);
list.setVisibleRowCount(4);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(list));
list.ListSelectionListener(
new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
getContentPane().setBackground(colors[list.getSeletedIndex]);
}
}
);
}
}
I keep getting an error on "ListSelectionListener" The method ListSelectionListener(new ListSelectionListener(){}) is undefined for the type JList
Could it be that I have a missing import or is it just messed up syntax?
Thanks
Problem solved,
ListSelectionListener wasn't imported.

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