简体   繁体   English

模拟String.valueof()

[英]Mocking String.valueof()

I'm testing my spring controller and trying to do the following 我正在测试弹簧控制器,并尝试执行以下操作

Controller 控制者

Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
    String role = String.valueOf(authentication.getAuthorities());
    if(role.contains("user")) {
        ...
    }

Test 测试

@Test
public void testLoginUser() throws Exception {
    User user = new User();
    user.setLogin("user");
    user.setRoleid(1L);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user,user));
    when(String.valueOf(Collection.class)).thenReturn("user");

But I get 但是我明白了

org.mockito.exceptions.misusing.MissingMethodInvocationException

I need my if block to be true and execute. 我需要if块为true并执行。
Is there any way it can be done? 有什么办法可以做到吗?

Because 因为
1. String class is final and you cant mock final classes with Mockito. 1. String类是最终类,您无法使用Mockito模拟最终类。
2. String.valueOf is a static metod and you cant mock static method with Mockito 2. String.valueOf是一个静态方法,您无法使用Mockito模拟静态方法

From Mockito FAQ Mockito常见问题解答

What are the limitations of Mockito Mockito的局限性是什么

 Needs java 1.5+ Cannot mock final classes // String is Final Cannot mock static methods... // String.valueOf is static 

Either mock authentication.getAuthorities() method or use Powermock . 可以使用模拟authentication.getAuthorities()方法或使用Powermock

This link might help. 链接可能会有所帮助。

String.valueOf is a static method and is not mocked by Mockito. String.valueOf是一个静态方法,Mockito并未对其进行模拟。 Your expression will simply resolve to a String instance with the value "class java.util.Collection" . 您的表达式将简单地解析为值为"class java.util.Collection"的String实例。

Why does Mockito not mock static methods? 为什么Mockito不模拟静态方法? .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM