小编Jon*_*rth的帖子

如何在SpringJunit4TestRunner中将@ComponentScan与特定于测试的ContextConfiguration一起使用?

我正在测试一个Spring Boot应用程序.我有几个测试类,每个测试类都需要一组不同的模拟或其他定制的bean.

这是设置草图:

的src/main/java的:

package com.example.myapp;

@SpringBootApplication
@ComponentScan(
        basePackageClasses = {
                MyApplication.class,
                ImportantConfigurationFromSomeLibrary.class,
                ImportantConfigurationFromAnotherLibrary.class})
@EnableFeignClients
@EnableHystrix
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

package com.example.myapp.feature1;

@Component
public class Component1 {
    @Autowired
    ServiceClient serviceClient;

    @Autowired
    SpringDataJpaRepository dbRepository;

    @Autowired
    ThingFromSomeLibrary importantThingIDontWantToExplicitlyConstructInTests;

    // methods I want to test...
}
Run Code Online (Sandbox Code Playgroud)

的src /测试/ JAVA:

package com.example.myapp;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebAppConfiguration
@ActiveProfiles("test")
public class Component1TestWithFakeCommunication {

    @Autowired
    Component1 component1; // <-- the thing we're testing. wants the above …
Run Code Online (Sandbox Code Playgroud)

spring spring-test spring-boot

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

Java 11 HttpClient不发送基本身份验证

我编写了以下HttpClient代码,但它没有导致将Authorization标头发送到服务器:

public static void main(String[] args) {
    var client = HttpClient.newBuilder()
            .authenticator(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username", "password".toCharArray());
                }
            })
            .version(HttpClient.Version.HTTP_1_1)
            .build();
    var request = HttpRequest.newBuilder()
            .uri("https://service-that-needs-auth.example/")
            .build();
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .thenAccept(System.out::println)
            .join();
}
Run Code Online (Sandbox Code Playgroud)

我从我正在调用的服务中收到HTTP 401错误.就我而言,它是Atlassian Jira Cloud API.

我已经确认我的getPasswordAuthentication()方法没有被HttpClient调用.

为什么它不起作用,我该怎么做呢?

java http java-http-client java-11

9
推荐指数
1
解决办法
2518
查看次数