kandi background
Explore Kits

mockito | popular Mocking framework for unit tests written | Unit Testing library

 by   mockito Java Version: v4.5.0 License: MIT

 by   mockito Java Version: v4.5.0 License: MIT

Download this library from

kandi X-RAY | mockito Summary

mockito is a Java library typically used in Testing, Unit Testing applications. mockito has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
Available as part of the Tidelift Subscription. The maintainers of org.mockito:mockito-core and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • mockito has a highly active ecosystem.
  • It has 12806 star(s) with 2261 fork(s). There are 428 watchers for this library.
  • There were 2 major release(s) in the last 6 months.
  • There are 302 open issues and 1026 have been closed. On average issues are closed in 51 days. There are 7 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of mockito is v4.5.0
mockito Support
Best in #Unit Testing
Average in #Unit Testing
mockito Support
Best in #Unit Testing
Average in #Unit Testing

quality kandi Quality

  • mockito has 0 bugs and 0 code smells.
mockito Quality
Best in #Unit Testing
Average in #Unit Testing
mockito Quality
Best in #Unit Testing
Average in #Unit Testing

securitySecurity

  • mockito has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • mockito code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
mockito Security
Best in #Unit Testing
Average in #Unit Testing
mockito Security
Best in #Unit Testing
Average in #Unit Testing

license License

  • mockito is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
mockito License
Best in #Unit Testing
Average in #Unit Testing
mockito License
Best in #Unit Testing
Average in #Unit Testing

buildReuse

  • mockito releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • It has 65330 lines of code, 6163 functions and 1031 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
mockito Reuse
Best in #Unit Testing
Average in #Unit Testing
mockito Reuse
Best in #Unit Testing
Average in #Unit Testing
Top functions reviewed by kandi - BETA

kandi has reviewed mockito and discovered the below as its top functions. This is intended to give you an instant insight into mockito implemented functionality, and help decide if they suit your requirements.

  • Matches a method invocation .
  • Returns the return value for the given type .
  • Trigger retransformation .
  • Prints a value as a string .
  • make sure arguments are valid
  • Filter the stack trace .
  • Registers type variables on the given class .
  • Creates the mock object .
  • Proxies a new instance of a given field .
  • Process annotation .

mockito Key Features

Still on Mockito 1.x? See what's new in Mockito 2! Mockito 3 does not introduce any breaking API changes, but now requires Java 8 over Java 6 for Mockito 2. Mockito 4 removes deprecated API.

How to develop Mockito?

copy iconCopydownload iconDownload
 ./gradlew build

How to release new version?

copy iconCopydownload iconDownload
git tag -a -m "Release 3.4.5" v3.4.5
git push origin v3.4.5

Skipping a method execution using Mockito

copy iconCopydownload iconDownload
   @Test
    public void test_method(){
        ActualClass spyActualClass = Mockito.spy(actualClassMock);

        doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
        spyActualClass.method();
    }
actualClassMock.method();
spyActualClass.method();
-----------------------
   @Test
    public void test_method(){
        ActualClass spyActualClass = Mockito.spy(actualClassMock);

        doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
        spyActualClass.method();
    }
actualClassMock.method();
spyActualClass.method();
-----------------------
   @Test
    public void test_method(){
        ActualClass spyActualClass = Mockito.spy(actualClassMock);

        doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
        spyActualClass.method();
    }
actualClassMock.method();
spyActualClass.method();

Mockito can not mock Random in Java 17

copy iconCopydownload iconDownload
   interface RandomSource {
        /**
         * Return a random number that matches the criteria you need
         */
        int nextNumber();
    }

    @Bean
    class DefaultRandomSource implements RandomSource {
        private final Random r = new Random();
        public int nextNumber() {
            return r.nextInt(2);
        }
    }
    
    @Bean
    class ClassToTest {
        private final RandomSource randomSource;

        @Autowired
        public ClassToTest(RandomSource randomSource) {
            this.randomSource = randomSource;
        }

        public String doSomething() {
            return randomSource.nextNumber() == 0 ? "Foo" : "Bar";
        }
    }
    
    @Test
    void testDoSomething() {
        RandomSource r = mock(RandomSource.class);
        when(r.nextNumber()).thenReturn(0);
        ClassToTest classToTest = new ClassToTest(r);
        assertEquals("Foo", classToTest.doSomething());
    }
