gpt4 book ai didi

java - 问:Mockito - Using @Mock and @Autowired

转载 作者:行者123 更新时间:2023-12-01 14:17:36 25 4
gpt4 key购买 nike

我想使用 Mockito 测试一个具有其他两个服务类的服务类,如下所示.

@Service
public class GreetingService {

private final Hello1Service hello1Service;
private final Hello2Service hello2Service;

@Autowired
public GreetingService(Hello1Service hello1Service, Hello2Service hello2Service) {
this.hello1Service = hello1Service;
this.hello2Service = hello2Service;
}

public String greet(int i) {
return hello1Service.hello(i) + " " + hello2Service.hello(i);
}
}

@Service
public class Hello1Service {

public String hello(int i) {

if (i == 0) {
return "Hello1.";
}

return "Hello1 Hello1.";
}
}

@Service
public class Hello2Service {

public String hello(int i) {

if (i == 0) {
return "Hello2.";
}

return "Hello2 Hello2.";
}
}

我知道如何模拟 Hello1Service.classHello2Service.classMockito如下所示。
@RunWith(MockitoJUnitRunner.class)
public class GreetingServiceTest {

@InjectMocks
private GreetingService greetingService;

@Mock
private Hello1Service hello1Service;

@Mock
private Hello2Service hello2Service;

@Test
public void test() {

when(hello1Service.hello(anyInt())).thenReturn("Mock Hello1.");
when(hello2Service.hello(anyInt())).thenReturn("Mock Hello2.");

assertThat(greetingService.greet(0), is("Mock Hello1. Mock Hello2."));
}
}

我想模拟 Hello1Service.class并注入(inject) Hello2Service.class使用 @Autowired如下所示。
我厌倦了使用 @SpringBootTest但它没有用。
有没有更好的办法?
@RunWith(MockitoJUnitRunner.class)
public class GreetingServiceTest {

@InjectMocks
private GreetingService greetingService;

@Mock
private Hello1Service hello1Service;

@Autowired
private Hello2Service hello2Service;

@Test
public void test() {

when(hello1Service.hello(anyInt())).thenReturn("Mock Hello1.");
assertThat(greetingService.greet(0), is("Mock Hello1. Hello2."));
}
}

最佳答案

您想注入(inject)一些要形成的功能的依赖关系,然后使用 @Spy .
您不要加载 Spring Container 并使用 @Autowired .

@Spy
private Hello2Service hello2Service=new Hello2Service();

您可以阅读有关 的更多详细信息模拟与 spy ;

https://dzone.com/articles/mockito-mock-vs-spy-in-spring-boot-tests

关于java - 问:Mockito - Using @Mock and @Autowired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52119364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com