Shared Preferences is null in mockito - unit-testing

I am trying to mock a simple shared preferences using Mockito . Since, the examples on google are too complicated to make anything out of it, I decided to go ahead on my own.
The shared preferences are setup using dagger.
It crashes with NPE in the saveString method in the SharedPreferenceManager class on the putString line.
#Module
public class StudentModule {
#Provides
#Singleton
static Context getContext(Application application) {
return application.getApplicationContext();
}
#Provides
#Singleton
static SharedPreferences getSharedPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
There is a manager class:
public class SharedPreferenceManager {
private SharedPreferences sharedPreferences;
private Context context;
#Inject public SharedPreferenceManager(SharedPreferences sharedPreferences, Context context){
this.sharedPreferences=sharedPreferences;
this.context=context;
}
public String doSomething(){
return sharedPreferences.getString("s","");
}
public void saveString(String s){
System.out.println(sharedPreferences.getClass().getSimpleName());
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("s","bis").apply();
}
}
Here is the test:
#RunWith(MockitoJUnitRunner.class)
public class MockTest {
#InjectMocks
SharedPreferenceManager sharedPreferenceManager;
#Mock SharedPreferences sharedPreferences;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void isSharedPefWorking(){
sharedPreferenceManager.saveString("bis");
assertEquals("bis",sharedPreferenceManager.doSomething());
}
}

SharedPreferences uses a SharedPreferences.Editor which you're not currently mocking.
You would need to do something like the following to mock and verify the behaviour of your SharedPreferenceManager.
#RunWith(MockitoJUnitRunner.class)
public class MockTest {
#InjectMocks
SharedPreferenceManager sharedPreferenceManager;
#Mock
SharedPreferences sharedPreferences;
#Mock
SharedPreferences.Editor sharedPreferencesEditor;
final String savedString = "savedString";
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(sharedPreferences.edit()).thenReturn(sharedPreferencesEditor);
when(sharedPreferencesEditor.putString(anyString(), anyString())).thenReturn(sharedPreferencesEditor);
}
#Test
public void saveString() {
sharedPreferenceManager.saveString(savedString);
verify(sharedPreferencesEditor).putString("s", savedString);
}
#Test
public void getString() {
when(sharedPreferences.getString("s","")).thenReturn(savedString);
String preferenceString = sharedPreferenceManager.doSomething();
assertEquals(preferenceString, savedString);
}
}

Related

Unit testing RxJava in MVP presenter in android

