Questions tagged [mockito]

1

votes
2

answer
2.7k

Views

How to Mock System.getProperty using Mockito

I have added mock-maker-inline text in org.mockito.plugins.MockMaker file and placed it in test/resources/mockito-extensions In my test case I am using: System system = mock(System.class); when(system.getProperty('flag')).thenReturn('true');` But I am getting the following exception: org.mockito.ex...
Raghu
1

votes
2

answer
725

Views

Mockito not throwing exception using thenThrow

I am using Mockito to mock the method of service layer. trying to mock the following line of code boolean status= accountDAO.updateAccount(Account acct); And To mock this I am using Mockito.when(accountDAO.updateAccount(Account acct)).thenThrow(new DataBaseException()); But the problem is when code...
R Ram
1

votes
2

answer
57

Views

how to match Some with any value in mockito

My function under test returns None or Some(ObjectOfSignupEmail). In my test case, I want to match that the returned value is Some(ArgumentMatchers.any[SignupEmail]) but I get error Expected :Some(null) Actual :Some(SignupEmail(Welcome,Test,Click here to verify email)) If I change the code to sig...
Manu Chadha
1

votes
1

answer
142

Views

Writing unit tests for Java 8 streams

I have a list and I'm streaming this list to get some filtered data as: List submittedRequestList = list.stream().filter(Objects::nonNull) .map(config -> taskExecutorService.submit(() -> requestHandler .handle(jobId, config))).collect(Collectors.toList()); When I wrote tests, I tried to return some...
codebot
1

votes
2

answer
42

Views

Mockito: mock method throws exception

I'm trying to mock this method: boolean login() throws SftpModuleException; Mocking code is: Mockito .when(this.sftpService.login()) .thenReturn(true); Since, login() throws an SftpModuleException, compiler tells me that this exception has to be handled. Is there any work around due to this exceptio...
Jordi
-1

votes
0

answer
13

Views

jdbcTemplate Mockito unit testing

I'm trying to perform unit testing and write a test for jdbctemplate.query. I need the code coverage for the below method. Code: ` public List UserInfo(final Long runId){ jdbcTemplate.setFetchSize(10); List userList = jdbcTemplate.query(con -> con.prepareStatement(GET_USER_INFO) , (rs, rowNum) -> {...
joe
1

votes
1

answer
606

Views

PowerMock not finding PrepareForTest annotation

I am writing test cases for Java classes, and I am using the PowerMock framework for the first time. The dependencies I added to my pom.xml are shown below, along with the full error message. When I tried using the @PrepareForTest annotation in my test class, it did not import anhything. I checked i...
spa
1

votes
1

answer
799

Views

How to test Spring Rest Controller with Mockito.when if controller has HttpServletRequest injected in method

My Controller looks like this @GetMapping('/networks/{networkId}') public Resource getNetwork( @PathVariable('networkId') UUID id, HttpServletRequest request) { Resource network = networkClient.getNetwork(id); network.removeLinks(); network.add(LinkHelper.getNetworkObjectLinkArray(request, id)); ret...
lombardoja
1

votes
1

answer
1.8k

Views

Spring Boot testing java.lang.IllegalStateException: Failed to load ApplicationContext and missing bean

I seem to have got myself into a loop of trying to fix this. I thought a bean was missing so I'd @MockBean the name of the class it said it was missing, run it again and it would say another class is missing. The classes it's erroring over aren't even the ones I'm testing. Why is this happening? I k...
Aaria
1

votes
3

answer
383

Views

How to mock the same method multiple times use mockito

I have a method that needs to be called multiple times, and I can return the same result in the test case, I invoke when use for loop, but is there more simple way to do this? val ONE_DAY_FORMAT: SimpleDateFormat = SimpleDateFormat('yyyy-MM-dd') val tempCalendar = Calendar.getInstance() for (i in (0...
littlegnal
1

votes
2

answer
1.5k

Views

Mock an object inside a method in JUnit

I'm trying to get to grips with JUnit & Mockito etc. I currently have a method with the below line. ObjectMetadata metadata = getMetadata(path.toString()); Is there any way I can mock it? I've tried things like the below Whitebox.setInternalState(, 'metadata', 'abc'); but I just get org.powermock.r...
pac
1

votes
1

answer
237

Views

Mockito + PowerMock + TestNG + Libgdx

I'm trying add the powermock library to the working project, but I'm getting errors. How I add it: 1) AbsTest extends PowerMockTestCase 2) Build.gradle dependencies 3) In some test add @PrepareForTest({SomeClass.class}). After this step this error occured. In build.gradle all libraries are included....
CoolONE
1

votes
1

answer
144

Views

How to prevent SpringBootTest stop server before async methods finished?

I have code like this @RequestMapping(value = '/create', method = RequestMethod.POST) public Result createModel(DataModel model) { CompletableFuture.runAsync(() -> doSomeThing(model)); return new Result('your request has been recieved successfully'); } and i try to write integration test like...
uuur
1

votes
1

answer
124

Views

Android - MockitoJUnitRunner - Cursor getCount always returns 0

I'm trying to use a cursor in my unit test with Mockito but getCount() method always return 0 even if I add a row. Someone can help me? final Cursor cursor = new MatrixCursor(new String[]{'ID', 'name', 'data'}); ((MatrixCursor) cursor).addRow(new Object[]{1, 'myName', 'myData'});
B3n
1

votes
1

answer
74

Views

Tests never get executed because of the Mockito.doThrow

I am testing an anroid app using Mockito. I want to test an exception case, but the method Mockito.doThrow hangs and the test never gets executed (it neither fails nor succeeds). Here's the code. PackageDownloader represents an AsyncTask. Its method get gets called inside of the downloadPackage meth...
annaoomph
1

votes
1

answer
105

Views

Groovy: Mockito UnfinishedStubbingException using verify (and inline mocks)

I'm trying to verify the calling of a method on a FileChooser. I'm coding in Groovy, and this appears to be the problem. I'm using the 'incubating' Mockito feature which enables you to mock even a final class. Code is: FileChooser mockFC = mock(FileChooser.class) doReturn(mockFC).when(spyCH).getFile...
mike rodent
1

votes
0

answer
183

Views

Not able to mock AccountManager class in Kotlin which is using RxJava

This is my code in kotlin and RxJava, I am trying to test method by mocking accountManager class from Android but not able to mock it :( . Creating variable like this: private val accountManager:AccountManager= mock() private val ACCOUNT_1 = Account('XXXXX', BuildConfig.APPLICATION_ID) Injecting us...
Sanjay Mallur
1

votes
0

answer
311

Views

How to solve assertion error status 404 in web mvc test

I have a controller like this ,This seems to be a problem with Spring boot No one has been able to solve this issue , The same issue was raised by another user , check link Error when using @WebMvcTest annotation on a Spring Boot test class @Controller @RequestMapping('/book') public class BookContr...
valik
1

votes
2

answer
36

Views

Mockito verify only passes with AVD running

I want to test a MVP-Pattern. So i have a Presenter class, which shall invoke the View methods when certain buttons are clicked. Now I want to verify, that the Presenter really invokes the Method, so I wrote these tests: Test Class: import org.junit.Before; import org.junit.Test; import org.junit.ru...
Evoxx
1

votes
0

answer
121

Views

Unit Testing - Inner class receives null when accessing outer class fields

I'm writing unit tests for a class with an inner class. When I try to access variables belonging to the outer class from inside the inner class, they resolve to be null. However, this is only when running the unit tests. class Outer { private final SomeClass foo; Outer(SomeClass foo) { this.foo = fo...
Alex Meuer
1

votes
2

answer
1.1k

Views

Matching varargs in Mockito for unit testing in an overloaded method

I am not able to mock varargs on an overloaded constructor in Mockito. This is the method I want to test @Override public List fetchDataFromExternalService() { return Arrays.asList(this.restTemplate.getForObject(URL, User[].class)); } User is a POJO class that has attributes, getters and setters. Re...
Kartik
1

votes
3

answer
1.9k

Views

Mock a private method [duplicate]

This question already has an answer here: How to mock private method for testing using PowerMock? 4 answers I have a method which is private . Now, I do not want to call this private method while doing unit test on execute() method. I have tried with PowerMockito and all, but with all type of mocki...
user3336194
1

votes
2

answer
286

Views

Is there any option to use something similar to mockito argument captor?

we are using gopkg.in/mgo.v2/bson to talk with mongo, and its API populates passed structures instead returning results, for example: func (p *Pipe) One(result interface{}) error {... Problems occurs when I want to mock / test code which is using that. I want to both mock this execution and somehow...
freakman
1

votes
1

answer
552

Views

Error “Method isEmpty in android.text.TextUtils not mocked” when using PowerMockito.spy

I use Mockito and PowerMock for local Unit tests in my Android app: testImplementation 'org.mockito:mockito-core:2.8.9' String powerMockVersion = '1.7.3' testImplementation 'org.powermock:powermock-module-junit4:${powerMockVersion}' testImplementation 'org.powermock:powermock-api-mockito2:${powerMoc...
Maksim Dmitriev
1

votes
0

answer
214

Views

Gradle with Mockito and MockMaker plugin

Trying to handle a problem with mocking Kotlin final classes. I used org.mockito:mockito-inline libs that uses org.mockito.plugins.MockMaker. All works fine when start tests from Android Studio, but when I use 'gradlew test' command I get error 'java.lang.IllegalStateException: Could not initialize...
Dmitry Bykov
1

votes
0

answer
161

Views

How to mock a RedisAtomicInteger

I've been trying to create a UnitTest for a method that will track the amount of calls made to an specific server. This is the actual method: public int setCounterOnRedis(int count) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern('yyyy-MM-dd'); String currentDate = dtf.format(LocalDate.now());...
Walter G.
1

votes
1

answer
14

Views

Injecting mock initiated by InjectingMock

@InjectMocks private Foo foo; @Mock private Var var; @InjectMocks private MyClass myClass Foo has Var. MyClass has Foo. I am injectiong Var in Foo by @InjectMocks and like to inject Foo to MyClass but Foo in MyClass is null. I guess it's because Foo is not annotated by @Mock. Is there any way I can...
1

votes
1

answer
315

Views

Inject mocks into class before constructor's logic comes on

Imagine, we have a class, in which a lot of logic is being executed inside a constructor. A question: how to inject mocks in such class before constructor's logic gets executed? Additional info: This class is not written by me and I do not want to violate the existing interface in this class by cha...
Andrey Ilyunin
1

votes
0

answer
277

Views

Testing loading and error state with kotlin coroutine

Is there a way for me to mock a suspend function so that it never emit data or it will emit error. With RxJava 2, I can mock the function to return either Observable.error or Observable.never but I couldn't find an equivalent feature in kotlin coroutine. Here's the function that need to be mocked. o...
Vincent_Paing
1

votes
1

answer
592

Views

Proper way to test POST method in Spring MVC Controller

I've got simple app based on SpringMVC and Hibernate, trying to test a POST method which saves a Customer Customer.class to the database. Don't want to test database yet, only simple unit testing. Got the test green, but feel is still not enough, how can I refactor it to make it as it supposed to be...
pinq
1

votes
1

answer
470

Views

ContextCompat with Mockito NullPointerException

I am using mockito to unit test my viewmodel, however im getting a NullPointerException with ContextCompat. @RunWith(MockitoJUnitRunner.class) public class ViewModelUnitTest { @Mock private MockContext mockContext; private ViewModel pViewModel; @Before public void setup() { MockitoAnnotations...
user3133966
1

votes
1

answer
178

Views

Why am I getting InvalidUseOfMatchers build error here?

This code compiles and debugs well, but when I do a maven build in Eclipse the unit test and the build fails. I don't understand where is the misuse of the matchers here? Thanks. [ERROR] Errors: [ERROR] Tests.MyTest() » InvalidUseOfMatchers @RunWith(SpringRunner.class) @ContextConfiguration(clas...
Yoan
1

votes
0

answer
146

Views

InjectMocks to deeper levels

Any suggestions for a better title are welcome. I have some beans as follows: public class ClassA { @Autowired ClassB b; ... } and public class ClassB { @Autowired ClassC c; ... } I want to write a test and mock the ClassC instance inside ClassB. How do we do that? One cumbersome example that wo...
Orkun Ozen
1

votes
1

answer
113

Views

Base Presenter Test class using Mockito and Kotlin - working around Generic type erasure

I'm trying to write a base test class with generics to reduce boilerplate code. It's specifically for testing (MVP) Presenters and I'm using Mockito to mock the View interface. E.g. something like this (simplified): abstract class BasePresenterTest { @Mock lateinit var mockView: V lateinit var prese...
user1405990
1

votes
1

answer
1.2k

Views

Android Testing custom views with mockito

I have a Customview class and I want to write a simple test for it. At first I want to check if the LayoutParams are set. CustomView Class public class CustomView extends FrameLayout { public CustomView(@NonNull Context context) { super(context); initFrameLayout(); } public void initFrameLayout() {...
dudi
1

votes
0

answer
134

Views

how to mock encryption code

I am using testng as my testing framework, mockito for mocks. What I have is: I am trying to write tests for one class that will be tested, the packet processor. The packet processor has two methods called send and receive, where the receive method receives one packet of a specific network protocol...
Michał Zegan
1

votes
1

answer
84

Views

How to mock a single injection in a chain of injections - Arquillian

How can a mock of a class that is in an injection chain? For example, ServiceA injects ServiceB that injects ServiceC (ServiceA -> ServiceB -> ServiceC). In the Arquillian test I need to test ServiceA and mock ServiceC, which is called in my injection chain. What I want is (ServiceA -> ServiceB -> M...
Fernando Prates
1

votes
1

answer
2.3k

Views

How to use ArgumentCaptor in mockito

I'm learning Mockito and Unit Testing in general. I want to learn how to unit test better by using Argument Captor. I'm using jdbc to handle my SQL statement. I have a method that inserts a user into my DB. public void insert(User user) { String sql = 'INSERT INTO user (id) VALUES ?'; jdbcTemplate.u...
Dixon Ivey
1

votes
1

answer
69

Views

Hamcrest matcher for collection argument without cast

I have a type: class SomeType {} And I have a method to mock with Mockito and Hamcrest: class SomeService { public List doSomething(List producer) { ... } } I need to mock the doSomething() method if a java.util.List is passed and that list contains at least one specified element. Now I use casting...
androberz
1

votes
2

answer
333

Views

Mockito answer is getting invoked only once

I am trying to mock spring's applicationContext.getBean(String, Class) method in below manner - when(applicationContext.getBean(Mockito.anyString(), Mockito.eq(SomeClass.class))).thenAnswer( new Answer() { @Override public SomeClass answer(InvocationOnMock invocation) throws Throwable { // doing so...
Kshitij

View additional questions