Questions tagged [mockito]
Mockito is a mocking framework for Java. It is inspired by EasyMock but aims to simplify mock stubbing, verification and tooling even further.
12,408
questions
1
vote
0
answers
16
views
Mockito - How to test Database Connection using Mock?
How can I implement, or rather "imitate" the database connection so that the program in which I am replacing the
access the database with an doubler module. The doubler should be able to ...
0
votes
1
answer
13
views
Mock Bean for all JUnit Tests in Spring Boot
In Spring Boot, is there a way to mock a single bean for all existing JUnit tests, without changing the existing test classes (e.g., by adding an annotation or adding inheritance)? Like injecting a ...
0
votes
1
answer
16
views
Mockk: no answer found for a mocked JPA call with partial matching?
I'm trying to write a Junit test case for an update API. The API is using saveAll method of JPA to perform updates. The API is working fine, but when trying to mock the saveAll method it is giving me ...
0
votes
2
answers
17
views
Is it possible to mock authentication with predefined arraylist as db?
I'm learning mock and I wonder if I could use a code similar as this:
Mockito.when(service.authenticateUser(test)).thenReturn(any());
to validate the success of authentication.
service....
0
votes
0
answers
21
views
How to test authentication using mocks?
I'm doing an exercise where testing is a task, and I should use mockito to test the methods.
I'm trying to test if the authentication is succesful, but I always get expection, saying
org.mockito....
-1
votes
0
answers
16
views
Attach information to a mocked object in Mockito
The Problem
I want to create a mocked Object, that can return the amount of times the insert-Method was called in my "Database". If I could implement the interface myself, i would "mock&...
0
votes
0
answers
11
views
Test Method with HttpServletResponse argument
I have a method in my SpringBoot app, in GenerateZipServiceImpl class:
@Override
public void generateZipFile(final Parameters parameters, final HttpServletResponse response){
...
.....
0
votes
1
answer
17
views
Unit test using junit and mockito for getObject method in AmazonS3
I have method which uses s3.getObject to get S3Object and writes the contents of the object into a temporary file
@Override
public Optional<String> getObject(String s3BucketName, String ...
0
votes
1
answer
19
views
Why does mockito mocked object in Cucumber stepdef file come as Null?
I am using mockito with cucumber .
I have a code in step def which looks like this :
@Mock
private SystemsConfig systemsConfig;
@And("The login to mySytem is executed ...
0
votes
0
answers
27
views
How to write unit testcases for springboot schedulers which is using fixedDelay
I have scheduled job using spring schedulers. Need help to write UnitTestcsaes for this.
On mocking and calling scheduler method how to handle this waiting time.. Do we really need to wait for such ...
0
votes
1
answer
31
views
How to fix Mockito Invalid use of argument matchers error
I am trying to use Mockito to mock a method, however, I keep getting errors. I have tried to set up Mockito with the spring annotations
@RunWith(MockitoJUnitRunner.class)
class ...
0
votes
1
answer
22
views
how to test @ConfigProperty variable of a class
Kindly let me know how we can test below piece of code in junit.
ConfigProperty is reading the values from application.property file. now i have to write an unit test case how i can writ kindly help ...
1
vote
1
answer
30
views
AssertNotNull AssertionFailedError: expected: not <null>
I'm testing an app, where a method creates and object, and I'm trying to test that the object actually gets created like this:
@Test
public void testCreateWagerGetsCreated(){
...
0
votes
1
answer
18
views
Is it possible to retrieve value from application.properties without autowiring the class under test?
I have a test class that is annotated with @Spy and @InjectMocks and tested using Mockito. The class under test has a value (url) that is retrieved from the application.properties file. I'd like to ...
0
votes
0
answers
28
views
JUnit and Mockito test for FileUtils.copyURLToFile
How can I write the unit test using JUnit and Mockito for a method as simple as the following
public class FileUtil {
public void copyURLToFile(String url, String filepath) {
try {
...
1
vote
2
answers
56
views
How to mock a variable and method in Abstract Class?
In a Java (Spring Boot) app, I use JUnit and Mockito and want to test the following service method:
public Page<EmployeeDTO> findAll(EmployeeRequest request, final Sort sort) {
final ...
1
vote
1
answer
15
views
Mockito Mock object being ignored and actual function being called
The mock object does not seem to work and the actual function is being called.
My Controller Class is as follows:-
@RestController
public class A {
@PostMapping(path = "/api/methods", ...
0
votes
0
answers
27
views
Error Actually, there were zero interactions with this mock, unittest
public class ABCService implements XYZ
{
private final ARepository aRepository;
private final BRepository bRepository;
private final SomeService someService;
public ABCService (...
0
votes
1
answer
17
views
Spy object keeps calling to real method even when stubbed
I am working on unit testing this service method, which requires using other methods in the same class that is being tested. So I have read about spy and applied it to my code. However, even when ...
0
votes
0
answers
10
views
Mockito - how to stub method on a real object?
Consider the following code:
class Foo {
public void bar() {
User user = new User(...);
if (!user.isValid() {
throw new SomeException();
}
...
}
}
In my ...
0
votes
2
answers
84
views
How to mock an intermediate class in the code flow in Java
I have 3 classes, as shown below, and I want to write a Unit test for the validate() method of class A. I do not want to mock class B. I want to mock class C and always return the same String when ...
0
votes
0
answers
43
views
Getting InvalidUseOfMatchingException or NullPointerException when all test run together
Getting following exceptions when run all tests together but works as expected when executed individually
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument ...
3
votes
1
answer
37
views
Spring MVC Controller testing PUT
Trying to test my web tier (spring boot, spring mvc) with junit5 and mockito. All other tests on http methods (get, put, ...) are working fine but the update.
Following the code.
Controller:
@...
0
votes
0
answers
20
views
Mockito+Kotlin+SpringBoot, `when` section doesn't mock, but invoke method meant to be mocked
I'm trying to modify existing test of kotlin+springboot project.
Mockito.`when`(serviceA.getData(anyString())).thenReturn(data)// existing mocking
Mockito.`when`(serviceB.getUserId()).thenReturn(...
1
vote
1
answer
28
views
Mockito verify still fails on using all Matchers
I am recently writing a JUnit test and I acknowledged that Mockito either needs all Raw values or using all Matchers but I find the following case still fails with all Matchers, error message is:
...
0
votes
0
answers
19
views
How to write test cases for Service layer using Junit 4 and mockito
My Repository layer is returning list object, But in my service layer i am filtering out all other and return a single Object.
when i try to create test cases it is giving org.mockito.exceptions....
0
votes
1
answer
31
views
How to write Junit for clone method catch block
My respected java developer friends.
i am trying test and cover the catch block of clone method. I have wasted one week but didn't find any solution to cover catch block. Please help me.
My source ...
0
votes
0
answers
22
views
Java | Mutation Testing | PiTEST | (negated conditional → SURVIVED) | (changed conditional boundary → SURVIVED)
I am getting piTest issues. Few mutations are getting survived.
PiTEST negated conditional → SURVIVED changed conditional boundary → SURVIVED
As per my understanding i am testing boundary conditions ...
0
votes
1
answer
18
views
error when Add a stub for a method using Mockito's 'when' API
Have this abstract class to get data from remote data source
abstract class NumberTriviaRemoteDataSource {
/// Calls the http://numberapi.com/{number} endpoint.
///
/// Throws a [ServerException]...
0
votes
0
answers
17
views
Android Mockito test cases with Retrofit
I am new to test cases and I am trying to write test cases for the below code but I did not get success after trying several method. My main target is to cover code coverage of ...
0
votes
1
answer
30
views
How to verify in a unit test that value that is not passed to service or repository?
I am trying to write a unit test for the following method (I use JUnit and Mockito):
public CommandDTO update(UUID uuid, OrderRequest request) {
final List<MenuItem> menuItemList = ...
-1
votes
0
answers
18
views
How to avoid jwt token or ignore authentication when testing HTTP API request?
mvc.perform(MockMvcRequestBuilders.get("/PensionerDetailByAadhaar?aadhaarNumber=123").header("Authorization","Bearer "+token)).andExpect(status().isOk());
Here I need to ...
0
votes
1
answer
16
views
Android java.lang.AssertionError: Verification failed: call 1 of 1: method was not called
I'm writing tests with mockito, trying to check if a method was called, but I always get this error:
java.lang.AssertionError: Verification failed: call 1 of 1: method was not called
This is the ...
0
votes
0
answers
13
views
How to write test cases for custom ErrorAttributes in spring boot
I have updated the spring boot version to 2.6.4 and related other dependencies and got error in getErrorAttributes() method because of changes in its 2nd arguments type from Boolean to ...
1
vote
0
answers
40
views
New code is not showing in Sonarqube Coverage on new code
I am trying to cover few lines of the code with junit test case. Though the test case is covering the lines which I found after debugging the test case, but in Sonarqube Coverage on new code those ...
0
votes
0
answers
17
views
how to mock rcall method inside abc method
in this rest abc service i am calling r system api call i have mocked fileProcessingHelper and used "when(fileProcessingHelper.rCall(client, request)).thenReturn(response);" then i am ...
0
votes
1
answer
13
views
Run unit test and Integration test in same application Spring Boot
I have spring boot application with REST APIs. There are three layers as @Controller, @Service and @Repositiry. I need to write unit test cases to each layer and integration test with all layers ...
-1
votes
0
answers
31
views
how to write junit test cases for if condition throws exception in java using mockito
if(!manifestFile.contains(TDW_RPM_STATEMENTS)) {
throw new FatalBatchException(ManifestService.class, MANIFEST_INVALID_FILE_NAME_ERROR, MANIFEST_FILE_NAME_VALIDATION_ERROR_CODE);
}
0
votes
0
answers
19
views
Apache Http Client Unit Test Issue | HttpResponseProxy{HTTP/1.1 406 Not Acceptable
While unit testing my code of posting payload to an endpoint I am getting exception like HttpResponseProxy{HTTP/1.1 406 Not Acceptable}
HttpClient httpClient = mock(HttpClient.class);
HttpResponse ...
0
votes
0
answers
26
views
How to test my update method with Mockito
Here is my test Class:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UpdateRestaurantTest {
@MockBean
private RestaurantRepository restaurantRepository;
@Autowired
...
0
votes
3
answers
25
views
mock a bean locally, in the same class
I've a TestClass with two Tests foo() and bar(), foo uses the original bean serviceObject, while bar uses a mockedBean: so always one test fails. is there any way to mock my bean only for bar()
@...
0
votes
0
answers
10
views
Junit test coverage for Kafka Kstream
I am pretty new to Kafka and junit and want to write the test coverage for below method which takes the KStrean object and topic. I am not sure if it can be done with topology?
public void ...
1
vote
2
answers
35
views
How to write Junit test class for code coverage
Can someone help me writing JUnit for the below serviceImpl class
@Component
public class ProcessStatusMasterServiceImpl implements ProcessStatusMasterService {
@Autowired
private ...
-2
votes
0
answers
24
views
Post method with null check is giving nullpointer exception on unit testing [closed]
This is post method which am trying to test. Id will be auto generated by DB thats why there is null check for id.
@PostMapping("/orders")
public ResponseEntity<OrderDTO> createOrder( ...
0
votes
0
answers
9
views
Unit test for Spring KafkaListener with "Acknowledge" interface as an argument
I'm not expert at unit test but trying to write unit test for :
@KafkaListener(id = "group_id", topics = "topic" )
public AvroObject listen(AvroObject test, Acknowledgment ...
0
votes
0
answers
17
views
Whats the difference between dart run vs flutter pub run
I downloaded the Mockito library (https://pub.dev/packages/mockito) and followed the instruction to use "dart run build_runner build" to generate mocks in my project directory and it failed ...
1
vote
4
answers
35
views
Java - How to Mock impl via using Mockito
I have this repository created in my class as such:
private static ModuleRepository repository = new ModuleRepository();
its called via:
repository.isModuleCached(moduleType,taxModuleInfo....
0
votes
0
answers
22
views
Json based unit testing
We have huge Data Objects which are a little too difficult to manage while creating test cases. In order to test the entire flow we have to create this big object and then assert on it. Sometimes ...
0
votes
2
answers
35
views
How to mock Function interface from java 8 and System class
I want to mock below call :
((Function<String, String>) System::getenv).apply(TransformerConstants.TRANSFORMER_POOL_SIZE)
I tried using below code :
PowerMockito.when(((Function<String, ...
0
votes
1
answer
16
views
how to write unit test case for this method using mockito?
public void saveDataToAudit(String key, ConsumerRecord<String, String> data) {
String rowKey = key + "-" + data.key();
Random random = new Random();
...