jUnit:NPE on private member initialization

Have jUnit test, which initializes my bean:

ShowProducts sp = new ShowProducts();

got NullPointerException on following line in ShowProducts.java:

    private Locale locale = FacesContext.getCurrentInstance().getViewRoot()

    public Locale getLocale() {
        return locale;

    public String getLanguage() {
        return locale.getLanguage();

    public void localize() {
        String localeParam = FacesContext.getCurrentInstance()
        locale = new Locale(localeParam);

How to initialize properly this field in test?





        <h:commandLink action="#{showProducts.localize}" includeViewParams="true"
            <f:param name="lang" value="ru"/>
        <h:commandLink action="#{showProducts.localize}" includeViewParams="true"
            <f:param name="lang" value="ua"/>


Apparently your JSF FacesContext is not configured properly (I do no know much about faces, but I assume that setting them up and running in jUnit test is pretty complicated). However, there is help underway - use mocking.

In your test case, you like to assure that: - ShowProducts retrieves proper locale out of faces context / view root - does other things properly.

I recommend you to use jmockit. Your test case would become something like:

 public void testShowProducts(@Cascading final FacesContext facesContext) {
        final Locale locale = new Locale(...)
        new Expectations() {

       ShowProducts sp = new ShowProducts();

       ...  do your assertions other stuff there

This techuique is applicable to lot of contextes and simplifies test code greatly.

Need Your Help

Connecting SQLite3 to Ipad

iphone ipad sqlite3 ios5

I am doing a login and password app, were i want to connect this to SQLite DB, i copied the SQLite framework , imported it and added the db file to support folder but it is not working, please chec...

Doctrine dsn error with generate.php file

php doctrine yaml

I have been working on the introduction on the link below and have been able to complete previous steps but when it comes to running the generate.php file I get an error about the dsn. Is there mis...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.