-----------------------
mock(SecureRandom.class, withSettings().withoutAnnotations())

Java generics from Kotlin when verifying using Mockito?

copy iconCopydownload iconDownload
verify(exactly = 0) { yourClass.doThings(any()) };
-----------------------
@Suppress("TYPE_MISMATCH_WARNING", "UPPER_BOUND_VIOLATED_WARNING")
verify(myInterfaceInstance, never()).doThings<Any, MyObject<*, *>?>(any<MyObject<*, *>>())

How to write Junit test for methods with local variables

copy iconCopydownload iconDownload
private static final ExecutorService l = Executors.newFixedThreadPool(1);

private static String getUserInputWithTimeout(int timeout, Callable<String> k) {
    LocalDateTime start = LocalDateTime.now();
    Future<String> g = l.submit(k);
    while (ChronoUnit.SECONDS.between(start, LocalDateTime.now()) < timeout) {
        if (g.isDone()) {
            try {
                String choice = g.get();
                return choice;
            } catch (InterruptedException | ExecutionException | IllegalArgumentException e) {
                logger.error("ERROR", e);
                g = l.submit(k);
            }
        }
    }
    logger.info("Timeout...");
    g.cancel(true);
    return null;
}
@Test
public void testgetUserInputWithUserInput() throws Exception {
    
    String ENTER = " ";
    System.setIn(new ByteArrayInputStream(ENTER.getBytes()));

    Callable<String> callable = () -> new Scanner(System.in).nextLine();

    assertEquals(ENTER, getUserInputWithTimeout(5, callable));
}
-----------------------
private static final ExecutorService l = Executors.newFixedThreadPool(1);

private static String getUserInputWithTimeout(int timeout, Callable<String> k) {
    LocalDateTime start = LocalDateTime.now();
    Future<String> g = l.submit(k);
    while (ChronoUnit.SECONDS.between(start, LocalDateTime.now()) < timeout) {
        if (g.isDone()) {
            try {
                String choice = g.get();
                return choice;
            } catch (InterruptedException | ExecutionException | IllegalArgumentException e) {
                logger.error("ERROR", e);
                g = l.submit(k);
            }
        }
    }
    logger.info("Timeout...");
    g.cancel(true);
    return null;
}
@Test
public void testgetUserInputWithUserInput() throws Exception {
    
    String ENTER = " ";
    System.setIn(new ByteArrayInputStream(ENTER.getBytes()));

    Callable<String> callable = () -> new Scanner(System.in).nextLine();

    assertEquals(ENTER, getUserInputWithTimeout(5, callable));
}

How to mock JWT token to use it with Mockito and Spring Boot

copy iconCopydownload iconDownload
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
}
 if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    } else {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
  if (username != null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtUtil.validateToken(jwt, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

        // chain.doFilter(request, response);

    }

    chain.doFilter(request, response);

}
-----------------------
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
}
 if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    } else {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
  if (username != null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtUtil.validateToken(jwt, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

        // chain.doFilter(request, response);

    }

    chain.doFilter(request, response);

}
-----------------------
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
}
 if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    } else {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
  if (username != null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtUtil.validateToken(jwt, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

        // chain.doFilter(request, response);

    }

    chain.doFilter(request, response);

}
-----------------------
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
}
 if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    } else {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
  if (username != null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtUtil.validateToken(jwt, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

        // chain.doFilter(request, response);

    }

    chain.doFilter(request, response);

}
-----------------------
@MockBean
private JwtUtil jwtUtil;
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    }
@WebMvcTest(value = CategoryCommandController.class, includeFilters = {
        // to include JwtUtil in spring context
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtUtil.class)})
class CategoryCommandControllerTest {

    Logger logger = LoggerFactory.getLogger(CategoryCommandController.class);

