我有一个Spring Integration测试,试图模拟一些Bean。由于某些原因,尽管我模拟了它们,但它们为NULL。这是代码段:
我要模拟的豆子
@Component
public class MockWS {
public String callSoapClient() throws JAXBException{
return "CallSoapCl";
}
}
使用Bean的类
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");
}
}
}
已对Bean进行模拟的Spring Boot集成测试
@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");
}
}
构建执行的输出: TEST BEAN:空
答案 0 :(得分:0)
您应该模拟一个接口,而不是一个类。另外,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");
}
}
答案 1 :(得分:0)
就我而言,以下注释组合有效:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ControllerThatIAmTesting.class })
@AutoConfigureMockMvc(addFilters = false) // if using MockMvc object
但是我必须使用@MockBean 注释显式声明我在测试类中的 ControllerThatIAmTesting 中使用的两个 Autowired 对象 - 否则 Spring 会抱怨它找不到合适的实现 - 顺便说一下,我的接口和它们的实现都在相同的对应中包
此外,使用 @WebMvcTest 而不是 @SpringBootTest(其他人建议它作为更具体的场景)导致 Spring 无法从我的 @Configuration 类中找到并初始化一些其他 @Autowired 依赖项。