Проблема в репозиториях Mongo с весенним загрузочным тестом junit5 и тестовыми контейнерамиJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Проблема в репозиториях Mongo с весенним загрузочным тестом junit5 и тестовыми контейнерами

Сообщение Anonymous »

Проблема с репозиториями в тестовой конфигурации ниже.

Код: Выделить всё

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.junit.jupiter.api.AfterAll;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.testcontainers.containers.MongoDBContainer;
import org.testcontainers.containers.wait.strategy.Wait;

@SpringBootTest
@TestConfiguration
public class MongoTestConfig {
static MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:4.4.2")
.withExposedPorts(27017)
.waitingFor(Wait.forListeningPort());

static {
mongoDBContainer.start();
}

// Method to get the MongoDB connection URL with a specified database name
private String getMongoUrl(String dbName) {
return String.format("mongodb://%s:%d/%s",
mongoDBContainer.getContainerIpAddress(),
mongoDBContainer.getMappedPort(27017),
dbName);
}

@Bean
@Primary
public MongoTemplate mongoTemplate() {
String databaseName = "test"; // Replace with your desired database name
String mongoUrl = getMongoUrl(databaseName);
System.out.println("Connecting to MongoDB at: " + mongoUrl); // Log the connection URL
return new MongoTemplate(new SimpleMongoClientDbFactory(mongoUrl));
}

@Bean
@Primary
public MongoClient mongoClient() {
String mongoUrl = getMongoUrl("test"); // Same database name
System.out.println("Creating MongoClient for: " + mongoUrl);
return MongoClients.create(mongoUrl);
}

@Bean
public GridFsOperations gridFsOperations(MongoTemplate mongoTemplate) {
return new GridFsTemplate(mongoTemplate.getMongoDbFactory(), mongoTemplate.getConverter());
}

@AfterAll
static void stopContainer() {
mongoDBContainer.stop();
}
}

Код: Выделить всё

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.hamcrest.Matchers.*;

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

@WebMvcTest(AccountQueryController.class) // Replace with your actual controller class
public class AccountQueryControllerTest {

@Autowired
private MockMvc mockMvc;

@InjectMocks
AccountQueryController accountQueryController;

@Test
public void searchByOrgAndGroupAndName_ShouldReturnAccounts() throws Exception {
String query = "testQuery";

mockMvc.perform(get("/byorgandgroupandname")
.param("query", query))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(greaterThan(0)))) // Assumes it returns a list
.andExpect(jsonPath("$[0].name", is("SampleName"))); // Replace with expected field
}
}
Ошибка ниже:
Вызвано: org.springframework.beans.factory.NoSuchBeanDefinitionException: нет квалифицирующего компонента типа 'org. Springframework.data.repository.support.Repositories доступны: ожидается как минимум 1 bean-компонент, который квалифицируется как кандидат на автоматическое подключение. Аннотации зависимостей: {}

Подробнее здесь: https://stackoverflow.com/questions/790 ... containers
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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