SpringBoot单元测试之使用MockBean

场景

eg: 在实际项目开发中,需要做单元测试时,由于开发环境不同导致整个项目启动时就会报错,这个时候可以考虑使用MockBean

使用

@Controller
public class DemoAction {
	public String getUserName(String id) {
		return null;
	}
}

测试类

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

    /**
     * 项目启动时排除掉的bean
     */
    @MockBean
    private DemoAction demoAction;

    @Test
    public void testGetUserName() throws Exception {
        Mockito.when(demoAction.getUserName("1")).thenReturn("zhangsan");
		System.out.println(demoAction.getUserName("1"));
    }

}

猜你喜欢

转载自blog.csdn.net/qq_28988969/article/details/105496849