gpt4 book ai didi

Spring - 如何测试具有 ApplicationEventPublisher 依赖关系的 Controller ?

转载 作者:行者123 更新时间:2023-11-28 20:27:05 25 4
gpt4 key购买 nike

我有一个正在发布事件的 Controller

@RestController
public class Controller
{
@Autowired
private ApplicationEventPublisher publisher;

@GetMapping("/event")
public void get()
{
publisher.publishEvent(new Event());
}
}

现在我想测试事件是否已发布。首先我尝试@MockBean ApplicationEventPublisher 并验证方法调用。但根据 https://jira.spring.io/browse/SPR-14335 这不起作用

所以我是这样做的:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = Controller.class)
public class ControllerTest
{
@Autowired
private MockMvc mockMvc;

@Test
public void getTest() throws Exception
{
this.mockMvc.perform(get("/").contentType(MediaType.APPLICATION_JSON)
.andExpect(status().isOk());
assertNotNull(Listener.event);
}

@TestConfiguration
static class Listener
{
public static Event event;

@EventListener
void listen ( Event incoming )
{
event = incoming;
}
}
}

这个常见用例是否有更简单的方法?

最佳答案

你可以这样做

@RunWith(SpringRunner.class)
public class ControllerTest {

private MockMvc mockMvc;

@MockBean
private ApplicationEventPublisher publisher;

@Before
public void setup() {
Controller someController= new Controller(publisher);
mockMvc = MockMvcBuilders.standaloneSetup(someController).build();
}

@Test
public void getTest() throws Exception
{
ArgumentCaptor<Event> argumentCaptor = ArgumentCaptor.forClass(Event.class);
doAnswer(invocation -> {
Event value = argumentCaptor.getValue();
//assert if event is correct
return null;
}).when(publisher).publishEvent(argumentCaptor.capture());

this.mockMvc.perform(get("/").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());

verify(publisher, times(1)).publishEvent(any(Event.class));
}

}

同时在 Controller 类中将字段注入(inject)更改为构造函数注入(inject)(这是一个很好的做法)。

@RestController
public class Controller
{

private ApplicationEventPublisher publisher;

@Autowired
public Controller(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
....
}

关于Spring - 如何测试具有 ApplicationEventPublisher 依赖关系的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52096936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com