具有自动装配依赖项的模拟服务 class
Mock Service class that has Autowired dependencies
我有一个服务 class 和一个配置 class 如下:
public class MyService{
@Autowired
MyConfig myconfig;
@Autowired
private WebClient webClient;
private String result;
public String fetchResult(){
return webClient.get().uri(myConfig.getUrl()).retrieve().bodyToMono(String.class).block();
}
}
@ConfigurationProperties("prefix="somefield")
@Component
class MyConfig{
private String url;
//getter & setter
}
}
下面是Junit:
@Runwith(MockitoJUnitRunner.class)
public class TestMe{
@InjectMocks
MyService myService;
@Test
public void myTest(){
when(myService.fetchResult().then return("dummy");
}
}
当我在服务 class 的 webClient 上 运行 这个 class 时,我收到空指针错误。
可能是什么问题。我是 JUnit 的新手。
我如何为此编写合适的 JUnit。
使 class 可测试的最简单方法是使用构造函数注入
public class MyService{
private final MyConfig myconfig;
private final WebClient webClient;
private String result;
@AutoWired
MyService(
MyConfig myconfig,
WebClient webClient
) {
this.myconfig = myconfig;
this.webClient = webClient;
}
...
}
我有一个服务 class 和一个配置 class 如下:
public class MyService{
@Autowired
MyConfig myconfig;
@Autowired
private WebClient webClient;
private String result;
public String fetchResult(){
return webClient.get().uri(myConfig.getUrl()).retrieve().bodyToMono(String.class).block();
}
}
@ConfigurationProperties("prefix="somefield")
@Component
class MyConfig{
private String url;
//getter & setter
}
}
下面是Junit:
@Runwith(MockitoJUnitRunner.class)
public class TestMe{
@InjectMocks
MyService myService;
@Test
public void myTest(){
when(myService.fetchResult().then return("dummy");
}
}
当我在服务 class 的 webClient 上 运行 这个 class 时,我收到空指针错误。 可能是什么问题。我是 JUnit 的新手。 我如何为此编写合适的 JUnit。
使 class 可测试的最简单方法是使用构造函数注入
public class MyService{
private final MyConfig myconfig;
private final WebClient webClient;
private String result;
@AutoWired
MyService(
MyConfig myconfig,
WebClient webClient
) {
this.myconfig = myconfig;
this.webClient = webClient;
}
...
}