我如何使用Mockito

时间:2019-08-22 00:23:53

标签: spring unit-testing spring-boot mockito

我正在使用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为空吗?

在此示例中,如何测试resourceLoader类。

1 个答案:

答案 0 :(得分:2)

我已经重新编写了您的测试。您不应嘲笑您的TestService,因为您实际上正在对其进行测试。 这是我所做的。

  • mockFile:是代表您文件的多行字符串
  • resourceLoader:模拟并设置为返回Resource
  • mockResource:模拟的Resource并将其设置为返回模拟文件的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");
    }