Ошибка неудовлетворенной зависимости: отсутствует компонент TestService1 в сотрудникеControllerJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Ошибка неудовлетворенной зависимости: отсутствует компонент TestService1 в сотрудникеController

Сообщение Anonymous »

Я столкнулся со следующей ошибкой при запуске класса WorkerControllerTest. Мне было приказано не изменять класс контроллера. Может ли кто-нибудь помочь мне решить эту проблему?
Изображение
< /p>
org.springframework.beans.factory.UnsatisfiedDependencyException: ошибка создания bean-компонента с именем «....controllers.EmployeeController»: неудовлетворительно Зависимость, выраженная через поле «testService1»: нет подходящего компонента типа «...services.TestService1»: ожидается как минимум 1 компонент, который соответствует критериям автоматического подключения. Аннотации зависимостей: {@org.springframework.beans.factory.annotation.Autowired(required=true)
Я пробовал использовать следующие подходы:
Использование отражения для установки частных полей,
Внедрение конструктора в тестовый класс,
Создание класса конфигурации теста для добавления необходимых bean-компонентов,
Настройка зависимостей вручную,
/>Я все еще не могу решить проблему.
@ContextConfiguration(classes = {TestConfiguration.class})
@WebFluxTest(controllers = EmployeeController.class)
@Profile("local")
public class EmployeeControllerTest {
@MockBean
private TestService1 testService1;
@MockBean
private TestService2 testService2;
private WebTestClient webTestClient; /* If I use @Autowired for this field, I'm getting an UnsatisfiedDependencyException: Error creating bean due to an unsatisfied dependency expressed through the field 'webTestClient'.*/
@InjectMocks
private EmployeeController employeeController;
private JwtAuthenticationToken jwtAuthenticationToken;
int pageIndex=0;
int pageSize=10;

@BeforeEach
void setup(){
MockitoAnnotations.openMocks(this);
jwtAuthenticationToken = mock(JwtAuthenticationToken.class);
when(jwtAuthenticationToken.getName()).thenReturn("testUser");
/*If I don't use the code below, I get the error: Cannot invoke "org.springframework.test.web.reactive.server.WebTestClient.post()" because "this.webTestClient" is null.*/
webTestClient = WebTestClient.bindToController(employeeController).webFilter(new SecurityContextServerWebExchangeWebFilter()).build();
}
@Test
void testEmployee(){
Page mockPage = new PageImpl(Collections.emptyList());
when(testService1.list(eq(jwtAuthenticationToken), eq(pageIndex), eq(pageSize))).thenReturn(Mono.just(mockPage));
webTestClient.post() .uri("/test/employee/{index}/{size}",pageIndex,pageSize).exchange().expectStatus().isOk().expectBodyList(EmployeeDto.class).hasSize(0);
}}

/*Controller Code:I've been instructed not to modify the controller class*/
@RestController
@RequestMapping("/test")
public class EmployeeController {
@Autowired //Field injection is not recommended
private TestService1 testService1;
@Autowired //Field injection is not recommended
private TestService2 testService2;
@PostMapping("/employee/{index}/{size}")
public Mono users(@NonNull JwtAuthenticationToken principal, @PathVariable int index, @PathVariable int size) {
return testService1.list(principal, index, size);
}
}


Подробнее здесь: https://stackoverflow.com/questions/791 ... controller
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»