    @MockBean
    private CategoryCommandService categoryCommandService;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MyUserDetailsService myUserDetailsService;

    @MockBean
    private CategoryRepository categoryRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtRequestFilter filter;

    //    @WithMockUser
    @Test
    void testCreateCategory() throws Exception {

        CategoryCreateDto categoryCreateDto = new CategoryCreateDto("category");
        CategoryCreateDto categoryCreateResponseDto = new CategoryCreateDto(UUID.fromString("2da4002a-31c5-4cc7-9b92-cbf0db998c41"), "category");

        String jsonCreate = asJsonString(categoryCreateDto);
        String jsonResponse = asJsonString(categoryCreateResponseDto);
        UserDetails dummy = new User("foo@email.com", "foo", new ArrayList<>());
        String jwtToken = jwtUtil.generateToken(dummy);
        RequestBuilder request = MockMvcRequestBuilders
                .post("/api/adverts/category")
                .content(jsonCreate)
                .header("Authorization", "Bearer " + jwtToken)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .accept(MediaType.APPLICATION_JSON);
// Below line is not used
//        mockMvc.perform(request).andReturn();

        //             Should be createCategory(eq(categoryCreateDto))?
        when(categoryCommandService.createCategory(categoryCreateDto)).thenReturn(
                categoryCreateResponseDto);
        // Mock Service method used in JwtRequestFilter
        when(myUserDetailsService.loadUserByUsername(eq("foo@email.com"))).thenReturn(dummy);
        MvcResult mvcResult = mockMvc.perform(request)
                .andExpect(status().is2xxSuccessful())
//                .andExpect(content().json(jsonResponse, true))
                .andExpect(jsonPath("$.id").value("2da4002a-31c5-4cc7-9b92-cbf0db998c41"))
//                .andExpect(jsonPath("$.title").value("category"))
                .andReturn();

        logger.info(mvcResult.getResponse().getContentAsString());
    }
    ...
}
-----------------------
@MockBean
private JwtUtil jwtUtil;
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    }
@WebMvcTest(value = CategoryCommandController.class, includeFilters = {
        // to include JwtUtil in spring context
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtUtil.class)})
class CategoryCommandControllerTest {

    Logger logger = LoggerFactory.getLogger(CategoryCommandController.class);

    @MockBean
    private CategoryCommandService categoryCommandService;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MyUserDetailsService myUserDetailsService;

    @MockBean
    private CategoryRepository categoryRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtRequestFilter filter;

    //    @WithMockUser
    @Test
    void testCreateCategory() throws Exception {

        CategoryCreateDto categoryCreateDto = new CategoryCreateDto("category");
        CategoryCreateDto categoryCreateResponseDto = new CategoryCreateDto(UUID.fromString("2da4002a-31c5-4cc7-9b92-cbf0db998c41"), "category");

        String jsonCreate = asJsonString(categoryCreateDto);
        String jsonResponse = asJsonString(categoryCreateResponseDto);
        UserDetails dummy = new User("foo@email.com", "foo", new ArrayList<>());
        String jwtToken = jwtUtil.generateToken(dummy);
        RequestBuilder request = MockMvcRequestBuilders
                .post("/api/adverts/category")
                .content(jsonCreate)
                .header("Authorization", "Bearer " + jwtToken)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .accept(MediaType.APPLICATION_JSON);
// Below line is not used
//        mockMvc.perform(request).andReturn();

        //             Should be createCategory(eq(categoryCreateDto))?
        when(categoryCommandService.createCategory(categoryCreateDto)).thenReturn(
                categoryCreateResponseDto);
        // Mock Service method used in JwtRequestFilter
        when(myUserDetailsService.loadUserByUsername(eq("foo@email.com"))).thenReturn(dummy);
        MvcResult mvcResult = mockMvc.perform(request)
                .andExpect(status().is2xxSuccessful())
//                .andExpect(content().json(jsonResponse, true))
                .andExpect(jsonPath("$.id").value("2da4002a-31c5-4cc7-9b92-cbf0db998c41"))
//                .andExpect(jsonPath("$.title").value("category"))
                .andReturn();

        logger.info(mvcResult.getResponse().getContentAsString());
    }
    ...
}
-----------------------
@MockBean
private JwtUtil jwtUtil;
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    }
@WebMvcTest(value = CategoryCommandController.class, includeFilters = {
        // to include JwtUtil in spring context
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtUtil.class)})
class CategoryCommandControllerTest {

