我们需要跟踪数据库指标,因此我们使用 datasource-proxy 来跟踪它,以将其集成到我们创建的自定义数据源的 Spring Boot 项目中,如下所示
@Component
@Slf4j
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceBeanConfig
{
public DataSource actualDataSource()
{
EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
return databaseBuilder.setType(EmbeddedDatabaseType.H2).build();
}
@Bean
@Primary
public DataSource dataSource() {
// use pretty formatted query with multiline enabled
PrettyQueryEntryCreator creator = new PrettyQueryEntryCreator();
creator.setMultiline(true);
log.info("Inside Proxy Creation");
SystemOutQueryLoggingListener listener = new SystemOutQueryLoggingListener();
listener.setQueryLogEntryCreator(creator);
return ProxyDataSourceBuilder
.create(actualDataSource())
.countQuery()
.name("MyDS")
.listener(listener)
.build();
}
}
Run Code Online (Sandbox Code Playgroud)
当我们运行主应用程序时,数据源代理被拾取,但是当我们使用@DataJpaTest时,它没有被拾取。如何在 JUNIT 测试用例中启用数据源代理?
编辑::
使用SpringBeanPostProcessor配置Proxy DataSource
@Slf4j
@Configuration
public class DataSourceBeanConfig implements BeanPostProcessor …Run Code Online (Sandbox Code Playgroud) 我有一个运行良好的spring boot 2.0.0 M2应用程序.
我在构造函数上使用autowired
@RequestMapping(value = "/rest")
@RestController
public class AddressRestController extends BaseController{
private final AddressService AddressService;
@Autowired
public AddressRestController(final AddressService AddressService) {
this.AddressService = AddressService;
}
...
}
@Service
public class AddressServiceImpl extends BaseService implements AddressService {
@Autowired
public AddressServiceImpl(final AddressRepository AddressRepository) {
this.AddressRepository = AddressRepository;
}
private final AddressRepository AddressRepository;
...
}
public interface AddressRepository extends JpaRepository<Address, Integer>, AddressRepositoryCustom {
}
@Repository
public class AddressRepositoryImpl extends SimpleJpaRepository implements AddressRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Autowired
public AddressRepositoryImpl(EntityManager …Run Code Online (Sandbox Code Playgroud) 我正在为带有 spting boot 的控制器编写一个单元@WebMvcTest。
使用@WebMvcTest,我将能够注入一个MockMvc对象,如下所示:-
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
@WebMvcTest
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void my_controller_test() throws Exception {
mockMvc.perform(post("/create-user"))
.andExpect(status().isCreated());
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中,我Principal使用 spring 注入一个参数HandlerMethodArgumentResolver。请告诉我如何使用 编写单元测试MockMvc,以便我可以注入模拟Principal对象作为控制器方法中的参数。
自动配置的 Spring MVC 测试部分解释了带有注释的测试@WebMvcTest将扫描HandlerMethodArgumentResolver. 所以我创建了一个 bean,它扩展HandlerMethodArgumentResolver并返回模拟Principal对象,如下所示。
@Component
public class MockPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(Principal.class);
}
@Override
public Object …Run Code Online (Sandbox Code Playgroud) 我有个问题。请求您的帮助。我们有一个 Spring Boot 应用程序,我编写了没有 Mocks 的集成测试,而是使用TestRestTemplate和@SpringbootTest.
因此,在本地计算机上,当我执行测试时,它们执行得很好,正如我MyApplication.class在里面给出的@SpringbootTest
那样,它将启动 spring 应用程序上下文并执行测试。
到这里一切都很好。
但我们将此应用程序部署在不同的测试环境(例如 qa、e2e、staging)上,然后部署在生产环境上。因此,我们必须针对上述环境执行 Jenkins 作业进行集成测试作为验收测试。
我在这里的问题是:
请帮助..我是 Spring Boot 的新手,被困在这里。
预先非常感谢
我有一个@Service,我试图在单元测试中模拟它,但到目前为止我得到一个空值。在应用程序类中,我指定什么是 scanBasePackages。我必须以不同的方式做到这一点吗?谢谢。
\n\n这是我实现接口的服务类:
\n\n@Service\npublic class DeviceService implements DeviceServiceDao {\n\nprivate List<Device> devices;\n\n@Override\npublic List<Device> getDevices(long homeId) {\n return devices;\n}\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这是我的单元测试。
\n\npublic class SmartHomeControllerTest {\n\n private RestTemplate restTemplate = new RestTemplate();\n private static final String BASE_URL = \xe2\x80\x9c..\xe2\x80\x9d;\n\n @Mock\n private DeviceService deviceService;\n\n@Test\npublic void getHomeRegisteredDevices() throws Exception {\n\n Device activeDevice = new DeviceBuilder()\n .getActiveDevice(true)\n .getName("Alexa")\n .getDeviceId(1)\n .getHomeId(1)\n .build();\n Device inativeDevice = new DeviceBuilder()\n .getInactiveDevice(false)\n .getName("Heater")\n .getDeviceId(2)\n .getHomeId(1)\n .build();\n\n UriComponentsBuilder builder = UriComponentsBuilder\n .fromUriString(BASE_URL + "/1/devices");\n\n List response = restTemplate.getForObject(builder.toUriString(), List.class);\n\n …Run Code Online (Sandbox Code Playgroud) 在我的 Spring Boot 应用程序中,我正在使用 @SpringBootTest 编写集成测试。我正在使用配置类并在其上使用@ComponentScan,但它没有加载组件并且测试失败。
应用程序配置.java
@Configuration
@ComponentScan(basePackages = { "com.example.inventory" })
public class ApplicationConfig {
@Bean
public MapperFactory mapperFactory() {
return new DefaultMapperFactory.Builder().build();
}
}
Run Code Online (Sandbox Code Playgroud)
这里的 DefaultMapperFactory 是 Orika Mapper 的一部分,我用它来将模型转换为 DTO,反之亦然。
ProductSupplierIntegrationTests.java
@SpringBootTest(classes = ApplicationConfig.class)
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class ProductSupplierIntegrationTests {
// tests
}
Run Code Online (Sandbox Code Playgroud)
产品供应商模式
@Entity
public class ProductSupplier {
@Id
@GeneratedValue
private Long id;
private Long supplierId;
@ManyToOne
private Supplier supplier;
private Double buyPrice;
private boolean defaultSupplier;
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
供应商模式
@Entity
public class …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种方法来最小化 a 的启动时间SpringBootTest,目前启动和执行测试最多需要 15 秒。我已经使用了特定类的嘲笑webEnvironment和。standaloneSetup()RestController
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = MOCK)
public class DataControllerMvcTests {
@Autowired
private DataService dataService;
@Autowired
private DataController dataController;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.standaloneSetup(dataController)
.build();
}
@Test
@WithMockUser(roles = "READ_DATA")
public void readData() throws Exception {
mockMvc.perform(get("/data")).andExpect(status().is2xxSuccessful());
} …Run Code Online (Sandbox Code Playgroud) 我有一个 @SpringBootTest,用于在服务器上执行集成测试。根据配置,我希望服务器有不同的行为。配置本身由我的应用程序逻辑深处的 bean (scope = singleton) 读取,它们通过 @Value 注释读取属性。
如何使用不同的配置设置执行相同的测试?我尝试编写不同的测试类并用 @TestPropertySource(properties = XYZ) 注释它们。但这似乎也会影响所有其他测试(由于单例范围?)。有没有办法在测试后重置属性?
重新指定我的问题:我想在测试期间使用不同的 @Value 属性配置我的 bean,并且该值应该仅在整个特定测试执行期间有效。
提前感谢您的指点。
我想编写一个测试来@NotNull验证.@NotEmpty@ConfigurationProperties
@Configuration
@ConfigurationProperties(prefix = "myPrefix", ignoreUnknownFields = true)
@Getter
@Setter
@Validated
public class MyServerConfiguration {
@NotNull
@NotEmpty
private String baseUrl;
}
Run Code Online (Sandbox Code Playgroud)
我的测试如下所示:
@RunWith(SpringRunner.class)
@SpringBootTest()
public class NoActiveProfileTest {
@Test(expected = org.springframework.boot.context.properties.bind.validation.BindValidationException.class)
public void should_ThrowException_IfMandatoryPropertyIsMissing() throws Exception {
}
Run Code Online (Sandbox Code Playgroud)
}
当我运行测试时,它报告在测试运行之前启动应用程序失败:
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'myPrefix' to com.xxxxx.configuration.MyServerConfiguration$$EnhancerBySpringCGLIB$$4b91954c failed:
Run Code Online (Sandbox Code Playgroud)
我如何期望异常会编写负面测试?即使我将其替换BindException.class为Throwable.class应用程序也无法启动。
我们有一个应用程序,它对外部jar有运行时依赖性(例如在Spring-boot中运行的Talend作业).现在我们可以使用-Dloader.path参数从Spring-Boot启动它.但是,我们无法使用外部lib文件夹运行集成测试(即从Spring-Boot Test启动Talend作业).是否可以使用SpringBoot测试为集成测试加载外部作业?