当前位置: 首页 > 知识库问答 >
问题:

MockBean在Spring boot集成测试中不起作用

陆昕
2023-03-14
@Component
public class MockWS {

    public String callSoapClient() throws JAXBException{
        return "CallSoapCl";
    }
}
public class SmDpES2PortImpl implements ES2SmDp {
    @Autowired
    private MockWS mock;

    @Override
    public void es2DownloadProfile(ES2DownloadProfileRequest parameters) {
         try {
            LOG.info("\n\n\n TEST BEAN: " + mock.callSoapClient() + "\n\n");
          }
     }  
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ES2SmDpApplicationTests {

    @MockBean(name="mockWS")
    MockWS mockService;

    @Test
    public void test1Es2DownloadProfile_Sucess() throws MalformedURLException, JAXBException, SOAPException {
        when(mockService.callSoapClient()).thenReturn("CallMockCLient");
    }
}

共有1个答案

商绍元
2023-03-14

您应该模拟一个接口,而不是一个类。而且,smdpes2portimpl必须是Spring bean。请尝试以下操作:

接口:

public interface IMockWS {

    public String callSoapClient() throws JAXBException;
}

组件类:

@Component
public class MockWS implements IMockWS {

    @Override
    public String callSoapClient() throws JAXBException{
        return "CallSoapCl";
    }
}
@Service //Also @Component is a good alternative
public class SmDpES2PortImpl implements ES2SmDp {
    @Autowired
    private IMockWS mock; //Notice that you are wiring an interface

    @Override
    public void es2DownloadProfile(ES2DownloadProfileRequest parameters) {
         try {
            LOG.info("\n\n\n TEST BEAN: " + mock.callSoapClient() + "\n\n");
          }
     }  
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ES2SmDpApplicationTests {

    @MockBean
    IMockWS mockService; //Again, you are mocking the interface, not the implementing class

    @Test
    public void test1Es2DownloadProfile_Sucess() throws MalformedURLException, JAXBException, SOAPException {
        when(mockService.callSoapClient()).thenReturn("CallMockCLient");
    }
}
 类似资料:
  • 与@mockbean和@spybean一样,有没有类似于@fakebean/@dummybean的东西? 其思想是,该实例是100%真实的(具有预期的生产内部状态),并且它覆盖(或者添加bean,以防在配置中没有声明)上下文中的bean。理想情况下,您不需要创建TestConfiguration类并将其设置为Primary,因为这样可以在每个测试的基础上控制假冒,只有在需要时才可以。否则它使用主的

  • controller.java UserServiceImpl.java 我得到了这个错误 应用程序启动失败 描述: 我使用的SpringBoot版本:2.1.0.发行版

  • 在spring boot中,我试图创建我的第一个事务性测试,但trasaction不起作用。 null 我需要的是: 将数据插入事务。 从事务中读取数据。 测试返回的数据。 回滚事务。

  • 接收方类别组织。springframework。云netflix。带子RibbonLoadBalancerClient未定义或继承已解析方法“抽象组织”的实现。springframework。云客户ServiceInstance选择接口org的(java.lang.String、org.springframework.cloud.client.loadbalancer.Request)。sprin

  • 我正在尝试使用Mockito在SprinBoot应用程序中进行一些jUnit测试。 现在我的服务有了一些变量,可以从通过注释: 我试图通过像这样使用来测试这个: 但是,该属性不会被填充,并保持为。 这方面有很多TPOIC,但我还没能拼凑出一个解决方案。我看到解决方案建议,但它似乎想做一个集成测试,使服务加速,但由于无法连接到数据库,服务失败了。所以这不是我想要的。 我还看到一些解决方案建议我制作一