    Logger logger = LoggerFactory.getLogger(CategoryCommandController.class);

    @MockBean
    private CategoryCommandService categoryCommandService;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MyUserDetailsService myUserDetailsService;

    @MockBean
    private CategoryRepository categoryRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtRequestFilter filter;

    //    @WithMockUser
    @Test
    void testCreateCategory() throws Exception {

        CategoryCreateDto categoryCreateDto = new CategoryCreateDto("category");
        CategoryCreateDto categoryCreateResponseDto = new CategoryCreateDto(UUID.fromString("2da4002a-31c5-4cc7-9b92-cbf0db998c41"), "category");

        String jsonCreate = asJsonString(categoryCreateDto);
        String jsonResponse = asJsonString(categoryCreateResponseDto);
        UserDetails dummy = new User("foo@email.com", "foo", new ArrayList<>());
        String jwtToken = jwtUtil.generateToken(dummy);
        RequestBuilder request = MockMvcRequestBuilders
                .post("/api/adverts/category")
                .content(jsonCreate)
                .header("Authorization", "Bearer " + jwtToken)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .accept(MediaType.APPLICATION_JSON);
// Below line is not used
//        mockMvc.perform(request).andReturn();

        //             Should be createCategory(eq(categoryCreateDto))?
        when(categoryCommandService.createCategory(categoryCreateDto)).thenReturn(
                categoryCreateResponseDto);
        // Mock Service method used in JwtRequestFilter
        when(myUserDetailsService.loadUserByUsername(eq("foo@email.com"))).thenReturn(dummy);
        MvcResult mvcResult = mockMvc.perform(request)
                .andExpect(status().is2xxSuccessful())
//                .andExpect(content().json(jsonResponse, true))
                .andExpect(jsonPath("$.id").value("2da4002a-31c5-4cc7-9b92-cbf0db998c41"))
//                .andExpect(jsonPath("$.title").value("category"))
                .andReturn();

        logger.info(mvcResult.getResponse().getContentAsString());
    }
    ...
}

How to return the argument, which the mock method was called with, as response?

copy iconCopydownload iconDownload
when(myObjectRepository.save(any(MyObject.class)))
     .then(AdditionalAnswers.returnsFirstArg());

Missing stub error on mockito in flutter. Trying to use setString on mocked SharedPreferences

copy iconCopydownload iconDownload
group('cacheNumberTrivia', () {
    const tNumberTriviaModel =
        NumberTriviaModel(number: 1, text: 'Test trivia');

    test('should call sharedPreferences to cache the data', () async {
      when(mockSharedPreferences.setString(any, any))
          .thenAnswer((_) async => true);
      dataSource.cacheLastNumberTrivia(tNumberTriviaModel);
      final expectedJsonString = jsonEncode(tNumberTriviaModel.toJson());
      verify(mockSharedPreferences.setString(
          cachedNumberTrivia, expectedJsonString));
    });
  });
when(mockSharedPreferences.setString(any, any))
          .thenAnswer((_) async => true);
-----------------------
group('cacheNumberTrivia', () {
    const tNumberTriviaModel =
        NumberTriviaModel(number: 1, text: 'Test trivia');

    test('should call sharedPreferences to cache the data', () async {
      when(mockSharedPreferences.setString(any, any))
          .thenAnswer((_) async => true);
      dataSource.cacheLastNumberTrivia(tNumberTriviaModel);
      final expectedJsonString = jsonEncode(tNumberTriviaModel.toJson());
      verify(mockSharedPreferences.setString(
          cachedNumberTrivia, expectedJsonString));
    });
  });
when(mockSharedPreferences.setString(any, any))
          .thenAnswer((_) async => true);

