-
Notifications
You must be signed in to change notification settings - Fork 41.5k
Description
I am using MockBean in a set of Controller WebMvcTests. The bean in question is a session scoped bean and is effectively a DTO with a few methods hanging off it used in the controller.
@Bean
@SessionScope
public MyBeanDTO bean() {
return new MyBeanDTO();
}
The controller is thus:
@Controller
public class MyController {
@Autowired
private MyBeanDTO myBean;
//mappings which set/get values/invoke methods of the bean
}
I've written some unit tests using WebMvcTest. There are about a dozen tests. Most of them involve getting a value from the bean, or checking something matches by calling a method on the bean, or both. As such there are mocks for the methods of the bean, like getValue or matches(value):
@WebMvcTest(MyController.class)
@Import({ARealValidator.class,SecurityConfig.class})
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MyBeanDTO myBean;
@MockBean
private IMyService myService;
private UUID token = UUID.randomUUID();
@BeforeEach
void init() {
when(myBean.getValue()).thenReturn(token);
}
@Test
void testA() throws Exception {
when(myService.findByToken(token)).thenReturn(new MyObject());
mockMvc.perform(get("/some/request"))
.andExpect(view().name("some/view"));
}
@Test
void testB() throws Exception {
when(myBean.matches(token)).thenReturn(false);
mockMvc.perform(get("/another/request?val="+token.toString()))
.andExpect(redirectedUrl("invalid"));
}
}
When ran together, most of the tests pass - but some fail, and it looks as though the mock has somehow been bypassed, as adding a line to log myBean.toString()
returns myBean bean
for the passing tests, and MyBean(value=null, otherValue=null)
for the failing tests.
Running each test individually passes the tests, and adding @DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD)
allows them to pass ran as a suite (albeit slowly).
The behaviour of the MockBean toString suggests the mock isn't being consistently reset/applied - does this seem like an issue to you?