简体   繁体   English

如何在 Java Spring boot 中模拟 RestTemplate?

[英]How to mock RestTemplate in Java Spring boot?

I am trying to mock RestTemplate getEntity() method using below code but i am getting exception and i am new for Unit testing我正在尝试使用以下代码模拟RestTemplate getEntity()方法,但出现异常,我是单元测试的新手

can some one help me please what is my mistake有人可以帮我吗请问我的错误是什么

Class班级

public List<SampleObject1> getGitHubUSersList(){

        try {
            ResponseEntity<SampleObject1[]>responseEntity = restTemplate.getForEntity("https://api.github.com/users", SampleObject1[].class);
            List<SampleObject1>arrayList  = Arrays.asList(responseEntity.getBody());
            System.out.println("final list is---->"+objectMapperl.writeValueAsString(arrayList));
            return arrayList;
        }catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }

Test Class测试班

public class SampleServiceTest1 {

    @Mock
    RestTemplate mockrestTemplate;

    @InjectMocks
    @Spy
    SampleService1 sampleService;

    @Before
    public void setup() {
    MockitoAnnotations.initMocks(this);
    }

@SuppressWarnings("unchecked")
@Test
public void getGitHubUSersListTest() {

    List<SampleObject1> sampleObject1s = new ArrayList<>();

    SampleObject1 sampoleObject1 = new SampleObject1();
    sampoleObject1.setId(1);
    sampoleObject1.setLogin("sample1");
    sampoleObject1.setNode_id("sample2");
    sampleObject1s.add(sampoleObject1);

    SampleObject1 sampoleObject2 = new SampleObject1();
    sampoleObject2.setId(2);
    sampoleObject2.setLogin("sample3");
    sampoleObject2.setNode_id("sample4");
    sampleObject1s.add(sampoleObject2);

    Mockito.doReturn(sampleObject1s).when(mockrestTemplate).getForEntity(Matchers.anyString(),  ArgumentMatchers.any(Class.class));

    List<SampleObject1> list = sampleService.getGitHubUSersList();

    assertNotNull(list);
}

} }

Error错误

org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to when() is null!
Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();
Also, if you use @Mock annotation don't miss initMocks()
    at com.example.microservice.service.SampleServiceTest1.getGitHubUSersListTest(SampleServiceTest1.java:50)

Your mock setup is wrong getForEntity does not return a List<SampleObject1> so you can not set that as return you need to return ResponseEntity<SampleObject1[]> .您的模拟设置是错误的getForEntity不返回List<SampleObject1>因此您不能将其设置为返回您需要返回ResponseEntity<SampleObject1[]>

So to solve your problem.所以要解决你的问题。 Declare a new mock声明一个新的模拟

@Mock
private ResponseEntity<SampleObject1[]> mockResponseEntity

doReturn(mockResponseEntity).when(mockrestTemplate).getForEntity(anyString(),  any(Class.class));
doReturn(new SampleObject1[]{sampoleObject1, sampoleObject2}).when(mockResponseEntity).getBody();

This should work.这应该有效。

I am assuming restTemplate response to be a List and not an Array.我假设 restTemplate 响应是一个列表而不是一个数组。

@RunWith(MockitoJUnitRunner.class)
public class SampleServiceTest {

    @InjectMocks
    private SampleService sampleService;

    @Mock
    private RestTemplate restTemplate;

    @Test
    public void name() {
        List<Pair> restResponseList = Arrays.asList(Pair.with("K1","V1"),Pair.with("K2","V2"));

        when(restTemplate.getForEntity(any(String.class), Matchers.<Class<List>>any()))
                .thenReturn(new ResponseEntity<>(
                        restResponseList,
                        new HttpHeaders(),
                        HttpStatus.OK));

        List<Pair> testResponse =sampleService.getGitHubUSersList();
        assertEquals(Pair.with("K1","V1"),testResponse.get(0));
        assertEquals(Pair.with("K2","V2"),testResponse.get(1));
    }
}

I see two potential issues with the code above which I think need to be fixed for your test to run correctly:我发现上面的代码有两个潜在问题,我认为需要修复这些问题才能使您的测试正确运行:

  1. You need to apply @RunWith(MockitoJUnitRunner.class) to your class declaration line (ie public class SampleServiceTest1 { ).您需要将@RunWith(MockitoJUnitRunner.class)到您的类声明行(即public class SampleServiceTest1 { )。
  2. When using the @InjectMocks and @Spy annotations, you need to have an actual instance.使用@InjectMocks@Spy注释时,您需要有一个实际实例。 As such, I would change your line SampleService1 sampleService;因此,我会更改您的行SampleService1 sampleService; to something like SampleService1 sampleService = new SampleService1();类似于SampleService1 sampleService = new SampleService1();

For examples on doing these two things, check out this helpful Baeldung article on Mockito annotations .有关执行这两件事的示例,请查看有关 Mockito annotations 的这篇有用的 Baeldung 文章

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

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