0

I have a class Component which creates two objects from other classes JMSConnector and AppiaConnector and links both of them.

I have a method that reads the status of both objects and return a combined value.

Here is the code: enter image description here

enter image description here

Problem I am facing when testing this method is I have no way of injecting mocks of appiaConnector and jmsConnector to test the behaviour of this method.

For example I tried this:

@RunWith(MockitoJUnitRunner.class) public class ComponentTest { @Mock JMSConnector jmsConnector; @Mock AppiaConnector appiaConnector; Component component = new Component(); @Test public void testGetStatus() { given(jmsConnector.getStatus()).willReturn(true); given(appiaConnector.getStatus()).willReturn(true); // this is what I want... but I can't dynamically inject these mocks into component ??? assertTrue(component.getStatus()); } } 

Is there a way that I can achieve this, or should I use stubs? (which seems an overkill for such a small method)

1 Answer 1

2

You can pass them as parameters instead of creating them inside the method.

public Component(AppiaConnector appiaConnector, JMSConnector jmsConnector) { // do your status check } 

Now if in your production code, you don't want to inject them, you can always create another constructor with no parameters. That way you keep your code the same but gain in testing flexibility

 public Component() { this(new AppiaConnector(), new JMSConnector()); } Component(AppiaConnector appiaConnector, JMSConnector jmsConnector) { // do your status check } 
Sign up to request clarification or add additional context in comments.

2 Comments

What you said is very true and I have already thought about it. But in my point of view, having an extra constructor just for the sake of unit testing is unnecessary. Which is why I opt for another solution in SO. I am very new to this profession. So please correct me (my point of view) if I am wrong.
having an extra constructor just for the sake of unit testing is unnecessary - I would disagree with this. I use Test Driven Development a lot, and to me tests are first class citizens in the code, and having the code testable is important to me. -- I know that some people dislike this extra constructor, but so far the only argument I had was we shouldn't add code for testing, which is fairly vague and abstract to be a strong argument. -- So if you don't want it, you're not alone, but if you really think about why you don't want it, you might not find strong reason against it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.