我尝试了 setter injection 来手动注入模拟 bean。
待测类
@ApplicationScoped
public class SomeService {
private ExternalService externalService;
@Inject
public void setExternalService(ExternalService externalService) {
this.externalService = externalService;
}
public String doSomething() {
return externalService.getData();
}
}
测试班
@HelidonTest
class SomeServiceTest {
@Inject
private SomeService someService;
private ExternalService externalService;
@BeforeEach
void setUp() {
externalService = Mockito.mock(ExternalService.class);
someService.setExternalService(externalService);
}
@Test
void doSomething() {
Mockito.when(externalService.getData())
.thenReturn("Mock data");
String actual = someService.doSomething();
Assertions.assertEquals("Mock data", actual);
}
}
还有一些方法可以通过模拟构造函数来模拟整个 bean。为此,我们必须使用@Observes 注解
@HelidonTest
public abstract class HelidonTestHelper {
private MockedConstruction<ExternalService> mockedConstruction;
void init(@Priority(1) @Observes @Initialized(ApplicationScoped.class) ContainerInitialized containerInitialized) {
mockedConstruction = Mockito.mockConstruction(ExternalService.class);
//mock common beans here. This will be executed once application scope is loaded.
}
void onStop(@Priority(1) @Observes @Destroyed(ApplicationScoped.class) ContainerShutdown containerShutdown) {
//do cleanup here if needed.
mockedConstruction.closeOnDemand();
}
}
完成上述操作后,您可以扩展我们创建的帮助程序类,而不是 helidon 测试。
class SomeServiceTest extends HelidonTestHelper {
@Inject
private SomeService someService;
@Inject //this will be a mock
private ExternalService externalService;
@Test
void doSomething() {
Mockito.when(externalService.getData())
.thenReturn("Mock data");
String actual = someService.doSomething();
Assertions.assertEquals("Mock data", actual);
}
}