有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用模拟覆盖自动连线实例

ServiceInstance。当对下面的URL进行PUT调用时,应该调用createInstance。为了能够测试在发送PUT请求时是否调用了正确的方法,我想模拟调用了该方法的对象(ServiceInstance)。但是,mock不会覆盖真实实例。我在这个环境中缺少什么

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MySpringBootApplication.class })
@SpyBean(ServiceInstance.class)

public class ServiceTest {

@Autowired
ServiceInstance serviceInstance;

@BeforeClass
public static void setUp() {
    SpringApplication.run(MySpringBootApplication.class, new String[] {});
}

@Test
public void sendPutRequest() throws JSONException, ClientProtocolException, IOException {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPut putRequest = new HttpPut("http://localhost:8080/v2/instances/1");
    //.....

    httpClient.execute(putRequest);
    Mockito.verify(serviceInstance, Mockito.times(1)).createInstance(Mockito.any());

}

}

共 (2) 个答案

  1. # 1 楼答案

    这是因为您没有使用mock,而是使用了spy,所以调用了real object和real method

    不要使用SpyBean注释,尝试使用MockBean注释(它在Spring上下文中模拟bean)

    Example

  2. # 2 楼答案

    您可以为测试创建配置文件

    @Profile("test")
    @Configuration
    public class ServiceInstanceConfiguration {
       @Bean
       @Primary
       public ServiceInstance serviceInstance() {
        return Mockito.mock(ServiceInstance.class);
       }
    }
    

    并使用配置文件“test”运行测试

    @ActiveProfiles("test")
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = { MySpringBootApplication.class })
    public class ServiceTest {
    
        @Autowired
        ServiceInstance serviceInstance;
      //...