gpt4 book ai didi

spring - 如何使用 mockito 在 spring boot 中测试资源加载器

转载 作者:行者123 更新时间:2023-12-05 09:12:40 28 4
gpt4 key购买 nike

我正在开发一个 spring boot 2.1.3 应用程序,它有一个使用 ResourceLoader 类从资源目录读取文本文件的服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TestService {

@Autowired
ResourceLoader resourceLoader;

public String testMethod(String test) {
List<String> list = null;

Resource resource = resourceLoader.getResource("classpath:test.txt");
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
list = buffer.lines().collect(Collectors.toList());
} catch (Exception e) {
System.out.println("error : " + e);
}

if (list.contains(test)) {
return "in file";
}

return "not in file";
}
}

我正在使用 mockito 为该服务编写单元测试:

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration()
public class AServiceTest {
@InjectMocks
private TestService cut;

@Test
public void testSuccessfulResponse() {
String actualResponse = cut.method("teststring");
String expectedResponse = getSuccessfulResponse();

assertThat(actualResponse, is(expectedResponse));
}

但是当我运行测试时resourceLoader为null?

如何测试本例中的 resourceLoader 类。

最佳答案

我已经重写了你的测试。你不应该 mock 你的 TestService 因为你实际上是在测试它。这是我所做的。

  • mockFile:是一个代表你的文件的多行字符串
  • resourceLoader:模拟并设置它返回资源
  • mockResource:模拟 Resource 并将其设置为返回 mockFile 的 InputStream。
    @Test
public void testSuccessfulResponse() throws IOException {
String mockFile = "This is my file line 1\nline2\nline3";
InputStream is = new ByteArrayInputStream(mockFile.getBytes());
cut = new TestService();
ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
cut.resourceLoader = resourceLoader;

Resource mockResource = Mockito.mock(Resource.class);
Mockito.when(mockResource.getInputStream()).thenReturn(is);

Mockito.when(resourceLoader.getResource(Mockito.anyString())).thenReturn(mockResource);

String actualResult1 = cut.testMethod("line3");
Assert.assertEquals(actualResult1, "in file");

String actualResult2 = cut.testMethod("line4");
Assert.assertEquals(actualResult2, "not in file");
}

关于spring - 如何使用 mockito 在 spring boot 中测试资源加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57600621/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com