Data Class with Nullable Parameter in Kotlin 1.5.0 &amp; 1.6.0 Throwing BackendException

copy iconCopydownload iconDownload
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    val kotlinVersion = "1.6.0"
    kotlin("jvm") version kotlinVersion
}

repositories {
    mavenCentral()
}

PowerMockito returns null when mocking private method for testing public method

copy iconCopydownload iconDownload
@RunWith(PowerMockRunner.class)
@PrepareForTest(TextManager.class)
public class TextManagerTest {

  @Test
  public void checkIfConcatenationWorks() throws Exception {
    // Arrange
    TextManager textmanager = PowerMockito.spy(new TextManager());
    PowerMockito.doReturn("someText").when(textmanager,"concatenateTwoString"
    , Mockito.anyString()
    , Mockito.anyString());

    // Act
    String text = textmanager.concatenate("ji","bo");

    // Assert
    assertThat(text).isEqualTo("jibo");
  }
}
-----------------------
 <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <version>5.8.1</version>
    </dependency>


    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    import org.junit.Assert;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @PrepareForTest(TextManager.class)
    @RunWith(PowerMockRunner.class)
    public class TextManagerTest {
    
        @org.junit.Test  //Test using Junit4
        public void checkIfConcatenationWorksWithJunit4() throws Exception {
            TextManager textmanager = PowerMockito.spy(new TextManager());
            PowerMockito.doReturn("jibo").when(textmanager, "concatenateTwoString", Mockito.anyString(), Mockito.anyString());
            String text = textmanager.concatenate("ji", "bo");
            Assert.assertEquals(text,"jibo");
        }
    
        @Test  //Test using Junit5
        public void checkIfConcatenationWorksWithJunit5() {
            Assertions.assertEquals("text","jibo");
        }
    }
   <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
-----------------------
 <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <version>5.8.1</version>
    </dependency>


    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    import org.junit.Assert;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @PrepareForTest(TextManager.class)
    @RunWith(PowerMockRunner.class)
    public class TextManagerTest {
    
        @org.junit.Test  //Test using Junit4
        public void checkIfConcatenationWorksWithJunit4() throws Exception {
            TextManager textmanager = PowerMockito.spy(new TextManager());
            PowerMockito.doReturn("jibo").when(textmanager, "concatenateTwoString", Mockito.anyString(), Mockito.anyString());
            String text = textmanager.concatenate("ji", "bo");
            Assert.assertEquals(text,"jibo");
        }
    
        @Test  //Test using Junit5
        public void checkIfConcatenationWorksWithJunit5() {
            Assertions.assertEquals("text","jibo");
        }
    }
   <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
-----------------------
 <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <version>5.8.1</version>
    </dependency>


    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    import org.junit.Assert;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @PrepareForTest(TextManager.class)
    @RunWith(PowerMockRunner.class)
    public class TextManagerTest {
    
        @org.junit.Test  //Test using Junit4
        public void checkIfConcatenationWorksWithJunit4() throws Exception {
            TextManager textmanager = PowerMockito.spy(new TextManager());
            PowerMockito.doReturn("jibo").when(textmanager, "concatenateTwoString", Mockito.anyString(), Mockito.anyString());
            String text = textmanager.concatenate("ji", "bo");
            Assert.assertEquals(text,"jibo");
        }
    
        @Test  //Test using Junit5
        public void checkIfConcatenationWorksWithJunit5() {
            Assertions.assertEquals("text","jibo");
        }
    }
   <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>

Mock a method coming from parent class to return a mocked data

copy iconCopydownload iconDownload
@RunWith(PowerMockRunner.class)
public class OfferServiceTest {

    @Spy
    @InjectMocks
    private OfferService offerService = new OfferService();

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity<Object> entity;


    @Test
    public void test() {
        PowerMockito.when(offerService, "getHttpEntity", "www.example.com")
            .thenReturn(entity);

        PowerMockito.when(restTemplate.exchange(anyString(), any(), any(), any()))
                .thenReturn(something);

        assertEquals(someObject, offerService.get());
    }
}
 
