0

I have a controller with multiple dependency which are solved by using spring configuration and Autowired in the controller class.

For Example:

@Controller
public class MyController{
    @Autowired
    private Type1 myDependency1;

    @Autowired
    private Type2 myDependency2;

}

I want to test this controller so that "mydependency1" is mocked and everything else is autowired.

How can I do this?

I was previously following following test:

@Mock
private Type1 myDependency1;

@InjectMocks
private Mycontroller controller = new MyController();

private MockMvc mockMvc;
@Before
public void setUp(){
    mockMvc = standaloneSetup(controller).build();
}

But this is only returning the controller with mock of myDependency1 and not injecting myDependency2.

sorryconnect
  • 33
  • 1
  • 6

1 Answers1

1

Alright after playing around with different mock tools, I gave up on the mock part and went back to profiles Function of spring.

I created a new profile called mockXYZ in my application-context.xml

And created the service i wanted to mock, or give a certain response as

@Service("type1")
@Profile("mockXYZ")
public class Type1Mock implements Type1{
    ....
}

And when testing, I made mockXYZ as my active profile, and used autowired my controller.

Like this I was able to mock only one dependency while other dependency working as normal, as they have only one implementation and would be selected for any profile.

Hope this helps others as well.

Thank you

sorryconnect
  • 33
  • 1
  • 6