FAQ Database Discussion Community


Can Mockito verify total number of method calls on a mocked Object?

java,unit-testing,mockito
Mockito's verify can assert a certain number of interactions with a method on a mocked object occurred. // Given SomeService someService = mock(SomeService.class); // When someService.prepare(); someService.prepare(); // Then verify(someService, times(2)).prepare(); // test passes Sometimes it is useful in unit tests to know that the total number of method invocations...

Mocking dependency that has setListener(…)

java,multithreading,testing,mocking,mockito
My class under test has a few dependencies. All of these provide setListener() as a way to receiving notification from their non-blocking operations. I implemented a blocking method that aggregates the results from all the non-blocking ops. Which mean I have to register the listeners using such setListener() methods, and...

Why do I need mockito for testing Spring applications?

java,spring,mockito
Im trying to understand how all things are related with Spring. However I do not understand why mockito is used when unit testing spring code? Can not spring handle to same DI that mockito does? What is it that mockito contributes that is not possible to do with pure spring?...

Mock class inside REST controller with Mockito

java,testing,junit,spring-boot,mockito
I have a spring-boot application which exposes a REST interface via a controller. This is an example of my controller: @RestController public class Controller { @Autowired private Processor processor; @RequestMapping("/magic") public void handleRequest() { // process the POST request processor.process(); } } I am trying to write unit tests for...

Mockito doThrow() not acting as I expect

java,unit-testing,junit,mockito,stubbing
I'm working on my UnitTests related to a project that uses WebDrivers, WebElements and so on. I got pretty far with mocking connections and everything but there is one problem I'm stuck with. I got a try block in my class that looks similar to class MyClass { myMethod() {...

How to mocking according to the received parameter?

java,unit-testing,mockito
According to the parameters that the method receives, desire to return something different. How to do it using the Mockito? For example, according to the id of "Planilha" I desire a different return but do not know how to make this equality. My test @Test(expected = InternalServerErrorException.class) public void testReadMetadados_invalidPlanilha_invalidFormat()...

Can an abstract class be mocked using mockito?

unit-testing,junit,mocking,mockito,abstract-class
In a class under test, if its constructor takes in an abstract class parameter can we mock it using mockito? Ex public abstract AbstractClass{ } //Class under test public class SourceClass{ SourceClass(AbstractClass abstractClass){} } @RunWith(MockitoJUnitRunner.class public SourceClassTest{ @Mock AbstractClass abstractClass; } whenever I do this i get this error java.lang.ExceptionInInitializerError...

Mock java.time.format.DateTimeFormatter class

java,mockito,powermock
I'm trying to mock the DateTimeFormatter class. I've done the following: @RunWith(PowerMockRunner.class) @PrepareForTest({DateTimeFormatter.class}) public class UnitTest { private DateTimeFormatter mockDateFormatter; private AwesomeClass awesomeClass; @Before public void setUp() { mockDateFormatter = PowerMockito.mock(DateTimeFormatter.class); awesomeClass = new AwesomeClass(mockDateFormatter); } @Test public void shouldToTestSomethingAwesome() { // Other test code PowerMockito.when(mockDateFormatter.format(any(LocalDate.class)))...

Test a void method with conditioned loop using mockito

java,unit-testing,junit,mocking,mockito
I have following method which asks for user input until valid user credentials are entered.It then generates id for that user and sets registered =TRUE. 1.How can I check the value of local variable "registered" from my unit test? 2.How can I assert in my test that while loop executed...

Alternatives to mock an static method

java,junit,static,mocking,mockito
I am developing a desktop application, I want to test the method foo of MyClass and I have the following scenario: MyClass: import package.MainWindow; public class MyClass{ public int foo(){ //some logic // . . . boolean result = getResult(); if (result) { MainWindow.printInMain("Success"); return 1; } else { MainWindow.printInMain("Fail:...

Mockito - verify object not invoked at all

java,mockito
How can you verify a mocked object is not invoked at all? I am trying to test the empty implementation of an interface method using Mockito.

should we avoid to use spring managed bean when it is unnecessary?

java,spring,refactoring,mockito,static-methods
Say I have a relative complex class which needs to be simplified by breaking into few smaller helper classes. One suggested refactor solution is : public class RefactoredComplexClass { private final Helper1 h1; private final Helper2 h2; // Helper1 and Helper2 will be injected by spring IoC public RefactoredComplexClass(Helper1 h1,...

Mockito. Mock single method which throws an exception

java,junit,mockito
I have a class with method impersonate which throws UnsupportedOperationException. So I want to mock only this only method. I know that I can do it with Mockito.spy. Session session = Mockito.spy(new Session("admin", "adminSpace")); Session imperSession = new Session("test", "testSpace"); when(session.impersonate(any(Credentials.class))).thenReturn(imperSession); But the problem is that Mockito really calls impersonate...

Object reference changing during Mockito Test

spring,unit-testing,mockito
I have just started working with Mockito and am having a problem with one of the tests failing, yet the actual code works correctly in a live environment. The controller being tested is: @Controller @RequestMapping("/notes") public class NotesController { private NoteRepository noteRepository; private MyUserRepository userRepository; @RequestMapping(value = "/add", method =...

Mockito - check if ANY method was called on an object(object was accessed)

java,unit-testing,junit,mockito
I want to write a test that passes a mock object A into an object under test B and checks if ANY of the methods of A were called. To give some context, class B is designed to manipulate A in a specific way, based on a set of parameters,...

What am I doing wrong in mocking this method?

java,testng,mockito
Here's a snippet of my test class. class MyClassTest { MyClass my; HandlerA handlerA; HandlerB handlerB @BeforeTest public void setUp() { handlerA = mock(HandlerA.class); handlerB = mock(HandlerB.class); my = new MyClass(handlerA, handlerB); } @Test public void testhandlerABuilderNegativeCase() { Shapes s = getShapes(); Types t = my.buildTypes(); when(handlerA.handle(s, t)).thenReturn(Response.status(500).type(MediaType.APPLICATION_JSON).build());//ineffective. Assert.assertFalse(my.handlerABuilder()); }...

why getName() returns null using mockito?

java,junit,mockito
Person.java is this code. public class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } and this is the test code. import org.mockito.Mock; import junit.framework.*; import org.mockito.MockitoAnnotations; import org.mockito.Spy; public class PersonTest { @Mock private Person person;...

how to mock QueueItems[] using mockito?

mockito
QueueItems[] items = .... how i can mock object for QueueItems[] using mockito? i tried : ArrayList workItems = mock(ArrayList.class); QueueItems = mock(QueueItems.class); but not working....

Mockito stubbing goes away after first invocation of a stubbed method

java,testng,mockito,stubbing
Java 8, TestNg 6.8.1, Mockito 1.10.19. This is my first experience with Mockito. I stub two methods in a class, both of them take a String and a double as parameters and return double. I only care about the second parameter in this case. When the stubbed methods are called...

Make sure method is called once for each object in a List

java,mockito
I have a bunch of objects in a List<MyClass> myObjects, which should be used as parameters of a method call on a mocked object. I'd like to verify that the corresponding method is called exactly once for each instance in myObjects like Iterator<MyClass> it = myObjects.iterator(); while(it.hasNext()) { MyClass myCurrentObj...

Is it possible to configure Mockito mock to call multiple answers on a single invocation?

java,junit,mockito
I have a test which tests a bunch of classes and I have to stub a void method. The stubbed behavior should always invoke one callback and in some cases the second one in addition depending on the invocation arguments. Here is my test code, method names represent what I...

Mockito says arguments are not identical but they are?

java,hibernate,unit-testing,session,mockito
This is the method that I want to test: public class SelectionVariantUniqueConstraintValidatorImpl implements UniqueConstraintValidator { private SessionFactory sessionFactory; @Override public List<Criteria> buildValidationCriteria(Object entity, Serializable id, String[] propertyNames) { final SelectionVariant selectionVariant = (SelectionVariant) entity; final Session session = sessionFactory.getCurrentSession(); final Criteria criteria = session.createCriteria(SelectionVariant.class); criteria.add(Restrictions.eq("client",...

How to partial mock a method that throws exceptions using Mockito?

java,unit-testing,mockito,partial-mocks
It's useful to test exception handling. In this specific case, I have a extractor that will do a specific task when an exception is thrown while unmarshaling a specific class. Example Code Below is a simplified example of the code. The production version is much more complicated. public class Example...

How I can write mockito junit for Listener class

java,spring,junit,mocking,mockito
Hi how to write mockitJunit for public void contextInitialized(ServletContextEvent event) in below class. public class AppStartUpContextListener extends ContextLoaderListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent event) { } @Override public void contextInitialized(ServletContextEvent event) { final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); final Configuration appConfig = (Configuration)...

Mockito - How to spy on Invocation argument in doAnswer

java,unit-testing,junit,mockito
This is my first day writing Unit tests using Mockito and I might have started with a complex exercise. Below is my class structure and I am writing tests for Class2.targetMethod(). Class1 static method modifies passed in object instead of returning any results. class Class1 { static void dbquery(OutParam out)...

Mockito - Mock not being injected for one of the testcases

java,unit-testing,mockito
I have a jsf spring application and using mockito for my unit test.I keep getting null pointer exception when i run my unit test iEmployeeService. There is no null pointer for iSecurityLoginService. Method to be mocked @Autowired IEmployeeService iEmployeeService; @Autowired ISecurityLoginService iSecurityLoginService; public void addEvent() { entityEventsCreate.setTitle(entityEventsCreate.getTitle()); entityEventsCreate.setModifiedBy(iSecurityLoginService .findLoggedInUserId()); int...

How do I completely mock out a class with PowerMockito?

java,unit-testing,mockito,powermock,powermockito
I'm reading this documentation on PowerMockito and it has two main examples: Mocking static methods Partially mocking a class but I want to know how to mock an entire class that's created with new. I am looking for the PowerMockito version of Mockito's mock method. This should be able to...

Is it possible to mock a system service in Android

android,mockito
all. I'm new to use Mockito:) Context mockContext = mock(Context.class); TelephonyManager mockTelephonyManager = mock(TelephonyManager.class); when(mockTelephonyManager.getNetworkCountryIso()).thenReturn("CN"); when(mockContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mockTelephonyManager); the above won't work when espresso test trying to use the telephony, it still return the system network country ISO. any thoughts? thanks!...

Is it bad practice to make a method package or private for the sake of testing?

java,android,unit-testing,junit,mockito
In Java (in an Android specific context, but this should apply across the board), is it considered bad practice to remove a private modifier - and thus be package specific - for the sake of unit testing? Say I have something like the following: public void init(long id) { mId...

Issues in writing test case for a private method

junit,mockito,powermock,easymock,powermockito
I am trying to write a test case for params method in the below class. Problems while writing a JUnit test case: The problem is that the method is private and inside the method it calls for super class methods. I tried using EasyMock where I will be able to...

Mockito gives error in put request

java,spring,mockito
I am trying to make Mock Test of REST service that update data to database of given Id. I have tried Add(POST request) that works fine. But when I am trying PUT request it gives me an error : Argument(s) are different! Wanted: service.updateMet( Met [id=10, name=mnTest, definition=mdTest] ); ->...

Mockito: How to test if another class' method is called within a method of a Mock?

junit,mocking,mockito,jboss-arquillian,verify
So I have a service class. public class OrganisationService { public List<Organisation> findAllForeignOrganisations() { // a few rows of JPQL-code that searches the database return myCriteria.getResultList(); } //...Other methods that return Lists with other types of organisations... } Then I have a class which I want to test. What I...

Mocked repository does not trigger as expected

spring,unit-testing,mocking,mockito,mockmvc
I have a Controller Unit test using Mockito and MockMvc. After a POST request, the POSTed object is resolved correctly, but my repository mock is not triggered. Here is the mock code: Date mydate = new Date(); Notification not = new Notification(); not.setId(-1L); not.setUserid("BaBlubb"); not.setTimestamp(mydate); not.setContent("MyContent"); Notification not2 = new...

java.lang.LinkageError: loader constraint violation When trying to use Mockito Argument Matcher

java,mockito,java.lang.linkageerror
I am trying to test a class and I have my own argument Mathcher to match the arguments. Here is the code: @Test public void testDoBindModelsToForm() { OrganizationToRelatedSubregionsConverter organizationToRelatedSubregionsConverter = mock(OrganizationToRelatedSubregionsConverter.class); List<Organization> subregion1 = new ArrayList<Organization>(); Organization subregionOrg1 = CommonentityFactory.eINSTANCE.createOrganization(); subregionOrg1.setMID(OrganizationMID.create(DOMAIN, 100L));...

Using both junit assertions and mockito verification

java,junit,mockito
I'm using Junit in conjunction with Mockito. I used mockito's verify method + junit assertion to do complete verification. Is this not desirable? Should we use one or the other but not both?

Mock throwing a null pointer exception. New to mockito

java,unit-testing,mockito,powermock
I'm trying to test the following method MainClass { .... Client client; WebTarget target; boolean doLogin(MultivaluedMap<String, String> headers) { client = getRestClient(); target = client.target(BASE_URL)) .path("v1/login"); MultivaluedMap<String, Object> castedHeaders = castMap(headers);//casts headers by entry. Response loginRsp = target .request().headers(castedHeaders) .post(Entity.entity(buildIusLoginEntity(), MediaType.APPLICATION_JSON_TYPE)); if (loginRsp.getStatus() != HttpServletResponse.SC_OK) { return false; } return...

Mockito RETURNS_SMART_NULLS answer weird behavior

java,mockito,method-invocation
I'm using the annotation @Mock(answer=Answers.RETURNS_SMART_NULL) with Mockito 1.9.5 in order to get some SmartNullPointerException when some unexpected mock calls occurs. Unfortunately, the test pass, even without mocking at least one important call. To be clear : My point is not to find by myself what I'm missing but to fail...

Mockito's spy does not work along with AspectJ using maven

unit-testing,maven,mockito,aspectj
I have the following test class and I'm using Mockito's spy. By running my unit test using Eclipse (right click->Run as unit test) all tests pass which means that eclipse build process using m2e and AJDT works fine. @RunWith(MockitoJUnitRunner.class) public class SampleTest { @Mock private AnotherClazz mockedClazz; @Spy @InjectMocks private...

java mocking custom objects

java,unit-testing,mockito
public class MainClass { public void makeCall() { CustomObject obj = new CustomObject(); obj.testMethod(); } } I want to unit test the makeCall(). So i have to mock the CustomObject in the above sample. I am using Mockito as the mock framework.But when i mock the object like mock(CustomObject.class). makeCall()...

Mocking Scala void function using Mockito

scala,mockito,spec2
I found a few answers for this but nothing is working for me. Trying to mock Apache Shiro Subject interface login method which returns void. Interface: void login(AuthenticationToken token) throws AuthenticationException; I have tried : #1 val subject = mock[Subject] doNothing().when(subject).login(new UsernamePasswordToken()) #2 val subject = mock[Subject] doNothing().when(subject).login(any[UsernamePasswordToken]) #3 when(subject.login(any[UsernamePasswordToken])).thenAnswer(new...

PowerMock complains of incorrect arguments even though the private method is mocked

java,unit-testing,mockito,powermock,easymock
I was trying out PowerMock, and am trying to mock a private method like so: expectPrivate(n, "doLogin", anyString(), anyString()).andReturn(true); That is, I want true to be returned from doLogin irrespective of the parameters passed. The public method which delegates to this private method simply passes-on the arguments. Here is the...

Mockito rule not being applied

java,unit-testing,junit,mocking,mockito
I was writing a testcase using Mockito and it seems to me one Mockito rules does not get defined. Below is my scenario. public class DummyTest { private final String[] alphabet= {"a", "b", "c", "d", "e" }; private final String[] numeric= {"1", "2", "3", "4", "5" }; AtomicInteger idx; String...

Create a JsonProcessingException

java,junit,jackson,mockito
I'm trying to create a JsonProcessingException to be thrown by a mock object. when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error")); However I'm unable to create a JsonProcessingException object as all the constructors are protected. How do I get around this?...

Mockito: How to match a String and List arguments

java,unit-testing,mockito
I'm basically trying to verify whether the correct parameters are being invoked in a method. Here's a snippet of the code I'm trying to test: Criteria criteria = session.createCriteria(User.class); criteria.add(Restrictions.in("type", Arrays.asList("employee", "supervisor"); Verifying this using: Mockito.verify(mockSession).createCriteria(User.class); Mockito.verify(mockCriteria).add(Restrictions.in("type", Arrays.asList("employee", "supervisor")); The first verify statement works. The second doesn't because, I believe,...

stub a method in mock bean in spring integration context

java,spring,mockito,spring-integration
I am trying to test a spring integration set up my unit test is as follows, @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { SIContext2Config.class }) public class FileMoverTest extends GenericTest { @Test public void testFileMover() throws InterruptedException { Thread.sleep(1000); int total = 2; int n = 0; for (int i =...

How to verify that static method was invoked with exact arguments?

java,unit-testing,mockito,powermock
I have following method to test: public static Map<String, CrxEntity> getCrxEntitiesByMixin(Session readSession, String rootPath, SupportedLocale locale, String mixin, String idPropertyName, Set<String> propertyNamesToStore) throws RepositoryException { return getCrxEntitiesByMixin(readSession, rootPath, locale, mixin, idPropertyName, propertyNamesToStore, null, false); } Following method invoke another public method thus I should to test only that arguments passed...

Mockito @InjectMocks doesn't work for fields with same type

java,unit-testing,mockito,inject
I was very surprised to find out that following simple code example doesn't work for all Mockito versions > 1.8.5 @RunWith(MockitoJUnitRunner.class) public class MockitoTest { @Mock(name = "b2") private B b2; @InjectMocks private A a; @Test public void testInjection() throws Exception { assertNotNull(a.b2); //fails assertNull(a.b1); //also fails, because unexpectedly b2...

Autowired MessageSource null in @ControllerAdvice unit testing controller

spring,unit-testing,mocking,spring-boot,mockito
I have added the setHandlerExceptionResovlers to my builder and that works well except the exceptionhandler bean has autowired MessageSource and when unit testing this is null. I assume it might be cause of having to manually setup the exception handler in test. The flow is calling the controller with invalid...

PowerMockito UnfinishedStubbingException

java,mockito,powermock
Hello I have this PowerMockito test which throws anì UnfinishedStubbingException @RunWith(PowerMockRunner.class) @PrepareForTest(SuperHero.class) public class SMSActionPresaInCaricoTest { @Test public void testExecute() { PowerMockito.mockStatic(SuperHero.class); when(SuperHero.findSuperHero(anyString())).thenReturn(new SuperHero ()); Action action = new Action(); action.execute("", ""); } The class SuperHero has a static method findSuperHero that returns an instance of SuperHero reading the data...

Mocking getPk() function when there is no setPk()

unit-testing,junit,mockito,hybris,powermockito
I have the following piece of code (a small part of a Facade) to cover in unit tests. I am using Mockito to mock functions belonging to a service layer. Iterator<AbstractOrderEntryModel> entryModelItr = orderEntryModelList.iterator(); while (entryModelItr.hasNext()) { AbstractOrderEntryModel entryModel = entryModelItr.next(); if (CollectionUtils.isNotEmpty(deletedPKList) && deletedPKList.contains(entryModel.getPk().toString())) { entryModelItr.remove(); modelService.remove(entryModel); } }...

mocking UrlEncoder in a static method

java,junit,mockito,powermock
I'm having trouble mocking UrlEncode.encode method which is inside a static method. MyEncodeClass.java has this method public static myEncode(String s) { UrlEncoder.encode(s, "utf-8"); } I want to force throw an exception when UrlEncode.encode method is called. @Test(expect = UnsupportedEncodingException.class) public void myTest() { PowerMockito.mockStatic(URLEncoder.class); when(URLEncoder.encode("aa", "utf-8")).thenThrow(UnsupportedEncodingException.class); MyEncodeClass.myEncode("aa"); } but I...

Mockito: get the value of a field in a mocked object

java,unit-testing,mockito
I have a mocked javax.ws.rs.client.WebTarget webTarget. Then I do following: Mockito.when(webTarget.path(Mockito.anyString())).thenReturn(webTarget). Now I'd like to retrieve the String set during the .path(String) method out of the webTarget mock. Is there any chance I can do that? At the time webTarget.getUri() unfortunately returns null....

Login page Junit test with mockito

java,mockito,junit4
I guess this is simple problem, but I am unable to get my head around it. this is the class for which I need to write test case @Controller @SessionAttributes public class LoginController { @RequestMapping(value = "/Login", method = RequestMethod.GET) public ModelAndView displayLogin(@RequestParam(value = "error", required = false) String error,...

How can I check method params when method call using mockito?

java,unit-testing,junit,mockito
I am trying to write unit test which will test fillA method. I need to verify that doSmth calling with correctly initialized a fields. Here is example. SecondClass secondClass = new SecondClass(); public void execute() { A a = new A(); fillA(a); secondClass.doSmth(a); } private void fillA(A a) { a.setFirstField("first...

Is it possible to use Mockito to completely stop a method from running?

java,unit-testing,mockito
I'm unit testing a method that has a lot of logic in it. It goes something like this: public void doSomething(int number){ //... complex logic if (number % 2 == 0) someInstanceObject.setOdd(false); else someInstanceObject.setOdd(true); //... more complex logic and database connections } Is it possible for Mockito to just end...

NPE while testing

java,junit,eclipse-plugin,mockito
I've got a NullPointerException on method testStartEnbaledFeed on line of RssServiceTest service.start(); and then on line of RssService job.addJobChangeListener(new JobChangeAdapter() { The key problem seems to be that the job.addChangelistener method is called for real. Anyone know how to solve it? RssServiceTest and RssService classes listed below: package org.eclipse.recommenders.internal.news.rcp; import...

Is it possible to use Mockito in Kotlin?

java,mocking,mockito,kotlin
The problem I'm facing is that Matchers.anyObject() returns null. When used to mock method that only accepts non-nullable types it causes a "Should not be null" exception to be thrown. `when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -> someResponse } Mocked method: public open fun login(userCredentials: UserCredentials): Response ...

Mockito: Verify a boolean method (or other types)

java,testing,mockito,void,verify
I know that you can only verify void methods. But I actually ask myself why. I recently stumbled upon an unit test where I really need to verify that a certain call has been made. To be exact, it's "newFolder.mkdirs()". The behavior of this method is pretty much "voidy"...

Null pointer exception depending on statement chaining in Mockito?

java,unit-testing,nullpointerexception,mockito,criteria
I have a test method that is supposed to test the following method: public class SelectionVariantUniqueConstraintValidatorImpl implements UniqueConstraintValidator { private SessionFactory sessionFactory; @Override public List<Criteria> buildValidationCriteria(Object entity, Serializable id, String[] propertyNames) { final SelectionVariant selectionVariant = (SelectionVariant) entity; final Session session = sessionFactory.getCurrentSession(); final Criteria criteria = session.createCriteria(SelectionVariant.class);...

Why is javers throwing “argument should not be null” when the compared objects are NOT null, in a mockito test?

java,mockito
I've used javers in a different part of our app. Now I'm adding it to another, and am getting an IllegalArgumentException: argument should not be null. But I have verified (by serializing the objects and logging them) that the 2 objects are NOT null when passed to the compare() method....

Mockito Matchers.any(…) on one argument only

java,testing,mockito,matcher
I want to do this: verify(function, Mockito.times(1)).doSomething(argument1, Matchers.any(Argument2.class)); Where argument1 is a specfic instance of type Argument1 and argument2 is any instance of the type Argument2. But I get an error: org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 2 matchers expected, 1 recorded. This exception may occur if matchers are combined...

Mockito Verify on passed sub type only sees super type

java,mockito,verify
I cannot easily verify 2 individual and unique call of a sub type class to a method which takes a supertype I have a scenario that acts like this... Both B and C extend abstract type A With public class X { public String doSomething(A a){ return ""; } }...

Is there a way to verify if the Catch part of a try/catch instruction is called in a test method when using JUnit?

java,unit-testing,junit,mockito
For example, if I had the following class that I want to test: public class SomeClass{ public void someMethod() { try { //Some code, where comething could go wrong } catch (Exception err) { //Handling it amounts to logging the problem and trying to continue } } } If I...

Using Mockito to test Java Hbase API

unit-testing,junit,hbase,mockito
This is the method that I am testing. This method gets some Bytes from a Hbase Database based on an specific id, in this case called dtmid. The reason I why I want to return some specific values is because I realized that there is no way to know if...

Unit testing a fluent interface with Mockito

java,unit-testing,mocking,mockito,builder-pattern
I want to mock the DAO interface used in the builder pattern as shown below. However when I run the test below it passes indicating that my mock object is never called. What am I doing wrong? public class DBContent { ... public static class Builder { DAO dao =...

how to mock internal method call using mockito/powermockito

java,junit,mockito,powermock
I am testing a method in class which in turn calls another artifacts' method and consume return value in it. public void methodToTest() { Object reply = artifactObj.anotherMethod(object); if(reply == null) return; Object =reply.getData(); } I have used powermockito and know that if "anotherMethod" existed inside the same class I...

Mockito - Does verify method reboot number of times?

java,unit-testing,junit,mockito
If we have this code: @Test public void test1(){ Interface1 i1 = mock(Interface1.class) method1(); // This method calls i1.mockedmethod() verify(i1, times(1)).mockedmethod(); method1(); verify(i1, times(2)).mockedmethod(); } I know that it will pass the first verify, but I'm in doubt with the second one. Does verify method counts all the times that...

Mockito, jacoco and surefire causes out of memory

maven,mockito,jacoco,surefire
I am using mockito 1.8.3, jacoco 0.72 and maven 3.0.5 surefire plugin (2.12.4) to execute unit test and generating coverage report, it was working fine. With more and more tests are added, it starts not working. I continuously encounter out of memory error during test execution, and cannot find out...

NPE when calling MockitoAnnotations.initMocks() in AndroidTestCase

java,android,testing,gradle,mockito
Trying to use mockito in my AndroidTestCase. I added the dependencies to the build.gradle: final DEXMAKER_VERSION = '1.2' dependencies { ... androidTestCompile "com.google.dexmaker:dexmaker:${DEXMAKER_VERSION}" androidTestCompile "com.google.dexmaker:dexmaker-mockito:${DEXMAKER_VERSION}" androidTestCompile 'org.mockito:mockito-core:1.10.19' } The TestCase with the mockito initialization: public class UsersListPresenterTest extends AndroidTestCase { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } public void...

Mocking factory pattern in Java

java,junit,mockito,factory-pattern
It may look similar to my question. I have a simple animal factory. public class AnimalFactory { public Animal getAnimal(String type) { if ("canine".equals(type)) { return new Dog(); } else { return new Cat(); } } } and class for public interface Animal { void makeSound(); } public class Dog...

Mockito always return null when testing dropwizard resources

unit-testing,junit,mockito,dropwizard
I am trying to test dropwizard resources and followed http://www.dropwizard.io/manual/testing.html to do so. However, I always get a null object from the mocked class/method. The resource method @GET @Path("/id") @ApiOperation("Find property by id") @Produces(MediaType.APPLICATION_JSON) public Property findById(@QueryParam("id") int id) { return propertyDAO.findById(id); } And the test class public class PropertiesResourceTest...

Why isnt mockito injecting the right response?

java,unit-testing,mocking,testng,mockito
I'm trying to use mockito in the following manner. Here's a part of main class IClient. public LoginResponse doLogin() { WebTarget target = buildTarget(); MultivaluedMap<String, Object> authHeaders = prepareHeaders(); Builder buildRequest = buildRequest(authHeaders,target); Response loginRsp = buildRequest .post(Entity.entity(" Valid JSON string", MediaType.APPLICATION_JSON_TYPE)); if(loginRsp == null) LOGGER.error("Response was null");// Response is...

jersey/Mockito: NullInsteadOfMockException on client.post call verification

java,jersey,mockito
I've run into a strange issue with unit testing the following jersey client call: WebResource webResource = _client.resource(url); ClientResponse response = webResource .accept("application/json") .type("application/x-www-form-urlencoded") .post(ClientResponse.class, postBody); PostBody is a MultivaluedMap. The unit test verifies fine the accept and type calls but fails on the post one with this exception: org.mockito.exceptions.misusing.NullInsteadOfMockException:...

Junit test cases fail for abstract method

java,spring,junit,mockito
I have an abstract method checkStatus() which has implementations in Checker.java class. But when I execute the Junit test case on abstract class method validate() that in-turn calls checkStatus(), fails due to missing spring dependency in Checker.java class. Details provided below. Abstract class: public abstract class MyAbstractClass { protected abstract...

Setting values through mockito not working

java,unit-testing,mockito
Consider the following class: public class FacadeImplTest { /*Class to test*/ private FacadeImpl facade; @Mock private Test test; @Mock private Test1 test1; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); facade = new FacadeImpl(); test.setID("1234"); } @Test public void testOrder() throws Exception { // Have methods to test } Here...

Intellij Live Template with Mockito

intellij-idea,mockito
So I'm trying to create a live template in Intellij for Mockito. What I have is follows: $VAR$ = Mockito.mock($VARCLASSNAME$);$END$ VAR has the expression of suggesteFirstVariableName() Now what do I need to put in for the expression so that it automatically picks up the class name of the VAR? Thanks,...

Tests repeats the code with Mockito

java,unit-testing,junit,mocking,mockito
My tests just repeats the code. For method public void start(Context context) { context.setA(CONST_A); context.setB(CONST_B); ... } I wrote test using Mockito @Test public void testStart() throws Exception { Context mockContext = mock(Context.class); action.start(mockContext); verify(mockAction).setA(Action.CONST_A); verify(mockAction).setB(Action.CONST_B); ... } Or for public void act() { state.act(); } test @Test public...

Mockito Expect an Exception

exception-handling,mockito,junit4,expect,mockmvc
I'm trying to test the method below with Mockito and Junit: @Transactional @RequestMapping(method=RequestMethod.PUT,value ="/updateEmployer/{empId}") public @ResponseBody Object updateEmployer(@PathVariable Integer empId,) throws Exception { Employee e = EmployeeRepository.findOne(empId); for (Department de : e.getDepartement()){ de.setDepartmentName(e.getName + "_" + de.getName()); } EmployeeRepository..saveAndFlush(e); return null; } This is the method Test: @Test // throw...

Mockito doThrow on void method with null argument not throwing exception: What am I doing wrong?

java,mockito
I am unsure if I have found a bug or if I am just doing it wrong. I am trying to have a mock throw an exception when a method is invoked (relatively easy normally), except the method is of void return type, and the object to be passed in...

Using Mockito WhiteBox for setting a member variable inside a method scope

junit,mockito
I am new to Mockito and is trying to figure out whether there is a way to set the value of a member variable inside a public method using WhiteBox features of Mockito. I tried searching for this but seems no references are talking about this. Is it doable or...

Mockito error with method that returns Optional

java,mockito,optional
I have an interface with the following method public interface IRemoteStore { <T> Optional<T> get(String cacheName, String key, String ... rest); } The instance of the class implementing the interface is called remoteStore. When I mock this with mockito and use the method when: Mockito.when(remoteStore.get("a", "b").thenReturn("lol"); I get the error:...

Can Powermockito be used with Android Studio 1.2

android,android-studio,mockito,android-gradle,powermock
I am using Android Studio 1.2 and the com.android.tools.build:gradle:1.2.2 plugin. Attempt 1 I include the following in my app/build.gradle: androidTestCompile ('com.google.dexmaker:dexmaker-mockito:1.2') androidTestCompile ('org.powermock:powermock-mockito-release-full:1.6.2') but then the PowerMockito package in not available for import: error: cannot find symbol PowerMockito.mockStatic(DatastoreFactory.class); ^ Attempt 2 I include the following in my app/build.gradle: androidTestCompile ('org.powermock:powermock-api-mockito:1.6.2')...

Use Mockito 2.0.7 to mock lambda expressions

java,unit-testing,junit,lambda,mockito
I want to mock a query provided on my repository like this: @Test public void GetByEmailSuccessful() { // setup mocks Mockito.when(this.personRepo.findAll() .stream() .filter(p -> (p.getEmail().equals(Mockito.any(String.class)))) .findFirst() .get()) .thenReturn(this.personOut); Mockito.when(this.communityUserRepo.findOne(this.communityUserId)) .thenReturn(this.communityUserOut); ... My @Before method looks like this: @Before public void initializeMocks() throws Exception { // prepare test data. this.PrepareTestData(); //...

How to mock Spring ConversionService?

java,spring,unit-testing,mockito
The web application I wrote works as expected. Now I want to unit-test the Controller methods. The pattern for these methods is: Convert the http request object (DTO) to domain object Use domain object to call business logic in a service layer Convert the response of the business logic to...

Mocking/Testing HTTP Get Request

java,unit-testing,http,junit,mockito
I'm trying to write unit tests for my program and use mock data. I'm a little confused on how to intercept an HTTP Get request to a URL. My program calls a URL to our API and it is returned a simple XML file. I would like the test to...

`answers` is not invoked when mocking a method with `call-by-name` parameter

mocking,mockito,specs2,callbyname
There is a class InvokeLater, the definition is like: class InvokeLater { def apply(f: => Any): Unit = { // do something ... f // do some other thing } } In specs test, I mocking it like: val invokeLater = mock[InvokeLater] invokeLater.apply(any) answers { f => f:Unit } But...

Mock private static final field using mockito or Jmockit

java,junit,mockito,static-members,jmockit
I am using private static final LOGGER field in my class and I want LOGGER.isInfoEnabled() method to return false. How can I mock the static final field by using mockito or jMockit My class is: import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Class1 { private static final Logger LOGGER = LoggerFactory.getLogger(Class1.class);...

In Java, how can I mock a service loaded using ServiceLoader?

java,mockito,serviceloader
I have a legacy Java application that has code something like this ServiceLoader.load(SomeInterface.class) and I want to provide a mock implementation of SomeInterface for this code to use. I use the mockito mocking framework. Unfortunately I am unable to change the legacy code, and I do not wish to add...

increasing code coverage for JdbcTemplate mocking

spring,unit-testing,mockito,code-coverage,jacoco
I am mocking JdbcTemplate for unit test cases, as don't want to hit actual database integration. But it is decreasing my code coverage (Red indicates missing coverage). Below is the snippet used. Same case happens by using user defined mappers. final List<String> resultList = new ArrayList<String>(); resultList.add("test1"); resultList.add("test2"); final JdbcTemplate...

Spring Bean Injection Failing Due To Proxy

java,spring,hibernate,junit,mockito
Spring Version: 3.2.4.RELEASE and 3.2.9.RELEASE Mockito Version: 1.8.5 I've been trying to introduce H2 tests to an old project for integration testing, and I've been running into a few issues. Due to the way transactions were propagating, I needed to mock out an autowired class. I've done this before, but...

Testing a void method with Mockito

java,mockito
I have a method like this: public void someMethod() { A a = new A(); // Where A is some class. a.setVar1(20); a.someMethod(); } I want to test 2 things: The value of Var1 member variable of a is 20. someMethod() is called exactly once. I have 2 questions: Are...

JdbcTemplate Mockito ClassCastException

spring,mockito,classcastexception
I am trying to mock a method of the Spring framework's JdbcTemplate class. The method has the following signature: public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException {...} The mocking is being done as mentioned below: when(jdbcTemplate.queryForObject(anyString(), eq(String.class))).thenReturn("data"); However, this call throws the following exception java.lang.ClassCastException:...

Mockito.any() for

java,unit-testing,mockito,mongodb-java,springmockito
I want to mock a method with signature as: public <T> T documentToPojo(Document mongoDoc, Class<T> clazz) I mock it as below: Mockito.when(mongoUtil.documentToPojo(Mockito.any(Document.class), Mockito.any(WorkItemDTO.class))) But I get error as: The method documentToPojo(Document, Class) in the type MongoUtil is not applicable for the arguments (Document, WorkItemDTO) Is there any method in Mockito...

Mocking @Log in Groovy

groovy,mockito
Given a class annotated with @Log; is it possible to mock the injected logger with Mockito for unit testing? Is this correct "Groovy-way" of doing things?

Mock same statement twice

java,unit-testing,mockito
I have a Java method with the following statement: public void someMethod() { ..... Long firstVal = someService.getSomeObject().getId(); Long secondVal = someService.getSomeObject().getNextFunc().getOtherObject().getId(); ..... } Now I am trying to test this method and in mock setup I am trying to do like: @RunWith(MockitoJUnitRunner.class) public class SomeServiceTest { @Mock SomeService mockSomeService;...

Testing using Mockito

android,mockito
Apologies for what may seem an idiotic post. How do you run Mockito on the newest version of Android Studio SDK? and can you run multiple tests using Mockito using the Android Studio platform? I've used Mockito on Eclipse and ran as much as 6 tests in the same window....

Unit Testing with jUnit and Mockito for External REST API calls

java,spring,unit-testing,junit,mockito
I building unit tests in a Spring Boot Java application for a service class. The service class makes an external call to a REST API service that return a JSON response. I am mocking this call using Mockito. I am hardcoding a JSON in the mockserver response. Is this bad...

Static Field as Null when mocking Enums with PowerMock

java,junit,mockito,powermock
I have written a Thread Pool and I am not able to write the Junits(PowerMock) for that class. public enum ThreadPool { INSTANCE; private static final String THREAD_POOL_SIZE = "threadpool.objectlevel.size"; private static TPropertyReader PROP_READER = new PropertyReader(); private final ExecutorService executorService; private static final ILogger LOGGER = LoggerFactory .getLogger(ReportExecutorObjectLevelThreadPool.class.getName()); ThreadPool()...

Testing Android App using greendao with Mockito

android,mockito,android-testing,greendao
I am new to android testing and trying to write unit tests (running on local jvm) using mockito in Android Studio. My IDE setup (gradle scripts) is done so far. dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') // Unit testing dependencies. testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:1.10.19' } In my app I...

Vaadin attach class to Page?

java,testing,mockito,vaadin
How can I mock 'Page' and set the class's page to my mock? (Is that even possible?) public class Example extends CssLayout(){ public void notification(){ Notification notif = new Notification("Title", "Message", Notification.Type.HUMANIZED_MESSAGE); notif.setStyleName("Warning"); notif.setPosition(Position.TOP_CENTER); notif.setDelayMsec(10000); notif.show(Page.getCurrent()); } } What I want to do : Example example = new Example(); Page...