我正在尝试模拟具有范围原型的bean。
package com.aks.operation;
@Scope(value="prototype")
public class Operation{
public int sum(int a,int b){
return a+b;
}
}
@Service
public class UseOperation{
@Autowired
private ApplicationContext context;
public void doOperation() throws Exception{
Operation opr = context.getBean(Operation.class); // this will return the prototype instance
..
..
}
}
// Junit的
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/app-context.xml" })
@ActiveProfiles("DEV")
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class })
@ComponentScan(basePackages = { "com.aks.operation" })
public class TestOperation{
@InjectMocks
private Operation operation;
@Autowired
private UseOperation useOperation;
@Before
public void before() throws Exception{
MockitoAnnotations.initMocks(this);
when(operation.sum(1,2)).thenReturn(3);
}
@Test
public void doOperation() throws Exception{
useOperation.doOperation();// this function will create the prototype instance, and that instance should be mine for which I did mocking
}
}
请建议我采取什么方法来测试原型实例。
这是context.getBean(Class<?>)
总是将新实例返回给我。
感谢。