当前位置: 首页 > 知识库问答 >
问题:

Mockito mock为给定测试用例提供null

轩辕远
2023-03-14

我正在使用SpringRunner运行JUnit mockito测试用例,下面是类,我试图编写测试用例,但得到空对象

    public class AccountManager {

        public String getToken() throws Exception {
               @Autowired
               RestClient restClient;

                String auth = apiUserPrefix + apiUserName + BatchJobConstants.COLON + apiUserPassword;
                byte[] encodedAuth = Base64.encodeBase64(
                        auth.getBytes(StandardCharsets.UTF_8));
                String authHeader = BatchJobConstants.BASIC_SPACE + new String(encodedAuth);
                String token= null;
                MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
                data.add("grant_type", "client_credential");
                String accManagerUrl = accManagerHost+":"+accManagerPort+"/"+accManagerResPath;
                RestResponseObject responseObject = null;

                try {
                    responseObject = restClient.execute(accManagerUrl, HttpMethod.POST, data, String.class, authHeader);
                    if (responseObject != null && responseObject.getPayload() != null && responseObject.getStatusCode() == HttpStatus.OK) {
                        JsonElement responseJson = (JsonElement) responseObject.getPayload();
                        if (responseJson.isJsonObject()) {
                            token= responseJson.getAsJsonObject().get(BatchJobConstants.ACCESS_TOKEN).getAsString();
                        }catch(RunTimeException e) {
//e
}
    return token;
        }

//Junit测试用例

@RunWith(SpringRunner.class)
    public class AccountManagerTest {
    @InjectMocks
        AccountManager accountManager;
    @Mock
         RestClient restClient;
 @Test
    public void getTokenAccMgrSucess() throws Exception {
        RestResponseObject restResponseObject = Mockito.mock(RestResponseObject.class);

        Mockito.when(restClient.execute(Mockito.anyString(), Mockito.any(HttpMethod.class),
                Mockito.anyString(), Mockito.eq(String.class), Mockito.anyString())).thenReturn(restResponseObject);
        String token = accountManagerTokenProvider.getToken();
        Assert.assertEquals("Token value {} ", null, token);

    }

    }

但是下面的代码即使在模拟这个之后仍然返回空值,你能帮助如何模拟这个吗?

responseObject = restClient.execute(accManagerUrl, HttpMethod.POST, data, String.class, authHeader);

注意:只有Mockito需要使用无powermockito

共有2个答案

薛欣德
2023-03-14

最后只使用mockito just user any()而不是anyString(),因为对象与string不匹配

Mockito.when(restClient.execute(Mockito.any(), Mockito.any(HttpMethod.class),
                Mockito.any(), Mockito.eq(String.class), Mockito.any())).thenReturn(restResponseObject);
左丘凡
2023-03-14

对于自动连接字段,您不仅需要模拟它,还应该将模拟的类绑定到spring上下文。您有两个选择:1。将模拟类标记为主bean

@Configuration
    public class TestConfiguration {
        @Bean
        @Primary
        public RestClient restClient() {
            return Mockito.mock(RestClient.class);
        }
    }

2.使用@MockBean注释

 @MockBean
 RestClient restClient;

更多信息:
https://www.baeldung.com/injecting-mocks-in-spring
https://www.baeldung.com/java-spring-mockito-mock-mockbean

 类似资料:
  • 问题内容: 刚开始使用Robolectric,这似乎是我所需要的。但是,在使用SharedPreferences方面,我遇到了一些障碍。 我有两个测试案例 活动需要新的/空的sharedPreferences 活动期望其中已包含一些数据的sharedPreferences 对于测试用例1,测试按预期通过,所以一切都很好:) 但是,对于测试用例2,我似乎无法找出一种向Robolectric提供一些虚

  • 我正在使用TestNG和Java运行测试 这是在https://www.tutorialspoint.com/testng/testng_parameterized_test.htm 错误是这样说的:[Utils][ERROR][错误]org.testng.TestNGExc0019:@Test on method addProjectWork需要参数'url',但未在C:\用户\SStaple\

  • ParameterResolver defines the Extension API for dynamically resolving parameters at runtime. If a test class constructor, test method, or lifecycle method (see Test Classes and Methods) declares a par

  • 我使用了test dat provider和factory来处理示例数据,更像是从具有多个值的excel行中读取数据。因此,每个映射表示每行的列名和值,并将其添加到列表中,以获得从excel读取的所有值。现在我返回

  • 问题内容: 我是AngularJS的新手,正在尝试调试一些路由,但是我不知道如何显示/查看传递给routeprovider的路由。 例如,如果我当前的路由设置如下: 调试时,我想破坏代码,并在控制台日志中输入类似内容; 以显示将由“ .when”评估的路线。 问题答案: 您可以收听发出的多个事件。这些事件是: 和, (我鼓励阅读链接提供的文档,以获取每个文件的描述。) 此时,您可以在一个控制器或指

  • 用户数据文件时在元数据服务中的一个特殊的键,它保存了一份能给虚拟机实例中的云服务使用的文件。比如,cloud-init程序便使用了用户数据文件,这个程序是一个源自Ubuntu的开源包,能用在多个Linux发行版上,它可以接管云实例的初始化过程。 您可以将用户数据写在一份本地文件中,然后在创建实例时用--user-data <user-data-file>参数将其传入。 $ nova boot --