How can I test resource loader in spring boot using mockito

apandey :

I am working on a spring boot 2.1.3 application which has a service which uses ResourceLoader class to read a text file from the resources directory:

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";
  }
}

I am writing a unit test for this service using 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));
  }

But when I run the test resourceLoader is null?

How can I test the resourceLoader class in this example.

Amit Phaltankar :

I have re-written your test. You should not mock your TestService because you are actually testing it. Here is what I have done.

  • mockFile: is a multi-line String that represents your file
  • resourceLoader: mocked and set it to return Resource
  • mockResource: mocked Resource and set it to return an InputStream of the mockFile.
    @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");
    }

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

Spring Mockito - Junit Test Controller - Тестовая модель один сервис

Junit 5 с Spring Boot: когда использовать @Extend с Spring или Mockito?

Как передать относительный путь к файлу в папке src / main / resource веб-приложения Spring Boot?

Как смоделировать асинхронный (@Async) метод в Spring Boot с помощью Mockito?

Вызов метода фиктивного объекта с использованием Spring Boot и Mockito

Mockito Spring Boot дает исключение нулевого указателя

Имитация свойства Spring @Resource с использованием Mockito

Spring boot loader cannot find resource

How to test DaoImpl methods using Junit and Mockito

Протестируйте методы интерфейса Spring-Boot Repository, не касаясь базы данных, используя Mockito

Утилита для фиксации класса службы Spring Test - Junit и Mockito

Spring boot 2.0.2, using Spring data how do I get message from entity validation

Spring-boot Test для загрузки внешних jar-файлов (эквивалент loader.path)

Как проверить аргументы, переданные статической функции, с помощью Java JUnit и Mockito (Spring Boot)

mockito and multiple HTTP in Spring Boot test

how can i set prefix path for thymeleaf in spring boot

How can I expose camel mbean in spring boot?

How to make Junit test in spring boot

Зависимости JUnit и Mockito для проекта Spring Boot

Spring Boot, Mockito, внедрение макета в компонент сеанса области видимости

How can I test SonarQube to see how well it actually works for catching security issues in a spring boot app?

Внедрение Mockito имитирует тест Spring Boot

How can I solve the error I get while testing the spring boot rest api via postman?

Создание тестового примера Mockito для модуля Spring Boot

Как провести модульное тестирование метода контроллера с помощью Spring Boot и mockito

How to test InternalServerError using mockito in Repository?

Using spring WebFlux, how can I get all the RequestHandlerMappings?

How can I get drawable resource by string?

How to unit-test StdDeserializer in spring boot?

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    Merging legends in plotly subplot

  3. 3

    Как я могу нарисовать заполненный прямоугольник в JFreeChart?

  4. 4

    Проблема с window.print в Safari

  5. 5

    Перебирайте несколько столбцов в фрейме данных Panda и находите уникальные значения подсчета

  6. 6

    JetBrains Rider enable-migrations для ASP.NET MVC на Mac

  7. 7

    migrate MongoDB container service - mongodump command not found

  8. 8

    Как создать переменную с использованием класса Color, который включает только выбранные цвета?

  9. 9

    Ошибка XDG0062: не удалось установить «Контент». в режиме навигации MUXC

  10. 10

    Как загрузить ZIP-файл в Nexus с помощью Maven и избежать создания артефакта pom в Nexus?

  11. 11

    QString удалить последние символы

  12. 12

    Symfony 4, Postgres - `Неверное значение параметра client_encoding:« utf8mb4 »` при выполнении команды doctrine

  13. 13

    HTML Body говорит cz-shortcut-listen = "true" с инструментами разработчика Chrome?

  14. 14

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  15. 15

    Как создать простую анимацию в Xamarin с помощью SkiaSharp

  16. 16

    Установка pip с использованием Python 2.7, установленного в ArcGIS

  17. 17

    Qt - не растягивать виджеты в QVBoxLayout

  18. 18

    How to convert C++/CLI string to const char*

  19. 19

    sbt: Как разрешить зависимости Maven, использующие свойства Maven

  20. 20

    Flutter: Unhandled Exception: FileSystemException: Creation failed, path = 'Directory: '' (OS Error: Read-only file system, errno = 30)

  21. 21

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

популярныйтег

файл