【发布时间】:2018-09-10 19:09:35
【问题描述】:
我很难将 spy bean 放入我的 ApplicationContext。我有一个名为 utilities 的 bean,类型为 Utilities:
@Component("utilities")
public class Utilities {
<snip>
/**
* Returns a random int. This is provided mostly for testing mock-ability
*
* @return a random integer
*/
public int getRandom() {
return (int) (Math.random() * Integer.MAX_VALUE);
}
}
它在我的 Spring 集成流程间接引用的类中使用。
然后我有这个木星测试:
@TestInstance(Lifecycle.PER_CLASS)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ExtendWith(SpringExtension.class)
@ContextConfiguration( classes = {
XmlLocations.class,
VisitorManager.class,
Utilities.class,
UnixTimeChannel.class
})
@WebMvcTest
//@TestExecutionListeners( { MockitoTestExecutionListener.class })
public class FullIntegrationTest {
@Autowired
private MockMvc mvc;
@SpyBean
private Utilities utilities;
private ClientAndServer mockServer;
private static final int MOCK_SERVER_PORT = 9089;
@BeforeAll
public void setUpBeforeClass() {
Mockito.when(utilities.getRandom()).thenReturn(Integer.MAX_VALUE);
mockServer = ClientAndServer.startClientAndServer(MOCK_SERVER_PORT);
RestAssuredMockMvc.mockMvc(mvc);
(new MockServerPingInit()).initializeExpectations(mockServer);
(new MockServerFullIntegrationInit()).initializeExpectations(mockServer);
}
@Test
public void t00200_IncomingMessage() {
RestAssuredMockMvc.given()
.queryParam("example", "example")
.when()
.request("POST", "/api/v1/incoming")
.then()
.statusCode(equalTo(200));
}
<snip>
但即使我创建了 spy bean 并在其上使用了 when/thenReturn,它也不会漂浮到我的应用程序上下文中等待被调用并返回它的模拟随机值。
我知道方法 utility.getRandom() 被调用,因为我可以在它上面放置一个断点并调试测试,它会命中 getRandom 方法,但是当我尝试添加一个如上所示的间谍 bean 并模拟时出 getRandom 返回一个固定值来测试断点仍然命中,所以我可以告诉真正的方法不是模拟被调用。
我也尝试将 when/thenReturn 放入测试中,以防它为时过早,但它没有帮助。
显然我做错了什么,可能在概念上是错误的。哈!
【问题讨论】:
-
如果从上下文配置中删除
Utilities.class会怎样?然后如果@SpyBean不起作用,您应该会看到应用程序上下文创建失败。 -
因为在 spring 集成流程中请求了实用程序 bean,所以在一个表达式中,我得到了这个:org.springframework.messaging.MessageHandlingException:表达式评估失败
-
请展示您如何在集成流程中使用
Utilities,并与我们分享整个堆栈跟踪。 -
我有同样的问题,我认为这是因为 beforeAll (应该是静态的)在实例尚未创建并且 spybean 是实例字段时触发。如果我想要 beforeAll 注释,我仍然不知道如何解决这个问题
标签: java spring mockito spring-integration