春季测试:在测试中创建少量类

问题描述

我有一个没有实现类的接口。

public interface MyInterface {
    String getName();
}

我还有另一个具有MyInterface作为依赖项的类。

@Component
public class SomeClass {
    @Autowired
    private MyInterface implementation;
    
    public MyInterface someMethod(List<MyInterface> list){
        //logic
    }
}

我必须测试SomeClass,但是我没有MyInterface实现类。在我可以用MyInterface将它们作为ApplicationContext的情况下,是否可以在测试中创建几个spring beans实现类并将它们添加到@Autowired中?

解决方法

假设您使用JUnit 5,则可以使用@TestConfiguration并在那里提供实现:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
class SomeServiceTest {

  @Autowired
  private MyInterface myInterface;

  @TestConfiguration
  static class TestConfig {

    @Bean
    public MyInterface myInterface() {
      
      /**
       * Long version of implementing your interface:
       * 
       *    return new MyInterface() {
       *         @Override
       *         public String getName() {
       *           return null;
       *         }
       *       }; 
       */
      
      // shorter ;-)
      return () -> "Hello World!";
    }
  }

  @Test
  void test() {
    SomeService someService = new SomeService(myInterface);
    System.out.println(someService.doFoo());
  }

}

但是您也可以使用Mockito为MyInterface创建一个模拟并进行快速的单元测试:

@ExtendWith(MockitoExtension.class)
class SomeServiceTest {

  @Mock
  private MyInterface myInterface;

  @InjectMocks
  private SomeService someService;

  @Test
  void test() {
    when(myInterface.getName()).thenReturn("Test");
    System.out.println(someService.doFoo());
  }

}

尽管上面的代码从技术上回答了您的要求,但正如J Asgarov在评论中提到的那样,请始终考虑采用这种方式是否有意义。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...