ImportJava.util.Random; Public classCodewithprivatemethod { Public voidMeaningfulpublicapi () {if(Dothegamble ("Whatever", 1 << 3)) { Throw NewRuntimeException ("Boom"); } } Private BooleanDothegamble (String whatever,intbinary) {Random random=NewRandom (System.nanotime ()); BooleanGamble =Random.nextboolean (); returnGamble; }}
Powermock:
ImportJava.lang.reflect.Method;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;ImportOrg.powermock.api.mockito.PowerMockito;Importorg.powermock.core.classloader.annotations.PrepareForTest;ImportOrg.powermock.modules.junit4.PowerMockRunner;Import Staticorg.mockito.Matchers.anyInt;Import Staticorg.mockito.Matchers.anyString;Import StaticOrg.powermock.api.mockito.PowerMockito.when;Import StaticOrg.powermock.api.support.membermodification.MemberMatcher.method; the @RunWith (Powermockrunner.class) @PrepareForTest (Codewithprivatemethod.class) Public classcodewithprivatemethodtest {@Test (expected= RuntimeException.class) Public voidWhen_gambling_is_true_then_always_explode ()throwsException {Codewithprivatemethod spy= Powermockito.spy (NewCodewithprivatemethod ()); When (Spy, Method (Codewithprivatemethod).class, "Dothegamble", String.class,int.class) . Witharguments (AnyString (), Anyint ()). Thenreturn (true); Spy.meaningfulpublicapi (); }}
http://codego.net/368377/
Powermock Mock Private Method