方法中的模拟bean和那些bean也在同一个类或超类

时间:2018-02-19 12:22:37

标签: spring-boot junit

@RunWith(SpringRunner.class)
@WebAppConfiguration
Class Test{

@Autowired
public SomeBean someBean;

@Test
public void testAccountPage2() throws Exception {
 SomeBean someBean = mock(SomeBean.class);  
 given(someBean.getAccount(anyString())).willReturn(getCustomer());
}

这里someBean.getAccount(anyString())不是模拟,它调用该bean impl的实际方法。似乎它采用了Autowired对象而不是模拟对象。

有人可以帮我在方法级别模拟bean吗?这些bean也在同一个类或超类中自动装配。

由于

2 个答案:

答案 0 :(得分:0)

要通过Mockito模拟替换Spring容器中的bean,请使用@MockBean

import org.springframework.boot.test.mock.mockito.MockBean; // import to add

@RunWith(SpringRunner.class)
@WebAppConfiguration
Class Test{

  @MockBean
  public SomeBean someBean;

  @Test
  public void testAccountPage2() throws Exception {      
    given(someBean.getAccount(anyString())).willReturn(getCustomer());
  }
}

要了解Spring Boot中MockitoMockBean之间的区别,您可以参考this question

答案 1 :(得分:0)

您需要注入模拟以使其工作而不是自动装配

//if you are just testing bean/services normally you do not need the whole application context
@RunWith(MockitoJUnitRunner.class)
public class UnitTestExample {

    @InjectMocks
    private SomeBean someBean = new SomeBean();

    @Test
    public void sampleTest() throws Exception {
        //GIVEN

        given(
            someBean.getAccount(
            //you should add the proper expected parameter
                any()
            )).willReturn(
            //you should add the proper answer, let's assume it is an Account class
            new Customer()
        );

        //DO
        //TODO invoke the service/method that use the getAccount of SomeBean
        Account result = someBean.getAccount("");

        //VERIFY
        assertThat(result).isNotNull();
        //...add your meaningful checks
    }
}