Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我可以使用@MockBean在测试类的一个方法中模拟bean吗?_Java_Spring Boot_Unit Testing_Mocking - Fatal编程技术网

Java 我可以使用@MockBean在测试类的一个方法中模拟bean吗?

Java 我可以使用@MockBean在测试类的一个方法中模拟bean吗?,java,spring-boot,unit-testing,mocking,Java,Spring Boot,Unit Testing,Mocking,我有一门mvc测试课 @RunWith(SpringRunner.class) @SpringBootTest public class UserTest { private MockMvc mockMvc; @Resource private WebApplicationContext webApplicationContext; @MockBean private UserBO userBO; @Before public vo

我有一门mvc测试课

@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();
// ...
    }
// ...
在一个测试用例中,我需要模拟另一个bean来覆盖一个特殊的错误处理分支。这可能吗?是否有任何方法可以使用与
UserBO
相同的
@MockBean
PermissionBO
不会被
UserBO
重新调谐,而是在与测试类中的
UserBO
相同的级别上使用。)


您应该在测试方法中使用
thenReturn()
,以便仅在特定测试中使用特定模拟值

例如:
Mockito.when(userBO.example()).thenReturn(“特定测试方法模拟”)

您可能应该在全局范围内尝试使用
然后调用realmethod
,并在这一测试中实际模拟该方法。在这里阅读更多:谢谢,但是许可证不是从userBO返回的。我会澄清我的问题。我不知道你到底需要做什么。如果
PermissionBO
UserBO
处于同一级别,您可能还需要模拟
PermissionBO
。谢谢!我完全错了。在这个类中,
PermissionBO
没有被完全模仿的理由!
@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(...)
}