I am new to TDD. Also new to MVP and Rxjava. I just dive into it and It is worth it. But I stuck at the testing part. I understand the basis of unit testing. It is a little bit difficult for me in beginning. But I stuck here and So how can test the presenter?
Here is the Presenter class -
public class NewsPresenter {
private final RxjavaService service;
private final MainView view;
private CompositeSubscription subscriptions;
public NewsPresenter(RxjavaService service, MainView view) {
this.service = service;
this.view = view;
subscriptions = new CompositeSubscription();
}
public void getNewsList(String urlQ){
view.showWait();
Subscription subscription = service.getNews(urlQ ,new RxjavaService.GetNewsCallback() {
#Override
public void onSuccess(Articles articles) {
view.removeWait();
view.getNewsListSuccess(articles);
}
#Override
public void onError(NetworkError networkError) {
view.removeWait();
view.onFailure(networkError.getAppErrorMessage());
Log.i("huh",networkError.getMessage());
}
});
subscriptions.add(subscription);
}
public void onStop(){
subscriptions.unsubscribe();
}
}
Here is the View Interface -
public interface MainView {
void showWait();
void removeWait();
void onFailure(String appErrorMessage);
void getNewsListSuccess(Articles articles);
}
Here is the RxJavaService class -
public class RxjavaService {
private final NewsRestService newsRestService;
public RxjavaService(NewsRestService newsRestService) {
this.newsRestService = newsRestService;
}
public interface GetNewsCallback {
void onSuccess(Articles articles);
void onError(NetworkError networkError);
}
public Subscription getNews(String q, final GetNewsCallback getNewsCallback) {
Log.i("stuck","service called");
return newsRestService.getNewsBySearch(q,"8dca7dea475e41e49518b2c61131e118",100)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(new Func1<Throwable, Observable<? extends Articles>>() {
#Override
public Observable<? extends Articles> call(Throwable throwable) {
return Observable.error(throwable);
}
})
.subscribe(new Subscriber<Articles>() {
#Override
public void onCompleted() {
Log.i("stuck","complete");
}
#Override
public void onError(Throwable e) {
getNewsCallback.onError(new NetworkError(e));
Log.i("stuck",e.getMessage());
}
#Override
public void onNext(Articles articles) {
getNewsCallback.onSuccess(articles);
Log.i("stuck","Onnext");
}
});
}
}
Here is the Test class where I am stuck-
#RunWith(MockitoJUnitRunner.class)
public class NewsListTest {
private NewsPresenter newsPresenter;
#Mock
private RxjavaService rxjavaService;
#Mock
private MainView mainView;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
newsPresenter = new NewsPresenter(rxjavaService,mainView);
}
#After
public void tearDown() throws Exception {
mainView = null;
newsPresenter.onStop();
}
#Test
public void Testing_The_Result() {
}
}
First things first
If you're into TDD, you'd never get into the situation you described. In TDD you start with a failing test, and just then go write the implementation. So your question is much more about testing then TDD.
I would recommend switching to RxJava2, as RxJava1 reaches End Of Life on March 31.
Look strange to me that RxJavaService changes the API from publish/subscribe to callbacks. Why not stick with rx API all the way to presenter?
Test with mocked RxJavaService
If you'd like to finish writing the test with the setup you have in the test, it would look something like this:
#Test
public void Testing_The_Result() {
final RxjavaService.GetNewsCallback[] callback = new RxjavaService.GetNewsCallback[1];
Mockito.when(rxjavaService.getNews(ArgumentMatchers.anyString(), ArgumentMatchers.any(RxjavaService.GetNewsCallback.class))).thenAnswer(new Answer<Subscription>() {
public Subscription answer(InvocationOnMock invocationOnMock) {
callback[0] = invocationOnMock.getArgument(1);
return mock(Subscription.class);
}
});
newsPresenter.getNewsList("some url");
Articles articles = new Articles();
callback[0].onSuccess(articles);
verify(mainView).removeWait();
verify(mainView).getNewsListSuccess(articles);
}
You can get rid of the ugly code by not using Mockito to mock RxJavaService, but rather roll you own hand-written mock, which would store the callback and provide it to the test.
However, I'd recommend a different approach.
Test with real RxJavaService and mocked NewsRestService
I'd say it makes more sense and gives a better test if we mocked only the NewsRestService:
#RunWith(MockitoJUnitRunner.class)
public class NewsList2Test {
private NewsPresenter newsPresenter;
#Mock
private MainView mainView;
#Mock
private NewsRestService newsRestService;
#Before
public void setUp() {
newsPresenter = new NewsPresenter(new RxjavaService(newsRestService), mainView);
}
#Test
public void show_success_in_view_when_there_are_articles() {
when(newsRestService.getNewsBySearch(eq("some url"), anyString(), anyInt()))
.thenReturn(Observable.just(new Articles()));
newsPresenter.getNewsList("some url");
verify(mainView).removeWait();
verify(mainView).getNewsListSuccess(any(Articles.class));
}
}

Test individual Spring Batch Tasklet step with parameters

I've implemented a simple job with 2 tasklets. I want to test the second tasklet by passing parameters.
I've read the Spring batch documentation and below my test:
#RunWith(SpringRunner.class)
#SpringBootTest
#ActiveProfiles({"test"})
#TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
StepScopeTestExecutionListener.class })
public class EtudeBatchApplicationTests {
#Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
public StepExecution getStepExecution() {
StepExecution execution = MetaDataInstanceFactory.createStepExecution();
execution.getJobExecution().getExecutionContext().putString("myValue", "foo,bar,spam");
return execution;
}
#Test
public void contextLoads() {
JobExecution jobExecution = jobLauncherTestUtils.launchStep("insertIncludedSiretsStep");
}
}
My problem is in my tasklet, the myValue is always null.
Below, the code of the tasklet:
#Component
#StepScope
#Slf4j
public class InsertIncludedSiretsTask implements Tasklet {
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
Object myValue = chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().get("myValue");
log.info("INSERTINCLUDEDSIRETSTASK runnning");
Thread.sleep(3000);
return RepeatStatus.FINISHED;
}
}
You can mock the ChunkContext following this example :
http://www.javased.com/index.php?source_dir=spring-insight-plugins/collection-plugins/spring-batch/src/test/java/com/springsource/insight/plugin/springbatch/TaskletCollectionAspectTest.java
Here is my code :
public ChunkContext createChunkContext() {
StepExecution stepExecution=Mockito.mock(StepExecution.class);
StepContext stepContext=Mockito.mock(StepContext.class);
ChunkContext chunkContext=Mockito.mock(ChunkContext.class);
JobExecution jobExecution= createJobExecution();
Mockito.when(chunkContext.getStepContext()).thenReturn(stepContext);
Mockito.when(stepContext.getStepExecution()).thenReturn(stepExecution);
Mockito.when(stepExecution.getJobExecution()).thenReturn(jobExecution);
return chunkContext;
}
public JobExecution createJobExecution() {
JobExecution execution = MetaDataInstanceFactory.createJobExecution();
execution.getExecutionContext().putString("myValue", "foo,bar,spam");
return execution;
}
#Test
public void testSendEmail() throws Exception {
StepContribution contribution= Mockito.mock(StepContribution.class);
ChunkContext chunkContext= createChunkContext();
sendReportTasklet.execute(contribution, chunkContext );
}
Based on Melkior answer which helped me a lot I simplify the test:
public class MyTaskletTest {
private static final String MY_JOB_PARAM = "my.job.param";
#Mock
private StepContribution stepContribution;
#Mock
private StepExecution stepExecution;
#Mock
private StepContext stepContext;
#Mock
private ChunkContext chunkContext;
private MyTasklet tasklet;
#Before
public void setupTest() {
when(chunkContext.getStepContext()).thenReturn(stepContext);
when(stepContext.getStepExecution()).thenReturn(stepExecution);
}
#Override
public void init() {
tasklet = new MyTasklet();
}
#Test
public void should_test_my_tasklet() throws Exception {
when(stepExecution.getJobParameters()).thenReturn(defaultJobParameters("myParam"));
tasklet.execute(stepContribution, chunkContext);
}
private JobParameters defaultJobParameters(String myParam) {
JobParametersBuilder paramsBuilder = new JobParametersBuilder();
paramsBuilder.addString(MY_JOB_PARAM, myParam);
return paramsBuilder.toJobParameters();
}
}

