Mocking Static Methods with Mockito using Java

preview_player
Показать описание
Starting with version 3.4.0 Mockito now supports mocking static methods. This video demonstrates how to make use of this feature to mock the usage of Java's UUID and LocalDateTime classes.

In addition, you'll learn how to refactor the implementation to avoid mocking static methods.

Рекомендации по теме
Комментарии
Автор

I was looking exactly for something like this! Thank you!

mareksierocinski
Автор

I think we can also declare a Supplier<LocalDateTime> and then mock it in the test class without using Clock.

aminesafi
Автор

I have written mock for static method and used verify to check if it's called but it complains that method invocation has not taken place even once, should I start try block at the beginning of every test so there are no scope issues?basically it's giving "there were 0 interactions with this mock"

sahilsayyed
Автор

How do I mock final String field in Springboot with @Value annotation? using Junit5 with mockito getting Mockitot cannot mock/spy final class

subba
Автор

I want to mock static class, that should be shared with mutiple test cases in Mockito.How can i acheive this .Thanks in advance

jananid
Автор

Can you please tell how to mock static block. I cannot change the code, is there anyway I can mock it?

ssk
Автор

Hey Rick,

Does it only work in Java 11? I'm using Java 8 and every time it runs this line try(MockedStatic<UUID> mockedUuid = - Mocked uuid private final variable becomes null-null-null-null-null
. Any idea why. Really appreciate the help

spandanankoppala
Автор

I'm trying to prepare a mock for the below scenario of util static method.
public static <T> String toJSON(final T convertToJson) {}

Junit -> try(MockedStatic<JSONUtil> mockedJSONUtil = {

}
Getting an error of String is not compatible with verification. Any idea that could help me to proceed please? Yes, I'm using generic as param to static Util method.

mohammedsardar
Автор

Good video. Is it possible to capture a value from a static method?

mauriciotoledo
Автор

Nice Video! Thanks for your work. I have another scene for mock a static void method with my mock method, Could you know is this possible in Mockito?
The real scene in my project is a Helper class, which do a fill job for parameters. Below is the code snippet:
void workMethod(List<Goods> goodsList) {
// some code

// some code
}
Does mockito or Powermockito can mock the method? Thanks a lot!😁

taihengwei
Автор

How to mock localdatetime gloablly? When i do what is in this video time is mocked when method is called in test method but when localdatetime.now() is called from other method then its not mocked so it's kinda useless example

HasNoName