我有一个没有实现类的接口。
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
中?
答案 0 :(得分:2)
假设您使用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在评论中提到的那样,请始终考虑采用这种方式是否有意义。