JUnit Tests for Liferay MVCPortlet using PowerMock

Im trying to make JUnit Test using PowerMock, but I have one problem. Here is my code:
public class MyGreeting extends MVCPortlet {
public static final String GREETING="greeting";
private static final String DEFAULT_GREETING="MY DEFAULT GREETING MESSAGE";
private static final Log _log = LogFactoryUtil.getLog(MyGreeting.class.getName());
#Override
public void render(RenderRequest req,RenderResponse res)
throws IOException, PortletException {
PortletPreferences prefs = req.getPreferences();
req.setAttribute(GREETING, prefs.getValue(GREETING, DEFAULT_GREETING));
super.render(req,res);
}
And I need to make JUnit test. I created another test package, new MyGreetingTest.java file, and come up to this code:
public class MyGreetingTest extends Mockito{
#BeforeClass
public static void setUpBeforeClass() throws Exception {
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
}
private MyGreeting portlet;
#Before
public void setUp() throws Exception {
portlet = new MyGreeting();
}
#After
public void tearDown() throws Exception {
}
#Mock
public RenderRequest request = mock(RenderRequest.class);
#Mock
PortletPreferences preferences = mock(PortletPreferences.class);
#Test
public final void renderTest() throws IOException, PortletException {
when(request.getPreferences()).thenReturn(preferences);
when(preferences.getValue(MyGreeting.GREETING, null)).thenReturn(value);
portlet.render(request, null);
String result = request.getAttribute(MyGreeting.GREETING).toString();
assertEquals(result, value);
}
But I have NullPointerException, because we can't apply getAttribute method to mock-request. Could you please tell me how to solve this problem? How can I test method with getAttribute method using Mockito?
I think you need to mock your method
Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00); // Mock implementation
when(stock.getValue()).thenCallRealMethod(); // Real implementation

Uses of Mockit.reset() on a mock object

Is it right to use Mockito.reset() in #Before method for mock objects which is being used in more than test method in the same test Class as shown below.
public class SampleTest {
#Mock
private CustomRepository customRepo;
#Before
public void setUp() {
Mockito.reset(customRepo);
}
#Test
public void test1(){
......
given(customRepo.someMethod()).willReturn(Answer1);
......
}
#Test
public void test2(){
......
given(customRepo.someMethod()).willReturn(Answer2);
......
}
}
You don't have to reset the mock because JUnit/Mockito creates a new instance of SampleTest and the mock object for each test.

#InjectMocks isnt actually injecting mocks

So i have a class that needs to be tested. Lets call it ClassToTest. It has a couple of Dao objects as fields.
Public class ClassToTest {
#Autowired
MyDao dao;
void methodToTest() {
dao.save(something);
}
}
As you can see ClassToTest does not contain any constructor or setter and I am using spring to autowire the fields.
Now, I have a base test class with all the dependencies that classToTest requires:
public abstract BaseTest {
#Mock
MyDao dao;
}
And the testClass extends this BaseTest class :
public class TestClass extends BaseTest {
#InjectMocks
ClassToTest classToTest = new ClassToTest();
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void test() {
classToTest.methodToTest();
}
}
This results in a null pointer exception when the save happens. However, if i change setup method to this :
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
classToTest.dao = dao;
}
the test passes.
My understanding was that when a class does not have a constructor or a setter, InjectMocks would inject the mocks by using field injection. Why is that not happening here?
Figured out that this is a bug in the 1.8.5 version that i was using : https://code.google.com/p/mockito/issues/detail?id=229.
Upgrading 1.10 fixed the issue.