@ExtendWith(MockitoExtension.class)
public class OfferServiceTest {

    @Spy
    @InjectMocks
    private OfferService offerService;

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity<Object> entity;


    @Test
    public void test() {
        when(ReflectionTestUtils.invokeMethod(offerService, "getHttpEntity", "www.example.com"))
                .thenReturn(entity);

        when(restTemplate.exchange(anyString(), any(), any(), any()))
                .thenReturn(something);

        assertEquals(someObject, offerService.get());
    }
}
-----------------------
@RunWith(PowerMockRunner.class)
public class OfferServiceTest {

    @Spy
    @InjectMocks
    private OfferService offerService = new OfferService();

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity<Object> entity;


    @Test
    public void test() {
        PowerMockito.when(offerService, "getHttpEntity", "www.example.com")
            .thenReturn(entity);

        PowerMockito.when(restTemplate.exchange(anyString(), any(), any(), any()))
                .thenReturn(something);

        assertEquals(someObject, offerService.get());
    }
}
 
@ExtendWith(MockitoExtension.class)
public class OfferServiceTest {

    @Spy
    @InjectMocks
    private OfferService offerService;

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity<Object> entity;


    @Test
    public void test() {
        when(ReflectionTestUtils.invokeMethod(offerService, "getHttpEntity", "www.example.com"))
                .thenReturn(entity);

        when(restTemplate.exchange(anyString(), any(), any(), any()))
                .thenReturn(something);

        assertEquals(someObject, offerService.get());
    }
}

Community Discussions

Trending Discussions on mockito
  • Skipping a method execution using Mockito
  • Mockito can not mock Random in Java 17
  • Java generics from Kotlin when verifying using Mockito?
  • Mockito vs Mocktail in Flutter
  • Unit testing retry in Spring Webflux with mocked response
  • How to write Junit test for methods with local variables
  • How to mock JWT token to use it with Mockito and Spring Boot
  • How to return the argument, which the mock method was called with, as response?
  • Missing stub error on mockito in flutter. Trying to use setString on mocked SharedPreferences
  • Data Class with Nullable Parameter in Kotlin 1.5.0 &amp; 1.6.0 Throwing BackendException
Trending Discussions on mockito

QUESTION

Skipping a method execution using Mockito

Asked 2022-Mar-21 at 09:41

I’m using Mockito for unit testing and I want to skip the execution of a method.

I referred to this ticket Skip execution of a line using Mockito. Here, I assume doSomeTask() and createLink() methods are in different classes. But in my case, both the methods are in the same class (ActualClass.java).

//Actual Class

public class ActualClass{
    
    //The method being tested
    public void method(){
        //some business logic
        validate(param1, param2);

        //some business logic
    }

    public void validate(arg1, arg2){
        //do something
    }
}

//Test class

public class ActualClassTest{

    @InjectMocks
    private ActualClass actualClassMock;

    @Test
    public void test_method(){

        ActualClass actualClass = new ActualClass();
        ActualClass spyActualClass = Mockito.spy(actualClass);

        // validate method creates a null pointer exception, due to some real time data fetch from elastic

        doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
        actualClassMock.method();
    }
}

Since there arises a null pointer exception when the validate method is executed, I’m trying to skip the method call by spying the ActualClass object as stated in the ticket I mentioned above. Still, the issue is not resolve. The validate method gets executed and creates a null pointer exception due to which the actual test method cannot be covered.

So, how do I skip the execution of the validate() method that is within the same class.

ANSWER

Answered 2022-Mar-04 at 09:36

You must always use your spy class when calling method().

   @Test
    public void test_method(){
        ActualClass spyActualClass = Mockito.spy(actualClassMock);

        doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
        spyActualClass.method();
    }

In practice, instead of

actualClassMock.method();

you must use

spyActualClass.method();

Source https://stackoverflow.com/questions/71349090

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install mockito

You can download it from GitHub, Maven.
You can use mockito like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the mockito component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with mockito
Consider Popular Unit Testing Libraries
Compare Unit Testing Libraries with Highest Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.