监视没有PowerMock的课程
我不想再使用PowerMock。因为Junit5开始嘲笑静态课程。因此,我试图摆脱PowerMock方法。
当我使用PowerMock时,我可以轻松地监视具有私有构造函数的类,然后我称静态方法。
这是我的代码的一部分(当我使用PowerMock时)
@RunWith(PowerMockRunner.class)
@PrepareForTest(MessageValidationUtils.class)
public class MessageValidationServiceTest {
@Mock
private CheckpointCustomerService checkpointCustomerService;
@Mock
private ProductClientService productClientService;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
PowerMockito.spy(MessageValidationUtils.class);
}
是MessageValidationUtilsss.class的间谍对象后,我正在测试以下内容:
when(MessageValidationUtils.validateTelegramKeyMap(messageProcessDto.getMessageMessageType(),
messageProcessDto.getMessageKeyValueMap())).thenAnswer((Answer<Boolean>) invocation -> true);
经过一些研究,我找不到与有私人构造师和私人构造师和的班级有关的东西静态方法。
I don't want to use powermock anymore. Because junit5 started mocking static classes. So i am trying to get rid of powermock methods.
While i was using PowerMock, i could easily spy a class that has a private constructor, and then i was calling the static methods.
This is a part of my code ( When i was using PowerMock )
@RunWith(PowerMockRunner.class)
@PrepareForTest(MessageValidationUtils.class)
public class MessageValidationServiceTest {
@Mock
private CheckpointCustomerService checkpointCustomerService;
@Mock
private ProductClientService productClientService;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
PowerMockito.spy(MessageValidationUtils.class);
}
After i make a spy object of MessageValidationUtils.class, i was testing this:
when(MessageValidationUtils.validateTelegramKeyMap(messageProcessDto.getMessageMessageType(),
messageProcessDto.getMessageKeyValueMap())).thenAnswer((Answer<Boolean>) invocation -> true);
After some research i couldn't find anything related to spy a class that has a private constructor and static methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
MockStatic
在Mockito中的定义您可以指定设置以默认情况下执行真实执行mockito.withSettings()。defaultanswer(mockito.calls_real_methods)
。这样,您的静态模拟将像间谍
一样工作。让我们创建简单的
utils
用于测试的类。为
Method2
进行模拟,然后执行Method1
和Method3
示例的真实执行:
更新:
使用
模拟>
in@beforeeach
更新:
Mockito不提供静态
间谍
创建的方法,但是您可以在那里定义自己的UTILS和IMPLEMET间谍静态定义。这样,您的测试将更清楚:
During
mockStatic
definition in Mockito you can specify setting to perform real execution by defaultMockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS)
. In this way, your static mock will work likeSpy
.Let's create simple
Utils
class for testing.Make mock for
method2
and perform real execution ofmethod1
andmethod3
Example for your class:
UPDATE:
Example to use
mockStatic
in@BeforeEach
UPDATE:
Mockito does not provide method for static
Spy
creation, but you can define own utils and implemet spy static definition there.In this way your tests will look more clear: