Junit runs all Test with the parameter marked with #Parameter - junit

In the following code, I would like to run TestMethod1 with the parameters marked with #Parameters
#RunWith(Parameterized.class)
public class Foo{
private boolean input;
private boolean expected;
public Foo(boolean input, boolean expected{
this.input=input;
this.expected=expected;
}
#Parameters
public static List<Object[]> data() {
return Arrays.asList(new Object[][]{{false, false}, {false, false}});
}
#Test
public void TestMethod1(){
assertEquals(expected, Baar.StaticMethod(input);
}
#Test
public void TestMethod2(){
assertEquals(expected, Baar.StaticMethod2(false);
}
The Problem is when I run junittes, both methods TestMethod1 and TestMethod2 are run with these parameters. How to tell the testrunner to run only TestMethod1 with the parameters marked with #Parameters?

not sure if pure junit allows it but there is plenty of plugins. in your case (all parameters known up-front) the simplest way would be to do parametrized testing with zohhak:
#RunWith(ZohhakRunner.class)
public class TestMyClass {
#TestWith({
"true, false".
"false, true"
})
public void test1(int actual, int expected) { //test }
#TestWith({
"false, false".
"true, true"
})
public void test2(int actual, int expected) { //test }
#Test
public void test3() { //test }
}
if you need to build parameters in run-time (generating, reading from file etc.) then you can check things like junit-dataprovider or junit-params

Related

mockito unit testing Wanted but not invoked:

I have seen there are similar question already exist in SO , I tried all the solution , but couldn't fix my problem , as I am new to tdd
I have a class like this
public class AppUpdatesPresenter {
public void stopService() {
ServiceManager.on().stopService();
}
}
I have the test class like this
#RunWith(MockitoJUnitRunner.class)
public class AppUpdatesPresenterTest {
#Mock
AppUpdatesPresenter appUpdatesPresenter;
#Mock
ServiceManager serviceManager;
#Mock
Context context;
#Test
public void test_Stop_Service() throws Exception {
appUpdatesPresenter.stopService();
verify(serviceManager,times(1)).stopService();
}
}
When I tried to test that , if I call stopService() method , then ServiceManager.on().stopService(); called at least once .
But I am getting the following error
Wanted but not invoked:
serviceManager.stopService();
-> at io.example.myapp.ui.app_updates.AppUpdatesPresenterTest.test_Stop_Service(AppUpdatesPresenterTest.java:103)
Actually, there were zero interactions with this mock.
Not sure whats gone wrong .
When you call appUpdatesPresenter.stopService();, nothing happened as you didn't tell it what should be happened.
To make your test pass, you need stubbing the appUpdatesPresenter.
#Test
public void test_Stop_Service() throws Exception {
doAnswer { serviceManager.stopService(); }.when(appUpdatesPresenter).stopService()
appUpdatesPresenter.stopService();
verify(serviceManager).stopService();
}
Btw, the above test is meaningless as you stub all the things.
To make the test case meaningful, you should inject the ServiceManager instead of coupling it with AppUpdatePresenter.
public class AppUpdatesPresenter {
private final ServiceManager serviceManager;
public AppUpdatesPresenter(ServiceManager serviceManager) {
this.serviceManager = serviceManager;
}
public void stopService() {
sm.stopService();
}
}
Then make the AppUpdatesPresenter under test.
#InjectMock AppUpdatesPresenter appUpdatesPresenter;
Now the test case doesn't rely on canned interaction but real implementation of your code.
#Test
public void test_Stop_Service() throws Exception {
appUpdatesPresenter.stopService();
verify(serviceManager).stopService();
}

How to define only last test method assertion will be involved

I have a two class's for testing regression test. We have in some case more than one test method in the class and in the methods we are usually using assertions. I want to know if there any method is available, to make use #Rule test method only the last method in the class. Here is my code:
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JustOneClass extends ParentClass {
#Rule
public class GeneralRule articleHotspotRule = new class GeneralRule (this);
#Test
aMethod(){
Assert.assertTrue()
}
#Test
bMethod(){
Assert.assertTrue()
}
#Test
cMethod(){
Assert.assertTrue()
}
#Test
dMethod(){
if this assert is failed Assert.assertTrue()
}
}
We have a another class which extends TestWatcher
public class GeneralRule extends TestWatcher {
private ParentClass baseTest;
public GeneralRule (final GeneralRule generalRule) {
this.baseTest = generalRule;
}
#Override
protected void failed(final Throwable e, final Description description) {
baseTest.after();
}
}
in this case I want that baseTest.after() will be used only if assertion of dMedthod is failed.
Rather than using a rule to try and check for the failure, how about checking for the failure condition and then fail the test programatically? Certainly not as elegant or reusable as a rule but may satisfy your requirement.
#Test
public void dMethod() {
...
if(actual == false) { // check for failure scenario
after(); // call the after method
Assert.fail("hello failure"); // programatically fail the test
}
}

Not able to partial mock static method with PowerMockito

I am to mock a static function named toBeMockedFunction in Util class. This method is called from toBeUnitTested which is a public static void method. I want toBeMockedFunction to do nothing. I tried many approaches (snippet posted of such 2) of partial mock and stubbing and unable to succeed.
Please suggest what I am doing wrong.
public class Util {
// Some code
public static void toBeUnitTested(CustomObject cb, CustomObject1 cb1, List<CustomObject2> rows, boolean delete) {
// some code
toBeMockedFunction(cb, "test", "test");
}
public static CustomObject toBeMockedFunction(CustomObject cb, String str1) {
// some code
}
}
And below is my junit class
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Util.class})
public class UtilTest {
#Test
public void Test1() {
PowerMockito.spy(Util.class);
//mock toBeMocked function and make it do nothing
PowerMockito.when(PowerMockito.spy(Util.toBeMockedFunction((CustomObject)Mockito.anyObject(), Mockito.anyString()))).thenReturn(null);
Util.toBeUnitTested(cb, "test", "test");
}
}
Approach2
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.toBeUnitTested((CustomObject)Mockito.anyObject(),Mockito.anyString())).thenCallRealMethod();
Util.toBeUnitTested(cb, "test", "test");
This is an example of how can do that:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Util.class})
public class UtilTest {
#Test
public void Test1() {
PowerMockito.spy(Util.class);
PowerMockito.doReturn(null).when(Util.class, "toBeMockedFunction", Mockito.any(CustomObject.class), Mockito.anyString(), Mockito.anyString());
List<CustomObject2> customObject2List = new ArrayList<>();
customObject2List.add(new CustomObject2());
Util.toBeUnitTested(new CustomObject(), new CustomObject1(), customObject2List, true);
}
}
Please note that the code of your OP doesn't compile. Method toBeMockedFunction(CustomObject cb, String str1) receives only 2 parameters and you are calling with 3: toBeMockedFunction(cb, "test", "test");. As you could see, I've added the last one to the method signature.
Hope it helps

How to have individual SetUp functions in Junit

I have two test functions and for each I want to have different #Before methods. How to achieve this ?
Although it seems to be convenient to organize all the test under the same class, for your case I think the best option is to separate the tests into different classes, each one with his corresponding setUp.
An alternative (I prefer the previous option) could be call the setUp directly in your test method, like the example as follows:
public class FooTest {
public void setUpMethod1() {
// do setUp things
}
public void setUpMethod2() {
// do setUp things
}
#Test
public void testMethod1() {
setUpMethod1();
// Test
}
#Test
public void testMethod2() {
setUpMethod2();
// Test
}
}
Only as a curiosity (IMO not recomended for your case), you can override the default junit RunListener with your own implementation. Method testStarted is executed before every test and you have access to class and methodName to be able to identify the running test. Dummy sample:
public class MyRunListener extends RunListener {
#Override
public void testStarted(Description description) throws Exception {
//...
Class testClass = description.getClass();
String methodName = description.getMethodName();
//...
}
}
Hope it helps.

How to run something after all the #Before's have happened?

We're using #Before's all along the hierarchy to get some test data inserted into the database before tests execute. I want to commit all that data to the database just before the #Test starts running.
One way to do this would be to commit the data as the last step in this test class' #Before method. But we have hundreds of such classes, and don't want to go in and modify all of those.
I've played with ExternalResource #Rule and TestWatcher #Rule...but they don't afford a way to hook in after all the #Before's have happened.
I'm thinking I need to look at building a custom TestRunner to do this.
Is that the right track?
What you are looking for, seems inconsistent to me. Settind some data and committing them are very close operations and shouldn't belong to different places. On the contrary, I would rather put them into one function and call it with actual parameters set to values you want to insert. Or use SQL strings as actual parameters. And call this finction from #Before
If you are insisting, there is no problem to do it. Create descendant classes for your Junit classes:
package ...;
import org.junit.Before;
public class NewAndBetterYourTest1 extends YourTest1 {
#Override
#Before
public void setUp() {
super.setUp(); // this is where you are setting everything.
makeCommits();
}
}
Only don't forget to launch these new tests
While you can't do quite what you are asking without a custom Runner, you could ensure that all of the data created in the #Before methods is committed with a Rule:
public class LocalDatabase extends ExternalResource {
private DataSource dataSource;
#Override
protected void before() {
dataSource = createLocalDatabase();
}
#Override
protected void after() {
try {
destoyLocalDatabase(dataSource);
} finally {
dataSource = null;
}
}
public void run(Callback callback) {
if (dataSource == null) {
throw new IllegalStateException("No DataSource");
}
Collection con = null;
try {
con = ds.getConnection(DB_USERNAME, PASSWORD);
callback.execute(con);
con.commit();
} finally {
if (con != null) con.close();
}
}
You can have this as a Rule in your base class:
public DatabaseTest {
#Rule
public LocalDatabase final localDatabase = new LocalDatabase();
}
And could could use it in a #Before method in any subclass
public UserDaoTest extends DatabaseTest {
#Before
public void populateInitialData() {
localDatabase.run(new Callback() {
#Override
public void execute(Connection con) {
...
}
});
}
...
}