This is the setup of the test class:
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ServiceApplication.class)
@PrepareForTest({ MyClass.class })
public class ControllerTest {
@Autowired
public TestRestTemplate restTemplate;
public static MyClass myClass = Mockito.mock(MyClass.class);
@BeforeClass
public static void beforeClassSetup() throws Exception {
PowerMockito.mockStatic(MyClass.class);
BDDMockito.given(MyClass.getInstance(Mockito.anyString())).willReturn(myClass);
BDDMockito.given(myClass.foo()).willReturn("BAR");
// ...
}
.
.
.
// test cases
In configuration class of this project, for load some beans, I use this static call for generate the instance.
@Configuration
@ComponentScan(basePackages = { "package.from.another.project.in.production" })
public class Beans {
@Bean
public MyClass myClass() {
return MyClass.getInstance(K.FOO);
}
}
This is my controller that uses the bean, as well as the static call according to the parameters.
@RestController
public class Controller {
@Autowired
private MyClass myClass;
@GetMapping(path = "/")
public String doSomething() {
String filter = myClass.foo();
return filter;
}
@GetMapping(path = "/two")
public String doSomething2(@RequestParam Map<String, String> allParams) {
String accountId = allParams.get("account_id");
String filter = MyClass.getInstance(K.BAR + accountId).foo();
return filter;
}
}
The bean is autowired because its use is greater than instantiation by the getInstance()
method. In addition, the instantiation by the getIntance()
method is variable according to the parameter. Don't ask me why the MyClass class is like this, because the API was old and I'm slowly refactoring.
The issue is that the autowired bean is correctly mocked by PowerMockito.mockStatic(MyClass.class)
and also by @MockBean
(which I used initially), but the call MyClass.getInstance()
in Controller.class
does not work at all.
I think the problem should happen when Spring climbs its environment and does not load everything that has been correctly mocked by PowerMockito, just the classes of its beans. Can anyone help me solve this problem?
This is just a wild guess, have you tried using regular Mockito as opposed to BDDMockito? Just want to rule it out as a culprit.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.