1

How can we unit test private class ?

For example with an example of private class @Autowired with qualifier I would like to verify if the good qualifier is call

public class MyClass {
    @Autowired
    IHelloService helloService;

    public void sayHello(List<Person> list) {
        for(Person person : list) {
            helloService.sayHello(person);
        }
    }
}

.

@Primary
@Component
public class SayHelloService implements ISayHello {

    @Autowired
    @Qualifier("french")
    ISayHello french;
    @Autowired
    @Qualifier("english")
    ISayHello english;

    @Override
    public void sayHello(Person person) {
        switch (person.getLanguage) {
            case "EN":
                english.sayHello(Person person);
            break;
            case "FR":
                french.sayHello(Person person);
            break;
            default:
            break;
        }
    }
}

.

@Qualifier("french")
Component
class SayHelloFrenchService implements ISayHello {
    public void sayHello(Person person) {
        sysout("Bonjour " + person.getName());
    }
}

@Qualifier("english")
Component
class SayHelloFrenchService implements ISayHello {
    public void sayHello(Person person) {
        sysout("Hello " + person.getName());
    }
}

Edit: I failed my example: the twice qualifier class were private

7
  • 1
    There are no private classes in your examples. Use constructor injection rather than field injection. Commented Mar 6, 2019 at 13:48
  • @Michael why do you suggest using constructor injection? Commented Mar 6, 2019 at 13:50
  • by private class, do you mean: instance variables? actually, you don't, otherwise they're less and less unit tests. you mock them Commented Mar 6, 2019 at 13:50
  • @russellhoff Because you can make the fields private and final without sacrificing your ability to test the class. Commented Mar 6, 2019 at 13:51
  • @russellhoff one reason to take it seriously, is because the Spring team advocates constructor injection. It makes testing a lot easier. Commented Mar 6, 2019 at 13:51

1 Answer 1

0

If i @Mock the interface it works.

I thought i must @Mock the implementation...

But i can't write tests of implementation of private class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.