'Can I use @MockBean to mock a bean in just one method of my test class?

I have this mvc test class

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {

    private MockMvc mockMvc;

    @Resource
    private WebApplicationContext webApplicationContext;

    @MockBean
    private UserBO userBO;

    @Before
    public void init() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
// ...
    }
// ...

In one single test case I need to mock another bean to cover a special error handling branch. Is this possible? Is there any method I can use which does the same as @MockBean for the UserBO? (PermissionBO is not retuned by UserBO but used on the same level as UserBO in the class under test.)

@Test(expects=IllegalStatusException.class)
public void testErrorHandlingBranch() {
    // How can I mock the bean *PermissionsBO* only for this test?
    // like @MockBean PermissionsBO permissionsBO;
    // Is there a method like injectMockBean(PermissionsBO.class)?
    mockMvc.perform(...)
}


Solution 1:[1]

You should use thenReturn() inside your test method in the way to use a specific mocked value only inside a specific test.

For example: Mockito.when(userBO.example()).thenReturn("Specific test method mock");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 liviubiur