标签: spring-boot-test

@DataMongoTest正在创建一个null MongoTemplate

我一直在尝试按照以下链接中的说明尝试添加自动配置的嵌入式MongoDB实例以进行黄瓜集成测试.这是目前无法正常工作,因为我不断获得一个null MongoTemplate.我以为@DataMongoTest会自动配置"@Autowired private MongoTemplate mongoTemplate;" 这不是这种情况吗?以下是我的代码:

mongoTemplate.save(doc,collection); 抛出nullpointer异常.

@SpringBootTest(classes = AppCommentApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DataMongoTest
public abstract class SpringIntegrationTest {

    @Value("${local.server.port}")
    public int port;

    @Autowired
    private MongoTemplate mongoTemplate;

    protected void importJSON(String collection, String file) {
        try {
            for (String line : FileUtils.readLines(new File(file), "utf8")) {
                Document doc = Document.parse(line);
                mongoTemplate.save(doc, collection);
            }
        } catch (IOException e) {
            throw new RuntimeException("Could not import file: " + file, e);
        }
    }

}


@RunWith(Cucumber.class)
@CucumberOptions(format = "pretty",
                 features = "src/test/resources/features",
                 glue = "com.app.comment.cucumber") …
Run Code Online (Sandbox Code Playgroud)

spring mongodb spring-data-mongodb spring-boot spring-boot-test

7
推荐指数
1
解决办法
1971
查看次数

为 Spring 控制器测试配置自定义 Json Serializer

我正在测试一个控制器:

@RestController()
public class MessagesController {
...
}
Run Code Online (Sandbox Code Playgroud)

使用@WebMvcTest 注释:

@RunWith(SpringRunner.class)
@WebMvcTest(value = {MessagesController.class})
public class MessagesControllerTest {

    private MockMvc mvc;

....

 this.mvc.perform(
                get("/messages/{id}", "dummyId")
                        .contentType(MediaType.APPLICATION_JSON))

                .andDo(print())
                .andExpect(status().isOk());
...
Run Code Online (Sandbox Code Playgroud)

但是当我启动我的测试时,Spring 尝试序列化一个 List> 类型的对象,但它失败了:

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotWritableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 500
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-boot spring-boot-test

7
推荐指数
0
解决办法
1003
查看次数

应用程序类中的@ComponentScan 中断@WebMvcTest 和@SpringBootTest

我正在创建带有@WebMvcTest注释的测试,发现如果我@ComponentScan在应用程序类中有注释,它将破坏测试的预期行为。

根据WebMvcTestjavadoc:

使用此批注将全面禁用自动配置,而是只适用于相关的测试MVC(即配置@Controller@ControllerAdvice@JsonComponent FilterWebMvcConfigurerHandlerMethodArgumentResolver咖啡豆,但没有@Component@Service@Repository豆类)“。

问题是@ComponentScan它正在实例化用@Service. 如果不是@ComponentScan我在@SpringBootApplication注释中指定扫描基础包,一切都按预期工作。

当我在@WebMvcTest注释中指定控制器类时会发生另一个问题。当@ComponentScan应用程序类中有注释时,它将加载所有控制器,而不是仅加载指定的控制器。

这是 Spring Boot 中的错误吗?

我想使用@ComponentScan是因为注释中excludeFilters没有的属性@SpringBootApplication

我发现的一种解决方法是创建一个带有@Configuration注释的单独类并将其移动到@ComponentScan那里。

spring-boot spring-boot-test

7
推荐指数
1
解决办法
3430
查看次数

在spring boot test中使用wiremock随机端口设置属性

我有一个Spring Boot测试,它使用wiremock来模拟外部服务.为了避免与并行构建冲突,我不想为wiremock设置固定端口号,并且希望依赖其动态端口配置.

该应用程序使用application.yml中external.baseUrl设置的property()(在src/test/resources下).但是我找不到以编程方式覆盖它的方法.我尝试过这样的事情:

    WireMockServer wireMockServer = new WireMockServer();
    wireMockServer.start();
    WireMock mockClient = new WireMock("localhost", wireMockServer.port());
    System.setProperty("external.baseUrl", "http://localhost:" + wireMockServer.port());
Run Code Online (Sandbox Code Playgroud)

但它不起作用,而是使用application.yml中的值.我看过的所有其他解决方案都使用静态值覆盖属性(例如在某些注释中),但在运行测试之前我不知道wiremock端口的值.

澄清:

弹簧引导和线缆都在随机端口上运行.那很好,我知道如何获得两个端口的价值.然而,wiremock应该模拟外部服务,我需要告诉我的应用程序如何到达它.我和这家external.baseUrl酒店一起做.我想在测试中设置的值当然取决于线程端口号.我的问题是如何在Spring启动测试中以编程方式设置属性.

java configuration spring-boot wiremock spring-boot-test

7
推荐指数
4
解决办法
8206
查看次数

SpringBootTest 从扫描中排除包

我想在使用 spring@SpringBootTest时以与使用@ComponentScan. 有没有像

@SpringBootTest(excludeFilters =@ComponentScan.Filter(
            type = FilterType.REGEX,
            pattern = "package\\.\\.to\\.Exclude.*"))
Run Code Online (Sandbox Code Playgroud)

java spring-boot spring-boot-test

7
推荐指数
1
解决办法
5879
查看次数

如何修复无法找到meta.properties的嵌入式kafka中的错误

我正在尝试使用kafka,kafka-streams和cassandra对应用进行集成测试。但是,当我尝试设置测试类时,我遇到了2个错误:错误[main] BrokerMetadataCheckpoint:无法读取dir下的meta.properties文件错误[主要] KafkaServer:无法读取日志目录下的meta.properties

我正在使用spring-boot-starter 2.1.2,spring-boot-starter-test 2.1.2,spring-kafka 2.2.0,spring-kafka-test 2.2.0,apache.kafka-streams 2.1.0

尝试更改logs.dir和logs.dirs参数。使用@EnableKafka @EnableKafkaStreams

@RunWith(SpringRunner.class)
@SpringBootTest
@EmbeddedKafka(partitions = 3, controlledShutdown = false, count = 1, topics = {"zc.deviceposition"}, brokerProperties = {"listeners=PLAINTEXT://localhost:9092", "port=9092", "log.dir=/home/name/logs"})
@EmbeddedCassandra(timeout = 60000)
@CassandraDataSet(value = {"bootstrap_test.cql"}, keyspace = "statistics")
@ActiveProfiles("test")
@DirtiesContext
public class CassandraTripsAggregatorProcessorSupplierIntegrationTest {
  @Test
  public void someTest() {System.out.println("hello world");}
}
Run Code Online (Sandbox Code Playgroud)

我期望使用嵌入式kafka运行上下文,但是现在我收到一个错误,指出meta.properties不存在

spring-boot-test embedded-kafka spring-kafka-test

7
推荐指数
1
解决办法
820
查看次数

SpringbootTest + TestContainers: how do I refresh the database after tests pollute the database

I am using an abstract class like this:

@SpringBootTest(classes = MyAppApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class AbstractIntegrationTest {

    static {
        PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer().withPassword("password")
                .withUsername("postgres").withDatabaseName("MyApp");
        postgreSQLContainer.start();

        System.setProperty("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
        System.setProperty("spring.datasource.password", postgreSQLContainer.getPassword());
        System.setProperty("spring.datasource.username", postgreSQLContainer.getUsername());

    }
Run Code Online (Sandbox Code Playgroud)

Then I have many tests that leverage that use that class like this:

public class moreTests extends AbstractIntegrationTest {

    TestRestTemplate restTemplate = new TestRestTemplate("my-user", "password"); 
    HttpHeaders headers = new HttpHeaders();

    @Test
    public void SimpleHealthCheck() {    
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);    
        ResponseEntity<String> response = …
Run Code Online (Sandbox Code Playgroud)

postgresql spring-boot spring-boot-test testcontainers

7
推荐指数
1
解决办法
8859
查看次数

如何将多个参数传递给@ValueSource

我正在尝试执行参数化 JUnit 5 测试,如何完成以下任务?

@ParametrizedTest
@ValueSource //here it seems only one parameter is supported
public void myTest(String parameter, String expectedOutput)
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用@MethodSource,但我想知道在我的情况下我是否只需要更好地理解@ValueSource

junit5 spring-boot-test

7
推荐指数
3
解决办法
1万
查看次数

Mockito 注入模拟 Spring Boot 测试

您好,我有一个包含映射器和存储库的服务类:

@Service
public class ProductServiceImp implements ProductService {
    @Autowired
    private ProductRepository repository;
    @Autowired
    private WarehouseApiMapper mapper;

    public ProductServiceImp(ProductRepository repository) {
        this.repository = repository;
    }
}
Run Code Online (Sandbox Code Playgroud)

存储库:

@Repository
public interface ProductRepository extends JpaRepository<Product, Integer> {
}
Run Code Online (Sandbox Code Playgroud)

映射器:

@Mapper(componentModel = "spring")
public interface WarehouseApiMapper {
    WarehouseApiMapper mapper = Mappers.getMapper(WarehouseApiMapper.class);

    Product ProductDtoToProduct(ProductDto productDto);

    ProductDto ProductToProductDto(Product product);
}
Run Code Online (Sandbox Code Playgroud)

在测试类中,我想注入模拟存储库和自动装配映射器这是我的测试类:

@SpringBootTest
public class ProductServiceTest {

    @Mock
    ProductRepository repository;

    @InjectMocks
    ProductServiceImp service;

    @ParameterizedTest
    @MethodSource("provideParametersProductUpdate")
    void assert_that_product_is_updated_correctly(String productName, BigDecimal productPrice) {
        Product oldProduct = new Product("Product that …
Run Code Online (Sandbox Code Playgroud)

dependency-injection mocking mockito spring-boot spring-boot-test

7
推荐指数
1
解决办法
7285
查看次数

@Value 属性在 JUnit 测试中始终为 null

我正在为可以使用两种不同配置运行的 Spring 应用程序编写一些单元测试。两个文件给出了两种不同的配置application.properties。我需要为每个类编写两次测试,因为我需要验证适用于某个配置的更改不会影响另一个配置。

为此我在目录中创建了两个文件:

src/test/resources/application-configA.properties

src/test/resources/application-configB.properties

然后我尝试使用两个不同的值加载它们@TestPropertySource

@SpringBootTest
@TestPropertySource(locations = "classpath:application-configA.properties")
class FooTest {
  @InjectMock
  Foo foo;

  @Mock
  ExternalDao dao;

  // perform test
}
Run Code Online (Sandbox Code Playgroud)

该类Foo是这样的:

@Service
public class Foo {
  @Autowired
  private External dao;

  methodToTest() {
    Properties.getExampleProperty();
    this.dao.doSomething(); // this needs to be mocked!
  }
}
Run Code Online (Sandbox Code Playgroud)

虽然班级Properties是:

@Component
public class Properties {
  private static String example;

  @Value("${example:something}")
  public void setExampleProperty(String _example) {
    example = _example;
  }

  public static String getExampleProperty() {
    return …
Run Code Online (Sandbox Code Playgroud)

java mockito spring-boot junit5 spring-boot-test

7
推荐指数
1
解决办法
8179
查看次数